Reformat code following spring-javaformat upgrade

This commit is contained in:
Phillip Webb 2023-02-21 22:49:23 -08:00
parent b93c9f7fec
commit df5898a146
1878 changed files with 27649 additions and 22403 deletions

View File

@ -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;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
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));
}
}

View File

@ -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<String> sourceJarTaskNames = sourceSets.stream().map(SourceSet::getSourcesJarTaskName)
.collect(Collectors.toSet());
Set<String> javadocJarTaskNames = sourceSets.stream().map(SourceSet::getJavadocJarTaskName)
.collect(Collectors.toSet());
Set<String> sourceJarTaskNames = sourceSets.stream()
.map(SourceSet::getSourcesJarTaskName)
.collect(Collectors.toSet());
Set<String> 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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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) {

View File

@ -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);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
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<String, String> 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<String, String> 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<Task> {

View File

@ -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

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class);
List<TaskProvider<PackageTangleCheck>> packageTangleChecks = new ArrayList<>();
for (SourceSet sourceSet : javaPluginExtension.getSourceSets()) {
TaskProvider<PackageTangleCheck> 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<PackageTangleCheck> 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()) {

View File

@ -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();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<File>) () -> new File(this.sourceSet.getOutput().getResourcesDir(),
"META-INF/spring.factories"))
.withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("spring.factories");
.file((Callable<File>) () -> new File(this.sourceSet.getOutput().getResourcesDir(),
"META-INF/spring.factories"))
.withPathSensitivity(PathSensitivity.RELATIVE)
.withPropertyName("spring.factories");
getInputs()
.file((Callable<File>) () -> 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<File>) () -> 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<String>) () -> 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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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> {
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<File>) task::getOutputFile), (artifact) -> artifact.builtBy(task));
project.getArtifacts()
.add(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME,
project.provider((Callable<File>) task::getOutputFile),
(artifact) -> artifact.builtBy(task));
});
});
}

View File

@ -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<ProhibitedHandler> action) {
@ -255,7 +258,7 @@ public class BomExtension {
public void dependencyVersions(Action<DependencyVersionsHandler> 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<Object> 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<String> 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);

View File

@ -60,8 +60,8 @@ public class BomPlugin implements Plugin<Project> {
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<Project> {
}
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<Project> {
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<Project> {
for (Node dependency : findChildren(dependencies, "dependency")) {
String groupId = findChild(dependency, "groupId").text();
String artifactId = findChild(dependency, "artifactId").text();
Set<String> 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<String> 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<Project> {
String groupId = findChild(dependency, "groupId").text();
String artifactId = findChild(dependency, "artifactId").text();
String version = findChild(dependency, "version").text();
Set<String> 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<String> 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<Project> {
@SuppressWarnings("unchecked")
private List<Node> findChildren(Node parent, String name) {
return (List<Node>) parent.children().stream().filter((child) -> isNodeWithName(child, name))
.collect(Collectors.toList());
return (List<Node>) parent.children()
.stream()
.filter((child) -> isNodeWithName(child, name))
.collect(Collectors.toList());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<String> 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<String> 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<String> exclusions = module.getExclusions()
.stream()
.map((exclusion) -> exclusion.getGroupId() + ":" + exclusion.getArtifactId())
.collect(Collectors.toSet());
Set<String> unused = new TreeSet<>();
for (String exclusion : exclusions) {
if (!resolved.contains(exclusion)) {

View File

@ -322,7 +322,7 @@ public class Library {
if (!line.startsWith("#")) {
String[] components = line.split(":");
Map<String, String> 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<String, String> 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));
}
}

View File

@ -51,7 +51,7 @@ public final class InteractiveUpgradeResolver implements UpgradeResolver {
librariesByName.put(library.getName(), library);
}
List<LibraryWithVersionOptions> libraryUpdates = this.libraryUpdateResolver
.findLibraryUpdates(librariesToUpgrade, librariesByName);
.findLibraryUpdates(librariesToUpgrade, librariesByName);
return libraryUpdates.stream().map(this::resolveUpgrade).filter(Objects::nonNull).collect(Collectors.toList());
}

View File

@ -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());
}

View File

@ -106,14 +106,19 @@ class StandardLibraryUpdateResolver implements LibraryUpdateResolver {
getLaterVersionsForModule(group.getId(), plugin, libraryVersion));
}
}
List<DependencyVersion> allVersions = moduleVersions.values().stream().flatMap(SortedSet::stream).distinct()
.filter((dependencyVersion) -> isPermitted(dependencyVersion, library.getProhibitedVersions()))
.collect(Collectors.toList());
List<DependencyVersion> 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<VersionOption> determineAlignedVersionOption(Library library, Map<String, Library> 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()) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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 + "'");

View File

@ -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<Milestone> milestones = repository.getMilestones();
java.util.Optional<Milestone> 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<Issue> 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<Upgrade> resolveUpgrades() {
List<Upgrade> 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<String> libraryPredicate = Pattern.compile(pattern).asPredicate();
List<Library> matchingLibraries = this.bom.getLibraries().stream()
.filter((library) -> libraryPredicate.test(library.getName())).collect(Collectors.toList());
List<Library> matchingLibraries = this.bom.getLibraries()
.stream()
.filter((library) -> libraryPredicate.test(library.getName()))
.collect(Collectors.toList());
if (matchingLibraries.isEmpty()) {
throw new InvalidUserDataException("No libraries matched '" + pattern + "'");
}

View File

@ -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);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<String, List<String>> getConflicts(List<Predicate<String>> 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<Predicate<String>> ignores) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<String> 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<String> 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) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<String> exclusions = dependency.getExcludeRules().stream().map(this::getId)
.collect(Collectors.toCollection(TreeSet::new));
TreeSet<String> 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<String> 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()) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2023 the original author 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(),

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
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<CheckAdditionalSpringConfigurationMetadata> 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<CheckSpringConfigurationMetadata> 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<RegularFile> 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));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<String> remaining = this.properties.stream().filter((property) -> !property.isDeprecated())
.map(ConfigurationProperty::getName).collect(Collectors.toSet());
Set<String> remaining = this.properties.stream()
.filter((property) -> !property.isDeprecated())
.map(ConfigurationProperty::getName)
.collect(Collectors.toSet());
for (Snippet snippet : this.snippets) {
Set<String> written = writeSnippet(outputDirectory, snippet, remaining);
remaining.removeAll(written);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<String, String> dependency = new HashMap<>();
dependency.put("path", ":spring-boot-project:spring-boot-devtools");
dependency.put("configuration", "propertyDefaults");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<String> expectedLogging = getProject().getObjects().property(String.class);
private final Property<String> applicationJar = getProject().getObjects().property(String.class)
.convention("/opt/apps/myapp.jar");
private final Property<String> applicationJar = getProject().getObjects()
.property(String.class)
.convention("/opt/apps/myapp.jar");
private final Map<String, String> 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();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<Parameter> parameters = mojo.getParameters().stream().filter(Parameter::isEditable)
.collect(Collectors.toList());
List<Parameter> requiredParameters = parameters.stream().filter(Parameter::isRequired)
.collect(Collectors.toList());
List<Parameter> parameters = mojo.getParameters()
.stream()
.filter(Parameter::isEditable)
.collect(Collectors.toList());
List<Parameter> 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<Parameter> optionalParameters = parameters.stream().filter((parameter) -> !parameter.isRequired())
.collect(Collectors.toList());
List<Parameter> optionalParameters = parameters.stream()
.filter((parameter) -> !parameter.isRequired())
.collect(Collectors.toList());
if (!optionalParameters.isEmpty()) {
writer.println();
writer.println();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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"));
});
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
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<Project> {
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<Project> {
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<Project> {
}
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<Project> {
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<Project> {
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<Project> {
@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<Project> {
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<Project> {
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;

View File

@ -111,10 +111,17 @@ class PluginXmlParser {
}
private String format(String input) {
return input.replace("<code>", "`").replace("</code>", "`").replace("&lt;", "<").replace("&gt;", ">")
.replace("<br>", " ").replace("\n", " ").replace("&quot;", "\"").replaceAll("\\{@code (.*?)}", "`$1`")
.replaceAll("\\{@link (.*?)}", "`$1`").replaceAll("\\{@literal (.*?)}", "`$1`")
.replaceAll("<a href=.\"(.*?)\".>(.*?)</a>", "$1[$2]");
return input.replace("<code>", "`")
.replace("</code>", "`")
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("<br>", " ")
.replace("\n", " ")
.replace("&quot;", "\"")
.replaceAll("\\{@code (.*?)}", "`$1`")
.replaceAll("\\{@link (.*?)}", "`$1`")
.replaceAll("\\{@literal (.*?)}", "`$1`")
.replaceAll("<a href=.\"(.*?)\".>(.*?)</a>", "$1[$2]");
}
private static final class IterableNodeList implements Iterable<Node> {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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())));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
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);
});
});
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<Starter> starters = this.starters.getFiles().stream().map(this::loadStarter)
.collect(Collectors.toCollection(TreeSet::new));
Set<Starter> 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));

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2023 the original author 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);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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> {
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())));
});
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
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<Project> {
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;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<File>) () -> this.sourceSet.getOutput().getResourcesDir())
.withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("resources");
.withPathSensitivity(PathSensitivity.RELATIVE)
.withPropertyName("resources");
getInputs().files((Callable<FileCollection>) () -> 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<File>) this::getOutputFile), (artifact) -> artifact.builtBy(this));
getProject().getArtifacts()
.add(testSliceMetadata.getName(), getProject().provider((Callable<File>) 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<String> 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<Path> 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<String> 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");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
@Override
public void apply(Project project) {
Provider<TestResultsOverview> testResultsOverview = project.getGradle().getSharedServices()
.registerIfAbsent("testResultsOverview", TestResultsOverview.class, (spec) -> {
});
project.getTasks().withType(Test.class,
(test) -> test.addTestListener(new FailureRecordingTestListener(testResultsOverview, test)));
Provider<TestResultsOverview> 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 {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<TestDescriptor> failureDescriptors) {
List<TestFailure> testFailures = failureDescriptors.stream().map(TestFailure::new).sorted()
.collect(Collectors.toList());
List<TestFailure> 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()));
});
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<Project> {
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) {

View File

@ -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<String, String> 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();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<NodeAssert> consumer) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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]]<<my.spring.test.prop,`+spring.test.prop.*+`>>" + NEWLINE
+ "|+++This is a description.+++" + NEWLINE + "|" + NEWLINE);
.isEqualTo("|[[my.spring.test.prop]]<<my.spring.test.prop,`+spring.test.prop.*+`>>" + NEWLINE
+ "|+++This is a description.+++" + NEWLINE + "|" + NEWLINE);
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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",

View File

@ -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));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2023 the original author 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) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author 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);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author 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<ResponseEntity<Object>> 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<String, Link> 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<String, Link> links = CloudFoundryWebFluxEndpointHandlerMapping.this.linksResolver
.resolveLinks(request.getURI().toString());
return new ResponseEntity<>(
Collections.singletonMap("_links", getAccessibleLinks(accessLevel, links)), HttpStatus.OK);
});
}
private Map<String, Link> getAccessibleLinks(AccessLevel accessLevel, Map<String, Link> 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<ResponseEntity<Object>> handle(ServerWebExchange exchange, Map<String, String> body) {
return this.securityInterceptor.preHandle(exchange, this.endpointId.toLowerCaseString())
.flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse));
.flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse));
}
private Mono<ResponseEntity<Object>> flatMapResponse(ServerWebExchange exchange, Map<String, String> body,

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<InfoContributor> infoContributors) {
List<InfoContributor> 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));

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<AccessLevel> 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<? extends Map<String, String>> 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<String, String> extractTokenKeys(Map<String, Object> response) {
@ -140,10 +148,14 @@ class ReactiveCloudFoundrySecurityService {
* @return the UAA url Mono
*/
Mono<String> 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;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author 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<Void> 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<Void> validateAlgorithm(Token token) {
@ -70,9 +72,9 @@ class ReactiveTokenValidator {
private Mono<Void> 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<String> 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<String, String> tokenKeys) {
@ -122,11 +126,12 @@ class ReactiveTokenValidator {
}
private Mono<Void> 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<Void> validateAudience(Token token) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<InfoContributor> infoContributors) {
List<InfoContributor> 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;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<String, Map<String, Link>> 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<String, Link> 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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<ConditionalOnAvailableEndpoint> conditionAnnotation = metadata.getAnnotations()
.get(ConditionalOnAvailableEndpoint.class);
.get(ConditionalOnAvailableEndpoint.class);
Class<?> target = getTarget(context, metadata, conditionAnnotation);
MergedAnnotation<Endpoint> 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,

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<E extends ExposableEndpoint<?>> 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

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<ExposableWebEndpoint> 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<Resource> 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);
}

View File

@ -99,7 +99,9 @@ public class WebFluxEndpointManagementContextConfiguration {
WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups groups) {
Collection<ExposableWebEndpoint> 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));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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<ExposableWebEndpoint> 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));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<ExposableWebEndpoint> 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));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<ExposableWebEndpoint> 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<Resource> 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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<String, DataSource> dataSources,
DataSourceHealthIndicatorProperties dataSourceHealthIndicatorProperties) {
if (dataSourceHealthIndicatorProperties.isIgnoreRoutingDataSources()) {
Map<String, DataSource> filteredDatasources = dataSources.entrySet().stream()
.filter((e) -> !(e.getValue() instanceof AbstractRoutingDataSource))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Map<String, DataSource> 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<DataSource, HealthContributor> contributorFunction) {
Map<String, DataSource> routedDataSources = routingDataSource.getResolvedDataSources().entrySet().stream()
.collect(Collectors.toMap((e) -> Objects.toString(e.getKey(), UNNAMED_DATASOURCE_KEY),
Map.Entry::getValue));
Map<String, DataSource> 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);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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"));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2023 the original author 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) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author 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);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2023 the original author 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;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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<DataSourcePoolMetadataProvider> 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<DataSourcePoolMetadataProvider> metadataProviders, MeterRegistry registry) {
String dataSourceName = getDataSourceName(beanName);
new DataSourcePoolMetrics(dataSource, metadataProviders, dataSourceName, Collections.emptyList())
.bindTo(registry);
.bindTo(registry);
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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);
}

View File

@ -232,8 +232,9 @@ public final class EndpointRequest {
}
private List<ServerWebExchangeMatcher> getDelegateMatchers(Set<String> 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<Object> 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) {

View File

@ -250,8 +250,9 @@ public final class EndpointRequest {
private List<RequestMatcher> getDelegateMatchers(RequestMatcherFactory requestMatcherFactory,
RequestMatcherProvider matcherProvider, Set<String> 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<Object> 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) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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."));

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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
* <code>&#064;Value(&quot;${local.management.port}&quot;)</code>.
*
* @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

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author 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());
}

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