diff --git a/applications/spring-shell/src/main/java/org/springframework/sbm/shell/ApplyShellCommand.java b/applications/spring-shell/src/main/java/org/springframework/sbm/shell/ApplyShellCommand.java index 4f1299acf..027f2734a 100644 --- a/applications/spring-shell/src/main/java/org/springframework/sbm/shell/ApplyShellCommand.java +++ b/applications/spring-shell/src/main/java/org/springframework/sbm/shell/ApplyShellCommand.java @@ -13,21 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * Copyright 2021 - 2022 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.springframework.sbm.shell; import lombok.RequiredArgsConstructor; diff --git a/components/openrewrite-spring-recipes/src/test/java/org/springframework/sbm/SpringBoot23To24MigrationTest.java b/components/openrewrite-spring-recipes/src/test/java/org/springframework/sbm/SpringBoot23To24MigrationTest.java index 5269b9ad0..5cee14690 100644 --- a/components/openrewrite-spring-recipes/src/test/java/org/springframework/sbm/SpringBoot23To24MigrationTest.java +++ b/components/openrewrite-spring-recipes/src/test/java/org/springframework/sbm/SpringBoot23To24MigrationTest.java @@ -27,7 +27,7 @@ import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.engine.recipe.Recipe; import org.springframework.sbm.engine.recipe.UserInteractions; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.parser.ProjectContextInitializer; import org.springframework.sbm.spring.migration.actions.InitDataSourceAfterJpaInitAction; import org.springframework.sbm.test.ProjectContextFileSystemTestSupport; diff --git a/components/recipe-test-support/src/main/java/org/springframework/sbm/test/ProjectContextFileSystemTestSupport.java b/components/recipe-test-support/src/main/java/org/springframework/sbm/test/ProjectContextFileSystemTestSupport.java index dbe8c2c97..35512fad3 100644 --- a/components/recipe-test-support/src/main/java/org/springframework/sbm/test/ProjectContextFileSystemTestSupport.java +++ b/components/recipe-test-support/src/main/java/org/springframework/sbm/test/ProjectContextFileSystemTestSupport.java @@ -21,7 +21,7 @@ import org.springframework.core.io.Resource; import org.springframework.sbm.engine.commands.ScanCommand; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.parser.ProjectContextInitializer; import java.io.IOException; diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/SbmCoreConfig.java b/components/sbm-core/src/main/java/org/springframework/sbm/SbmCoreConfig.java index 3cf338bf2..d2bc152b9 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/SbmCoreConfig.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/SbmCoreConfig.java @@ -16,11 +16,10 @@ package org.springframework.sbm; import org.openrewrite.ExecutionContext; -import org.openrewrite.InMemoryExecutionContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.scopes.annotations.ScanScope; import java.util.function.Supplier; diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/build/api/ApplicationModules.java b/components/sbm-core/src/main/java/org/springframework/sbm/build/api/ApplicationModules.java index 640e0acd4..41cb378f4 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/build/api/ApplicationModules.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/build/api/ApplicationModules.java @@ -17,14 +17,12 @@ import org.jetbrains.annotations.NotNull; import org.openrewrite.maven.tree.MavenResolutionResult; +import org.openrewrite.maven.tree.Scope; import org.springframework.sbm.build.impl.MavenBuildFileUtil; import org.springframework.sbm.build.impl.OpenRewriteMavenBuildFile; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -165,11 +163,40 @@ private boolean isDeclaredInProject(ParentDeclaration parentPomDeclaration) { private boolean noOtherPomDependsOn(BuildFile buildFile) { return !this.modules.stream() - .anyMatch(module -> module.getBuildFile().getRequestedDependencies().stream().anyMatch(d -> d.getCoordinates().equals(buildFile.getCoordinates()))); + .anyMatch(module -> module.getBuildFile().getRequestedDependencies().stream().anyMatch(d -> d.getGav().equals(buildFile.getCoordinates()))); } public boolean isSingleModuleApplication() { return modules.size() == 1; } + /** + * Find all modules with a declared dependency on the module with given GAV. + * @return modules that have a dependency to the given module and the scope of this dependency. + */ + public Map> findModulesWithDeclaredDependencyTo(String gav) { + Map> dependantModules = new HashMap<>(); + for (Module m : this.modules) { + Optional declaredDependency = m.getBuildFile().findRequestedDependency(gav); + if (declaredDependency.isPresent()) { + Dependency dependency = declaredDependency.get(); + String scopeStr = dependency.getScope(); + Scope scope = scopeStr != null ? Scope.valueOf(uppercaseFirstChar(scopeStr)) : Scope.Compile; + if(dependantModules.containsKey(scope)) { + dependantModules.get(scope).add(m); + } else { + List modules = new ArrayList<>(); + modules.add(m); + dependantModules.put(scope, modules); + } + } + } + return dependantModules; + } + + // TODO: provide in common util class + String uppercaseFirstChar(String name) { + if (name.isEmpty()) return name; + return Character.toUpperCase(name.charAt(0)) + name.substring(1); + } } diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/build/api/BuildFile.java b/components/sbm-core/src/main/java/org/springframework/sbm/build/api/BuildFile.java index 4e57ec4d7..507bdcd0c 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/build/api/BuildFile.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/build/api/BuildFile.java @@ -15,12 +15,14 @@ */ package org.springframework.sbm.build.api; +import org.openrewrite.maven.tree.ResolvedDependency; import org.openrewrite.maven.tree.Scope; import org.springframework.sbm.project.resource.ProjectResource; import java.nio.file.Path; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; @@ -40,6 +42,11 @@ public interface BuildFile extends ProjectResource { */ List getRequestedDependencies(); + /** + * Searches for a requested dependency matching the given GAV. + */ + Optional findRequestedDependency(String gav); + /** * Returns any available dependency (declared or transitive) with given scope. */ @@ -98,12 +105,18 @@ public interface BuildFile extends ProjectResource { List getResolvedDependenciesPaths(); + Map> getResolvedDependenciesMap(); + + /** + * Returns the classpath for given {@code scope}. + * target/classes and target/test-classes are included. + */ + Set getClasspath(Scope scope); + boolean hasPlugin(Plugin plugin); void addPlugin(Plugin plugin); - List getClasspath(); - List getSourceFolders(); List getTestSourceFolders(); @@ -176,4 +189,22 @@ public interface BuildFile extends ProjectResource { Optional findPlugin(String groupId, String artifactId); + /** + * Returns GAV of groupId:artifactId:version of this build file. + */ + default String getGav() { + return getGroupId() + ":" + getArtifactId() + ":" + getVersion(); + } + + /** + * Searches for the dependency matching the given gav. + */ + Optional findDeclaredDependency(String gav); + + /** + * Returns the declared dependency matching the given gav and throw exception if it doesn't exist. + * @throws IllegalStateException when no dependency with given gav exists. + */ + Dependency getDeclaredDependency(String gav); + } diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/build/api/DependenciesChangedEvent.java b/components/sbm-core/src/main/java/org/springframework/sbm/build/api/DependenciesChangedEvent.java index 2b6edc331..67b622a41 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/build/api/DependenciesChangedEvent.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/build/api/DependenciesChangedEvent.java @@ -15,15 +15,19 @@ */ package org.springframework.sbm.build.api; -import lombok.Getter; -import lombok.RequiredArgsConstructor; +import org.openrewrite.maven.tree.Scope; +import org.springframework.sbm.build.impl.OpenRewriteMavenBuildFile; import java.nio.file.Path; import java.util.List; +import java.util.Map; +import java.util.Set; -@RequiredArgsConstructor -@Getter -public class DependenciesChangedEvent { - - private final List resolvedDependencies; +/** + * Event published when new dependencies were added to a {@link BuildFile}. + * A listener can then use the information to recompile affected java source files. + * + * @author Fabian Krueger + */ +public record DependenciesChangedEvent(OpenRewriteMavenBuildFile openRewriteMavenBuildFile, Map> resolvedDependencies) { } diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/build/api/Dependency.java b/components/sbm-core/src/main/java/org/springframework/sbm/build/api/Dependency.java index 535ab20ef..aba4f9693 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/build/api/Dependency.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/build/api/Dependency.java @@ -17,6 +17,7 @@ import io.micrometer.core.lang.Nullable; import lombok.*; +import org.openrewrite.maven.tree.Scope; import org.openrewrite.semver.LatestRelease; import jakarta.validation.constraints.NotNull; @@ -99,7 +100,7 @@ private String tagString(String name, String value) { /** * @return the dependency coordinates as {@code 'groupId:artifactId:version'} */ - public String getCoordinates() { + public String getGav() { return getGroupId() + ":" + getArtifactId() + ":" + getVersion(); } @@ -125,4 +126,8 @@ public static Dependency fromCoordinates(String coordinate) { throw new IllegalArgumentException("Expected dependency in format groupid:artifactid[:version], but it is: " + coordinate); } } + + public String getEffectiveScope() { + return scope == null ? Scope.Compile.name() : scope; + } } diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/build/impl/OpenRewriteMavenBuildFile.java b/components/sbm-core/src/main/java/org/springframework/sbm/build/impl/OpenRewriteMavenBuildFile.java index 6b7e3ee5e..271b1ac37 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/build/impl/OpenRewriteMavenBuildFile.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/build/impl/OpenRewriteMavenBuildFile.java @@ -23,6 +23,7 @@ import org.openrewrite.marker.Markers; import org.openrewrite.maven.*; import org.openrewrite.maven.tree.*; +import org.openrewrite.xml.tree.Content; import org.openrewrite.xml.tree.Xml; import org.springframework.context.ApplicationEventPublisher; @@ -41,6 +42,7 @@ import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.sbm.parsers.RewriteMavenArtifactDownloader; import org.springframework.sbm.support.openrewrite.GenericOpenRewriteRecipe; +import org.springframework.util.Assert; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; @@ -78,7 +80,6 @@ public OpenRewriteMavenBuildFile(Path absoluteProjectPath, this.rewriteMavenArtifactDownloader = rewriteMavenArtifactDownloader; } - public OpenRewriteMavenBuildFile(Path projectRootDirectory, SourceFile maven, ApplicationEventPublisher eventPublisher, ExecutionContext executionContext, MavenBuildFileRefactoring refactoring, RewriteMavenArtifactDownloader rewriteMavenArtifactDownloader) { this(projectRootDirectory, cast(maven), eventPublisher, executionContext, refactoring, rewriteMavenArtifactDownloader); } @@ -124,11 +125,14 @@ protected List visit(List before, ExecutionContext ctx) .toList(); for (int i = 0; i < newMavenFiles.size(); i++) { - Optional mavenModels = MavenBuildFileUtil.findMavenResolution(mavenFiles.get(i)); Optional newMavenModels = MavenBuildFileUtil.findMavenResolution(newMavenFiles.get(i)); - mavenFiles.get(i).withMarkers(Markers.build(List.of(newMavenModels.get()))); - // FIXME: 497 verify correctness - mavenFiles.set(i, newMavenFiles.get(i)); + if(newMavenModels.isPresent()) { + mavenFiles.get(i).withMarkers(Markers.build(List.of(newMavenModels.get()))); + // FIXME: 497 verify correctness + mavenFiles.set(i, newMavenFiles.get(i)); + } else { + throw new IllegalArgumentException("Could not find MavenResolutionResult on %s.".formatted(newMavenFiles.get(i).getSourcePath().toString())); + } } sourceFiles = nonMavenFiles; @@ -143,12 +147,12 @@ public String toString() { } @Override - public String getDisplayName() { + public @NotNull String getDisplayName() { return "Refresh POM model"; } @Override - public String getDescription() { + public @NotNull String getDescription() { return getDisplayName(); } @@ -161,7 +165,11 @@ public void apply(Recipe recipe) { } public MavenResolutionResult getPom() { - return MavenBuildFileUtil.findMavenResolution(getSourceFile()).get(); + Optional mavenResolution = MavenBuildFileUtil.findMavenResolution(getSourceFile()); + if(mavenResolution.isEmpty()) { + throw new IllegalArgumentException("Could not find expected MavenResolutionResult for %s.".formatted(getSourceFile().getSourcePath().toString())); + } + return mavenResolution.get(); } public RewriteSourceFileHolder getResource() { @@ -172,7 +180,7 @@ public RewriteSourceFileHolder getResource() { public void addDependency(Dependency dependency) { if (!containsDependency(dependency)) { addDependencyInner(dependency); - eventPublisher.publishEvent(new DependenciesChangedEvent(getResolvedDependenciesPaths())); + eventPublisher.publishEvent(new DependenciesChangedEvent(this, getResolvedDependenciesMap())); } } @@ -196,7 +204,7 @@ private boolean containsDependency(Dependency dependency) { @Override public void addDependencies(List dependencies) { addDependenciesInner(dependencies); - eventPublisher.publishEvent(new DependenciesChangedEvent(getResolvedDependenciesPaths())); + eventPublisher.publishEvent(new DependenciesChangedEvent(this, getResolvedDependenciesMap())); } /** @@ -205,8 +213,24 @@ public void addDependencies(List dependencies) { @Override public boolean hasDeclaredDependencyMatchingRegex(String... dependencyPatterns) { return getDeclaredDependencies().stream() - .map(d -> d.getCoordinates()) - .anyMatch(dc -> Arrays.stream(dependencyPatterns).anyMatch(r -> dc.matches(r))); + .map(Dependency::getGav) + .anyMatch(dc -> Arrays.stream(dependencyPatterns).anyMatch(dc::matches)); + } + + /** + * {@inheritDoc} + */ + @Override + public Optional findDeclaredDependency(String gav) { + return this.getDeclaredDependencies().stream().filter(d -> d.getGav().equals(gav)).findFirst(); + } + + /** + * {@inheritDoc} + */ + @Override + public Dependency getDeclaredDependency(String gav) { + return findDeclaredDependency(gav).orElseThrow(() -> new IllegalStateException("Dependency with gav '%s' is not declared in pom file '%s'".formatted(gav, this.getSourcePath()))); } /** @@ -215,8 +239,8 @@ public boolean hasDeclaredDependencyMatchingRegex(String... dependencyPatterns) @Override public boolean hasEffectiveDependencyMatchingRegex(String... dependencyPatterns) { return getEffectiveDependencies().stream() - .map(d -> d.getCoordinates()) - .anyMatch(dc -> Arrays.stream(dependencyPatterns).anyMatch(r -> dc.matches(r))); + .map(Dependency::getGav) + .anyMatch(dc -> Arrays.stream(dependencyPatterns).anyMatch(dc::matches)); } @Override @@ -227,9 +251,7 @@ public boolean hasExactDeclaredDependency(Dependency dependency) { /** * Retrieve dependencies declared in buildfile with version and scope from dependency management if not explicitly declared. - * * Given this pom.xml and a call without any given `scope` parameter - * * [source,xml] * ---- * @@ -249,9 +271,7 @@ public boolean hasExactDeclaredDependency(Dependency dependency) { * * * ---- - * * a dependency `org.junit.jupiter:junit-jupiter:5.7.1` with scope `test` will be returned. - * * TODO: tests... * - with all scopes * - Managed versions with type and classifier given @@ -287,7 +307,7 @@ public List getRequestedDependencies() { List requestedDependencies = getPom().getPom().getRequestedDependencies(); // FIXME: #7 use getPom().getDependencies() instead ? List declaredDependenciesWithEffectiveVersions = requestedDependencies.stream() - .map(d -> mapDependency(d)) + .map(this::mapDependency) .map(d -> { if(d.getType() == null || d.getClassifier() == null || d.getVersion() == null) { @@ -302,7 +322,7 @@ public List getRequestedDependencies() { d.getScope() != null ? Scope.fromName(d.getScope()) : null ); if (dependencies.isEmpty()) { - // requested dependency from another module in this multi-module project won't be resolvable + // requested dependency from another module in this multimodule project won't be resolvable d.setGroupId(resolvedGroupId); d.setArtifactId(resolvedArtifactId); d.setVersion(resolvedVersion); @@ -331,6 +351,13 @@ public List getRequestedDependencies() { return declaredDependenciesWithEffectiveVersions; } + @Override + public Optional findRequestedDependency(String gav) { + return getRequestedDependencies().stream() + .filter(d -> d.getGav().equals(gav)) + .findFirst(); + } + /** * {@inheritDoc} * @@ -358,14 +385,14 @@ public Set getEffectiveDependencies() { .get(Scope.Provided) .stream() .map(d -> mapDependency(Scope.Provided, d)) - .forEach(d -> collect.add(d)); + .forEach(collect::add); getPom() .getDependencies() .get(Scope.Test) .stream() .map(d -> mapDependency(Scope.Test, d)) - .forEach(d -> collect.add(d)); + .forEach(collect::add); return collect; } @@ -373,13 +400,11 @@ public Set getEffectiveDependencies() { @Override public void removeDependencies(List dependencies) { removeDependenciesInner(dependencies); - - eventPublisher.publishEvent(new DependenciesChangedEvent(getResolvedDependenciesPaths())); + eventPublisher.publishEvent(new DependenciesChangedEvent(this, getResolvedDependenciesMap())); } /** * Removes all dependencies matching given regex. - * * Example: {@code "com\\.acme\\:artifact\\.id\\:.*"} matches all versions of {@code com.acme:artifact.id} * * @param regex varargs matching dependency coordinates `groupId:artifactId:version` @@ -387,16 +412,16 @@ public void removeDependencies(List dependencies) { @Override public void removeDependenciesMatchingRegex(String... regex) { List dependenciesMatching = getDeclaredDependencies().stream() - .filter(c -> Arrays.stream(regex).anyMatch(r -> c.getCoordinates().matches(r))) + .filter(c -> Arrays.stream(regex).anyMatch(r -> c.getGav().matches(r))) .collect(Collectors.toList()); removeDependenciesInner(dependenciesMatching); - eventPublisher.publishEvent(new DependenciesChangedEvent(getResolvedDependenciesPaths())); + eventPublisher.publishEvent(new DependenciesChangedEvent(this, getResolvedDependenciesMap())); } @Override public void addToDependencyManagement(Dependency dependency) { addToDependencyManagementInner(dependency); - eventPublisher.publishEvent(new DependenciesChangedEvent(getResolvedDependenciesPaths())); + eventPublisher.publishEvent(new DependenciesChangedEvent(this, getResolvedDependenciesMap())); } private org.springframework.sbm.build.api.Dependency mapDependency(org.openrewrite.maven.tree.Dependency d) { @@ -414,12 +439,21 @@ private org.springframework.sbm.build.api.Dependency mapDependency(org.openrewri return dependencyBuilder.build(); } + @NotNull private String resolveScope(String groupId, String artifactId, @Nullable String type, @Nullable String classifier) { Scope managedScope = getPom().getPom().getManagedScope(groupId, artifactId, type, classifier); return managedScope != null ? managedScope.name().toLowerCase() : "compile"; } private org.springframework.sbm.build.api.Dependency mapDependency(Scope scope, ResolvedDependency d) { + List dependencyExclusions = d.getRequested().getExclusions(); + List exclusions = new ArrayList<>(); + if(dependencyExclusions != null) { + exclusions = dependencyExclusions.stream() + .map(e -> Dependency.builder().groupId(e.getGroupId()).artifactId(e.getArtifactId()).build()) + .collect(Collectors.toList()); + } + return new Dependency( d.getGroupId(), d.getArtifactId(), @@ -427,13 +461,7 @@ private org.springframework.sbm.build.api.Dependency mapDependency(Scope scope, d.getType(), scope.name().toLowerCase(), d.getClassifier(), - d.getRequested().getExclusions() != null ? - d.getRequested().getExclusions() - .stream() - .map(e -> Dependency.builder().groupId(e.getGroupId()).artifactId(e.getArtifactId()).build()) - .collect(Collectors.toList()) - : - List.of() + exclusions ); } @@ -494,6 +522,7 @@ private void updateClasspathRegistry() { } private Recipe getAddDependencyRecipe(Dependency dependency) { + Assert.notNull(dependency.getVersion(), "The version of the Dependency that should be added was null."); AddDependencyVisitor addDependencyVisitor = new AddDependencyVisitor( dependency.getGroupId(), @@ -507,7 +536,7 @@ private Recipe getAddDependencyRecipe(Dependency dependency) { false, null); - return new GenericOpenRewriteRecipe(() -> addDependencyVisitor); + return new GenericOpenRewriteRecipe<>(() -> addDependencyVisitor); } public void removeDependenciesInner(List dependencies) { @@ -523,16 +552,13 @@ public void removeDependenciesInner(List dependencies) { private Recipe getDeleteDependencyVisitor(Dependency dependency) { // FIXME: Test that RemoveDependency considers scope - RemoveDependency v = new RemoveDependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getScope()); - return v; + return new RemoveDependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getScope()); } @Override public List getEffectiveDependencyManagement() { MavenResolutionResult pom = getPom(); - if (pom.getPom().getDependencyManagement() == null) { - return Collections.emptyList(); - } + pom.getPom().getDependencyManagement(); return pom.getPom().getDependencyManagement().stream() .map(this::getDependency) .distinct() @@ -588,7 +614,7 @@ public void addToDependencyManagementInner(Dependency dependency) { refreshPomModel(); } - private > void apply(Recipe recipe, RewriteSourceFileHolder resource) { + private void apply(Recipe recipe, RewriteSourceFileHolder resource) { refactoring.execute(resource, recipe); } // FIXME: #7 rework dependencies/classpath registry @@ -596,11 +622,35 @@ private > void apply(Recipe recipe, R // resolve classpath according to list of jar/pom @Override - public List getResolvedDependenciesPaths() { - return getPom().getDependencies().get(Scope.Provided).stream() - .filter(this::filterProjectDependencies) - .map(rd -> rewriteMavenArtifactDownloader.downloadArtifact(rd)) - .collect(Collectors.toList()); + public Map> getResolvedDependenciesMap() { + Map> dependenciesMap = new HashMap<>(); + Arrays.stream(Scope.values()).forEach(scope -> { + List resolvedDependencies = getPom().getDependencies().get(scope); + if(resolvedDependencies != null) { + Set paths = resolvedDependencies + .stream() + .map(rd -> rewriteMavenArtifactDownloader.downloadArtifact(rd)) + .collect(Collectors.toSet()); + dependenciesMap.put(scope, paths); + } + }); + return dependenciesMap; +// return getPom().getDependencies().get(Scope.Provided).stream() +//// .filter(this::filterProjectDependencies) +// .map(rd -> rewriteMavenArtifactDownloader.downloadArtifact(rd)) +// .collect(Collectors.toList()); +// return getPom().getDependencies(); + } + + @Override + public Set getClasspath(Scope scope) { + Map> resolvedDependenciesMap = getResolvedDependenciesMap(); + Set classpath = resolvedDependenciesMap.entrySet().stream() + .filter(e -> e.getKey().isInClasspathOf(scope)) + .map(e -> e.getValue()) + .flatMap(Set::stream) + .collect(Collectors.toSet()); + return classpath; } @NotNull @@ -617,11 +667,19 @@ public boolean hasPlugin(Plugin plugin) { .flatMap(b -> b.getChildren("plugin").stream()) .filter(p -> p.getChildren("groupId") != null && !p.getChildren("groupId").isEmpty()) .filter(p -> { - String groupId = ((Xml.CharData) p.getChildren("groupId").get(0).getContent().get(0)).getText(); + List groupId1 = p.getChildren("groupId").get(0).getContent(); + if(groupId1 == null) { + throw new IllegalStateException("Found 'groupId' element without content in file %s".formatted(getSourcePath().toString())); + } + String groupId = ((Xml.CharData) groupId1.get(0)).getText(); return plugin.getGroupId().equals(groupId); }) .filter(p -> { - String artifactId = ((Xml.CharData) p.getChildren("artifactId").get(0).getContent().get(0)).getText(); + List artifactId1 = p.getChildren("artifactId").get(0).getContent(); + if(artifactId1 == null) { + throw new IllegalStateException("Found 'artifactId' element without content in file %s".formatted(getSourcePath().toString())); + } + String artifactId = ((Xml.CharData) artifactId1.get(0)).getText(); return plugin.getArtifactId().equals(artifactId); }) .findFirst(); @@ -649,11 +707,9 @@ public List getTestResourceFolders() { } @Override - public List getClasspath() { - List classpath = new ArrayList<>(); - classpath.add(getSourceFile().getSourcePath().toAbsolutePath().getParent().resolve("target/classes")); - classpath.addAll(getResolvedDependenciesPaths()); - return classpath; + public List getResolvedDependenciesPaths() { + List dependenciesPaths = getResolvedDependenciesMap().values().stream().flatMap(Set::stream).toList(); + return dependenciesPaths; } @Override @@ -729,6 +785,9 @@ public boolean hasParent() { public void upgradeParentVersion(String version) { if (hasParent()) { @Nullable Parent parent = getPom().getPom().getRequested().getParent(); + if(parent == null) { + throw new IllegalStateException("Trying to upgrade parent version in '%s' failed, the parent does not exist and was null".formatted(getSourcePath())); + } apply( new UpgradeParentVersion(parent.getGroupId(), parent.getArtifactId(), version, null, List.of()) ); @@ -784,7 +843,7 @@ public void addPluginRepository(RepositoryDefinition repository) { public List getRepositories() { return getPom().getPom().getRepositories().stream() .map(r -> RepositoryDefinition.builder() - .id(r.getId()) + .id(Objects.requireNonNull(r.getId())) .url(r.getUri()) .releasesEnabled("true".equalsIgnoreCase(r.getReleases())) .snapshotsEnabled("true".equalsIgnoreCase(r.getSnapshots())) @@ -807,7 +866,7 @@ public List getPluginRepositories() { private boolean anyRegexMatchesCoordinate(Plugin p, String... regex) { String coordinate = p.getGroupId() + ":" + p.getArtifactId(); - return Stream.of(regex).anyMatch(r -> coordinate.matches(r)); + return Stream.of(regex).anyMatch(coordinate::matches); } @@ -826,7 +885,7 @@ public void removePluginsMatchingRegex(String... regex) { List coordinates = getPlugins().stream() .filter(p -> this.anyRegexMatchesCoordinate(p, regex)) .map(p -> p.getGroupId() + ":" + p.getArtifactId()) - .collect(Collectors.toList()); + .toList(); if (!coordinates.isEmpty()) { removePlugins(coordinates.toArray(new String[]{})); } @@ -834,7 +893,6 @@ public void removePluginsMatchingRegex(String... regex) { @Override public void removePlugins(String... coordinates) { - List removeMavenPlugins = new ArrayList<>(); List c = Arrays.asList(coordinates); Iterator iterator = c.iterator(); Recipe recipe; @@ -847,9 +905,11 @@ public void removePlugins(String... coordinates) { recipe.getRecipeList().add(new RemoveMavenPlugin(split[0], split[1])); } - List run = recipe.run(new InMemoryLargeSourceSet(List.of(getSourceFile())), executionContext).getChangeset().getAllResults(); + List sourceFile = List.of(getSourceFile()); + LargeSourceSet sourceSet = new InMemoryLargeSourceSet(sourceFile); + List run = recipe.run(sourceSet, executionContext).getChangeset().getAllResults(); if (!run.isEmpty()) { - replaceWith((Xml.Document) run.get(0).getAfter()); + replaceWith(run.get(0).getAfter()); } } @@ -862,6 +922,11 @@ public Optional findPlugin(String groupId, String artifactId){ .findAny(); } + @Override + public String getGav() { + return getPom().getPom().getGav().toString(); + } + private String resolve(String expression) { return getPom().getPom().getValue(expression); } diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/DependenciesChangedEventHandler.java b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/DependenciesChangedEventHandler.java index f522502f4..28900ded1 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/DependenciesChangedEventHandler.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/DependenciesChangedEventHandler.java @@ -15,57 +15,26 @@ */ package org.springframework.sbm.java.impl; -import org.openrewrite.ExecutionContext; -import org.openrewrite.SourceFile; -import org.springframework.sbm.build.api.DependenciesChangedEvent; -import org.springframework.sbm.engine.context.ProjectContextHolder; import lombok.RequiredArgsConstructor; -import org.openrewrite.Parser; -import org.openrewrite.java.tree.J; import org.springframework.context.event.EventListener; -import org.springframework.sbm.parsers.JavaParserBuilder; +import org.springframework.sbm.build.api.BuildFile; +import org.springframework.sbm.build.api.DependenciesChangedEvent; import org.springframework.stereotype.Component; -import java.io.ByteArrayInputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +/** + * Handles {@link DependenciesChangedEvent}s. + * The provided {@link BuildFile} allows to fin + * + * @author Fabian Krueger + */ @Component @RequiredArgsConstructor public class DependenciesChangedEventHandler { - private final ProjectContextHolder projectContextHolder; - private final JavaParserBuilder javaParserBuilder; - private final ExecutionContext executionContext; + private final DependencyChangeHandler dependencyChangedHandler; @EventListener public void onDependenciesChanged(DependenciesChangedEvent event) { - if (projectContextHolder.getProjectContext() != null) { - Set compilationUnitsSet = projectContextHolder.getProjectContext().getProjectJavaSources().stream() - .map(js -> js.getResource().getSourceFile()) - .map(js -> new Parser.Input(js.getSourcePath(), () -> new ByteArrayInputStream(js.printAll().getBytes(StandardCharsets.UTF_8)))) - .collect(Collectors.toSet()); - List compilationUnits = new ArrayList<>(compilationUnitsSet); - - Path projectRootDirectory = projectContextHolder.getProjectContext().getProjectRootDirectory(); - - Stream parsedCompilationUnits = javaParserBuilder.build().parseInputs(compilationUnits, null, executionContext); - // ((J.VariableDeclarations)parsedCompilationUnits.get(0).getClasses().get(0).getBody().getStatements().get(0)).getLeadingAnnotations().get(0).getType() - parsedCompilationUnits - .filter(J.CompilationUnit.class::isInstance) - .map(J.CompilationUnit.class::cast) - .forEach(cu -> { - projectContextHolder.getProjectContext().getProjectJavaSources().stream() - .filter(js -> js.getResource().getAbsolutePath().equals(projectRootDirectory.resolve(cu.getSourcePath()).normalize())) - .forEach(js -> js.getResource().replaceWith(cu)); - }); - } else { - throw new IllegalStateException("Could not get ProjectContext from ProjectContextHolder."); - } + dependencyChangedHandler.handleDependencyChanges(event.openRewriteMavenBuildFile()); } } diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/DependencyChangeHandler.java b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/DependencyChangeHandler.java new file mode 100644 index 000000000..5c6dae61a --- /dev/null +++ b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/DependencyChangeHandler.java @@ -0,0 +1,291 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.java.impl; + +import lombok.RequiredArgsConstructor; +import org.jetbrains.annotations.NotNull; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Parser; +import org.openrewrite.SourceFile; +import org.openrewrite.java.marker.JavaSourceSet; +import org.openrewrite.java.tree.J; +import org.openrewrite.maven.MavenExecutionContextView; +import org.openrewrite.maven.MavenSettings; +import org.openrewrite.maven.cache.LocalMavenArtifactCache; +import org.openrewrite.maven.tree.ResolvedDependency; +import org.openrewrite.maven.tree.Scope; +import org.openrewrite.maven.utilities.MavenArtifactDownloader; +import org.springframework.sbm.build.api.ApplicationModules; +import org.springframework.sbm.build.api.Module; +import org.springframework.sbm.build.impl.OpenRewriteMavenBuildFile; +import org.springframework.sbm.engine.context.ProjectContext; +import org.springframework.sbm.engine.context.ProjectContextHolder; +import org.springframework.sbm.java.api.JavaSource; +import org.springframework.sbm.parsers.JavaParserBuilder; +import org.springframework.sbm.parsers.SortedProjects; +import org.springframework.sbm.parsers.SourceFileParser; +import org.springframework.sbm.utils.JavaHelper; +import org.springframework.stereotype.Component; + +import java.io.ByteArrayInputStream; +import java.nio.file.Path; +import java.util.*; +import java.util.stream.Stream; + +/** + * @author Fabian Krüger + */ +@Component +@RequiredArgsConstructor +public class DependencyChangeHandler { + private final ProjectContextHolder projectContextHolder; + private final JavaParserBuilder javaParserBuilder; + private final ExecutionContext executionContext; + + private SourceFileParser sourceFileParser; + /** + * Handle changes of the dependency list in {@code currentBuildFile}. + * First the affected java sources in the module of the {@code currentBuildFile} are recompiled. + * It then recursively finds the modules depending on the current currentBuildFile and recompiles affected sources with the new classpath. + * + * @return + */ + public void handleDependencyChanges(OpenRewriteMavenBuildFile currentBuildFile) { + // TODO: use parser component here +// SortedProjects sortedProjects = new SortedProjects(); +// sourceFileParser.parseOtherSourceFiles( +// currentBuildFile.getAbsoluteProjectDir(), +// sortedProjects, +// pathToDocumentMap, +// resources, +// provenanceMarkers, +// styles, +// executionContext +// ); + + ProjectContext projectContext = projectContextHolder.getProjectContext(); + // create a mapping dependency -> dependant module information + Map> dependencyModuleMap = createDependencyToModuleMappings(projectContext.getApplicationModules()); + // track recompiled sources + List recompiledClasses = new ArrayList<>(); + // get current module + Module module = getModuleForBuildFile(currentBuildFile, projectContext); + // recompile module + List recompiledModuleClasses = recompileModuleClasses(module); + recompiledClasses.addAll(recompiledModuleClasses); + // recompile directly or transitively affected modules + List recompiledClassesFromAffectedModules = recompileAffectedModules(dependencyModuleMap, module); + recompiledClasses.addAll(recompiledClassesFromAffectedModules); + // update the wrapped SourceFiles + updateSourceFileHolder(projectContext, recompiledClasses); + } + + private static Module getModuleForBuildFile(OpenRewriteMavenBuildFile currentBuildFile, ProjectContext projectContext) { + return projectContext.getApplicationModules().findModule(currentBuildFile.getGav()).orElseThrow(() -> new IllegalStateException("Could not find Module for given build file %s".formatted(currentBuildFile.getSourcePath()))); + } + + private Map> createDependencyToModuleMappings(ApplicationModules applicationModules) { + Map> map = new HashMap<>(); + for(Module m : applicationModules.list()) { + m.getBuildFile().getDeclaredDependencies().forEach(d -> { + String scope = JavaHelper.uppercaseFirstChar(d.getEffectiveScope().toLowerCase()); + DependingModuleInfo moduleInfo = new DependingModuleInfo(d.getGav(), Scope.valueOf(scope), m); + map.computeIfAbsent(d.getGav(), k -> new ArrayList<>()).add(moduleInfo); + }); + } + return map; + } + + private void updateSourceFileHolder(ProjectContext projectContext, List recompiledClasses) { + List recompiledClassesPaths = recompiledClasses.stream() + .map(c -> projectContext.getProjectRootDirectory().resolve(c.getSourcePath().toString())) + .map(Path::toString) + .toList(); + + projectContext.getProjectResources().stream() + .forEach(r -> { + if(recompiledClassesPaths.contains(r.getAbsolutePath().toString())) { + int i = recompiledClassesPaths.indexOf(r.getAbsolutePath().toString()); + SourceFile sourceFile = recompiledClasses.get(i); + r.replaceWith(sourceFile); + } + }); + } + + private List recompileAffectedModules(Map> dependencyModuleMap, Module module) { + List recompiledSourceFiles = new ArrayList<>(); + recursivelyRecompileAffectedModules(dependencyModuleMap, module, recompiledSourceFiles); + return recompiledSourceFiles; + } + + private void recursivelyRecompileAffectedModules(Map> dependencyModuleMap, Module module, List recompiledSourceFiles) { + List affectedModules = dependencyModuleMap.getOrDefault(module.getBuildFile().getGav(), List.of()); + affectedModules.forEach(affectedModuleInfo -> { + Module affectedModule = affectedModuleInfo.module(); + recompiledSourceFiles.addAll(recompileModuleClasses(affectedModule)); + recursivelyRecompileAffectedModules(dependencyModuleMap, affectedModule, recompiledSourceFiles); + }); + } + + private List recompileModuleClasses(Module module) { + Map> resolvedDependenciesMap = module.getBuildFile().getResolvedDependenciesMap(); + Map> scopeListMap = flattenToCompileAndTestScope(resolvedDependenciesMap); + List mainSources = module.getMainJavaSourceSet().list().stream() + .map(ja -> new Parser.Input(ja.getAbsolutePath(), () -> new ByteArrayInputStream(ja.print().getBytes()))) + .toList(); + // FIXME: reuse logic from parser here. it must be guaranteed that markers are added + Set compileClasspath = scopeListMap.get(Scope.Compile); + List main = javaParserBuilder.classpath(compileClasspath).build().parseInputs(mainSources, module.getProjectRootDir(), executionContext).toList(); + JavaSourceSet javaSourceSet = module.getMainJavaSourceSet().list().get(0).getResource().getSourceFile().getMarkers().findFirst(JavaSourceSet.class).get(); + List testSources = module.getTestJavaSourceSet().list().stream() + .map(ja -> new Parser.Input(ja.getAbsolutePath(), () -> new ByteArrayInputStream(ja.print().getBytes()))) + .toList(); + List test = javaParserBuilder.classpath(scopeListMap.get(Scope.Test)).build().parseInputs(testSources, module.getProjectRootDir(), executionContext).toList(); + List result = new ArrayList<>(); + result.addAll(main); + result.addAll(test); + return result; + } + + void otherCode() { + +// replaceWrappedCompilationUnits(); +// +// // TODO: replace wrapped cu in RSFHs +// +// ProjectContext projectContext = projectContextHolder.getProjectContext(); +// if (projectContext != null) { +// Set compilationUnitsSet = projectContext.getProjectJavaSources().stream() +// .map(js -> js.getResource().getSourceFile()) +// .map(js -> new Parser.Input(js.getSourcePath(), () -> new ByteArrayInputStream(js.printAll().getBytes(StandardCharsets.UTF_8)))) +// .collect(Collectors.toSet()); +// List compilationUnits = new ArrayList<>(compilationUnitsSet); +// +// Path projectRootDirectory = projectContext.getProjectRootDirectory(); +// +// // recompile affected classes in all affected modules +// // get affected modules directly depending on changed module and recompile affected classes +// // now these modules provide a new classpath to the modules depending on the current module. +// // this ends when all modules were recompiled +// +// OpenRewriteMavenBuildFile currentBuildFile = event.openRewriteMavenBuildFile(); +// Map> resolvedDependencies = event.getResolvedDependencies(); +// parseDependantModules(projectContext, currentBuildFile, resolvedDependencies); +// +// +// event.resolvedDependencies().keySet().stream() +// .forEach(scope -> { +// OpenRewriteMavenBuildFile openRewriteMavenBuildFile = event.getOpenRewriteMavenBuildFile(); +// Map> modulesWithDependencyTo = projectContext.getApplicationModules().findModulesWithDeclaredDependencyTo(openRewriteMavenBuildFile.getGav()); +// modulesWithDependencyTo.keySet().stream() +// .forEach(s -> ); +// }); +// +// javaParserBuilder.classpath(); +// +// List parsedCompilationUnits = javaParserBuilder.parseInputs(compilationUnits, null, executionContext); +// // ((J.VariableDeclarations)parsedCompilationUnits.get(0).getClasses().get(0).getBody().getStatements().get(0)).getLeadingAnnotations().get(0).getType() +// parsedCompilationUnits.forEach(cu -> { +// projectContext.getProjectJavaSources().stream() +// .filter(js -> js.getResource().getAbsolutePath().equals(projectRootDirectory.resolve(cu.getSourcePath()).normalize())) +// .forEach(js -> js.getResource().replaceWith(cu)); +// }); +// } + } + +// private static void replaceWrappedCompilationUnits() { +// parsedCompilationUnits.forEach(cu -> { +// projectContext.getProjectJavaSources().stream() +// .filter(js -> js.getResource().getAbsolutePath().equals(projectRootDirectory.resolve(cu.getSourcePath()).normalize())) +// .forEach(js -> js.getResource().replaceWith(cu)); +// }); +// } + + private List compileModuleSources(List javaSources, List resolvedDependencies) { + // TODO: Create SBM wrapper bean for MavenArtifactDownloader in ScanScope during parsing and use it here + Path localRepo = Path.of(System.getProperty("user.home")).resolve(".m2/repository"); + MavenSettings mavenSettings = MavenExecutionContextView.view(executionContext).getSettings(); + MavenArtifactDownloader mavenArtifactDownloader = new MavenArtifactDownloader(new LocalMavenArtifactCache(localRepo), mavenSettings, error -> { + throw new RuntimeException(error); + }); + List classpath = resolvedDependencies.stream() + .map(mavenArtifactDownloader::downloadArtifact) + .toList(); + + List inputs = mapToParserInputs(javaSources); + + return javaParserBuilder.classpath(classpath).build().parseInputs(inputs, projectContextHolder.getProjectContext().getProjectRootDirectory(), executionContext) + .filter(J.CompilationUnit.class::isInstance) + .map(J.CompilationUnit.class::cast) + .toList(); + } + + private Map> boilDownEffectiveDependenciesToCompileAndTestScope(Map> effectiveDependencies) { + // FIXME: + return effectiveDependencies; + } +/* + private void parseDependantModules(ProjectContext projectContext, OpenRewriteMavenBuildFile currentBuildFile, Map> resolvedDependencies) { + Map> dependantModules = projectContext.getApplicationModules().findModulesWithDeclaredDependencyTo(currentBuildFile.getGav()); + Map> compileAndTestScopeDependencies = boilDownToCompileAndTestScope(resolvedDependencies); + dependantModules.stream().forEach(m -> { + + List compileScopeDependencies = compileAndTestScopeDependencies.get(Scope.Compile); + @Nullable Path relativeTo = projectContext.getProjectRootDirectory(); + if(!compileScopeDependencies.isEmpty()) { + List mainJavaSources = mapToParserInputs(m.getMainJavaSources()); + Stream compileScopeSourceFiles = javaParserBuilder.classpath(compileScopeDependencies).build().parseInputs(mainJavaSources, relativeTo, executionContext); + updateRewriteSourceFileHolders(projectContext, compileScopeSourceFiles); + } + + List testScopeDependencies = compileAndTestScopeDependencies.get(Scope.Test); + if(!testScopeDependencies.isEmpty()) { + List testJavaSources = mapToParserInputs(m.getTestJavaSources()); + Stream testScopeSourceFiles = javaParserBuilder.classpath(testScopeDependencies).build().parseInputs(testJavaSources, relativeTo, executionContext); + updateRewriteSourceFileHolders(projectContext, testScopeSourceFiles); + } + }); + } + */ + + @NotNull + private static List mapToParserInputs(List mainJavaSources1) { + List mainJavaSources = mainJavaSources1.stream() + .map(js -> new Parser.Input(js.getSourcePath(), () -> new ByteArrayInputStream(js.print().getBytes()))) + .toList(); + return mainJavaSources; + } + + private Map> flattenToCompileAndTestScope(Map> resolvedDependencies) { + Map> boiled = new HashMap<>(); + Arrays.stream(Scope.values()) + .forEach(scope -> { + Set paths = resolvedDependencies.get(scope); + if(paths != null) { + if(scope.isInClasspathOf(Scope.Compile)) { + boiled.computeIfAbsent(Scope.Compile, k -> new HashSet<>()).addAll(paths); + } + if(scope.isInClasspathOf(Scope.Test)) { + boiled.computeIfAbsent(Scope.Test, k -> new HashSet<>()).addAll(paths); + } + } + }); + return boiled; + } + + private record DependingModuleInfo(String gav, Scope scope, Module module) { + } +} diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java b/components/sbm-core/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java new file mode 100644 index 000000000..5004179a0 --- /dev/null +++ b/components/sbm-core/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java @@ -0,0 +1,45 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.parsers; + +import lombok.Getter; +import lombok.Setter; +import org.openrewrite.java.JavaParser; +import org.springframework.sbm.scopes.annotations.ScanScope; +import org.springframework.stereotype.Component; + +import java.util.function.Supplier; + +/** + * @author Fabian Krüger + */ +@Component +@ScanScope +public class JavaParserBuilder extends JavaParser.Builder{ + + @Getter + @Setter + private JavaParser.Builder builder; + + public Supplier getSupplier() { + return () -> builder; + } + + @Override + public JavaParser build() { + return builder.build(); + } +} diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/DependencyHelper.java b/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/DependencyHelper.java index e0aedd103..16dabaa6b 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/DependencyHelper.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/DependencyHelper.java @@ -22,6 +22,7 @@ import org.openrewrite.maven.internal.MavenParsingException; import org.openrewrite.maven.tree.*; import org.openrewrite.maven.utilities.MavenArtifactDownloader; +import org.springframework.stereotype.Component; import java.nio.file.Path; import java.nio.file.Paths; @@ -30,6 +31,7 @@ import java.util.stream.Collectors; @Slf4j +@Component public class DependencyHelper { public List downloadArtifacts(Consumer errorHandler, Set dependencies) { diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/MavenProjectParser.java b/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/MavenProjectParser.java index f2395eb4a..3b3e9378c 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/MavenProjectParser.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/MavenProjectParser.java @@ -38,6 +38,7 @@ import org.springframework.sbm.build.impl.MavenBuildFileUtil; import org.springframework.sbm.build.impl.RewriteMavenParser; import org.springframework.sbm.engine.events.*; +import org.springframework.sbm.parsers.RewriteMavenProjectParser; import org.springframework.sbm.parsers.RewriteProjectParser; import org.springframework.sbm.scopes.ProjectMetadata; import org.springframework.stereotype.Component; diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/RewriteMavenParserFactory.java b/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/RewriteMavenParserFactory.java index 253103056..32972754e 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/RewriteMavenParserFactory.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/RewriteMavenParserFactory.java @@ -19,7 +19,7 @@ import org.openrewrite.maven.cache.LocalMavenArtifactCache; import org.openrewrite.maven.cache.ReadOnlyLocalMavenArtifactCache; import org.openrewrite.maven.utilities.MavenArtifactDownloader; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import java.nio.file.Path; import java.nio.file.Paths; diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/properties/api/PropertiesSource.java b/components/sbm-core/src/main/java/org/springframework/sbm/properties/api/PropertiesSource.java index eb4940158..55050f6bd 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/properties/api/PropertiesSource.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/properties/api/PropertiesSource.java @@ -17,7 +17,6 @@ import org.openrewrite.ExecutionContext; import org.openrewrite.internal.InMemoryLargeSourceSet; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.sbm.properties.migration.recipes.AddProperty; import lombok.extern.slf4j.Slf4j; @@ -38,7 +37,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; // TODO: fcoi RewriteSourceFileHolder as member ?! @Slf4j diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/archfitfun/ExecutionScopeArchFitTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/archfitfun/ExecutionScopeArchFitTest.java index 571b1ccab..28c3dce15 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/archfitfun/ExecutionScopeArchFitTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/archfitfun/ExecutionScopeArchFitTest.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.openrewrite.ExecutionContext; import org.openrewrite.maven.MavenSettings; @@ -33,7 +32,10 @@ import org.springframework.sbm.engine.commands.ApplicableRecipeListCommand; import org.springframework.sbm.engine.commands.ApplyCommand; import org.springframework.sbm.engine.commands.ScanCommand; -import org.springframework.sbm.engine.context.*; +import org.springframework.sbm.engine.context.ProjectContext; +import org.springframework.sbm.engine.context.ProjectContextFactory; +import org.springframework.sbm.engine.context.ProjectContextSerializer; +import org.springframework.sbm.engine.context.ProjectRootPathResolver; import org.springframework.sbm.engine.git.GitSupport; import org.springframework.sbm.engine.git.ProjectSyncVerifier; import org.springframework.sbm.engine.precondition.PreconditionVerifier; @@ -100,13 +102,12 @@ * @author Fabian Krüger */ @Slf4j -@Disabled() @SpringBootTest(classes = { -// ScanScope.class, -// ExecutionScope.class, + ScanScope.class, + ExecutionScope.class, ScanCommand.class, ProjectRootPathResolver.class, -// PathScanner.class, + PathScanner.class, SbmApplicationProperties.class, ResourceHelper.class, PreconditionVerifier.class, @@ -114,21 +115,21 @@ ProjectContextFactory.class, ProjectResourceWrapperRegistry.class, ProjectResourceSetHolder.class, - ProjectContextHolder.class, JavaRefactoringFactoryImpl.class, BasePackageCalculator.class, JavaParserBuilder.class, -// RewriteParserConfiguration.class, -// RewriteProjectParser.class, -// ResourceParser.class, -// RewriteJsonParser.class, -// RewriteXmlParser.class, -// RewriteYamlParser.class, -// RewritePropertiesParser.class, -// RewritePlainTextParser.class, -// RewriteMavenParser.class, + RewriteParserConfiguration.class, + RewriteProjectParser.class, + ResourceParser.class, + RewriteJsonParser.class, + RewriteXmlParser.class, + RewriteYamlParser.class, + RewritePropertiesParser.class, + RewritePlainTextParser.class, + RewriteMavenParser.class, MavenSettingsInitializer.class, RewriteMigrationResultMerger.class, + RewriteMavenArtifactDownloader.class, JavaProvenanceMarkerFactory.class, MavenConfigHandler.class, RewriteSourceFileWrapper.class, @@ -145,9 +146,7 @@ ExecutionScopeArchFitTestContext.class, SbmSupportRewriteConfiguration.class }, - properties = { - "spring.main.allow-bean-definition-overriding=true", // required to provide custom ProjectMetadata - "debug=true"} + properties = "spring.main.allow-bean-definition-overriding=true" ) public class ExecutionScopeArchFitTest { public static final String TEST_RECIPE_NAME = "dummy-recipe"; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/archfitfun/ExecutionScopeArchFitTestContext.java b/components/sbm-core/src/test/java/org/springframework/sbm/archfitfun/ExecutionScopeArchFitTestContext.java index 75831c43d..c4dfdbbc0 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/archfitfun/ExecutionScopeArchFitTestContext.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/archfitfun/ExecutionScopeArchFitTestContext.java @@ -24,7 +24,7 @@ import org.springframework.sbm.engine.recipe.Action; import org.springframework.sbm.engine.recipe.Condition; import org.springframework.sbm.engine.recipe.Recipe; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.scopes.ProjectMetadata; import java.util.UUID; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java index 0ff27ed06..3a4cc2a08 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java @@ -25,7 +25,8 @@ import org.openrewrite.ExecutionContext; import org.springframework.sbm.SbmCoreConfig; import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.java.OpenRewriteTestSupport; +import org.springframework.sbm.parsers.RewriteExecutionContext; import static com.tngtech.archunit.lang.conditions.ArchConditions.notBe; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; @@ -47,12 +48,12 @@ public class ControlledInstantiationOfExecutionContextTest { )) ) ) - .andShould() - .notBe(classWithPermissionToCreateExecutionContext) - .andShould() - .notBe(SbmCoreConfig.class) - .andShould() - .notBe(RewriteExecutionContext.class) + .andShould( + notBe(classWithPermissionToCreateExecutionContext) + .and(notBe(SbmCoreConfig.class)) + .and(notBe(RewriteExecutionContext.class)) + .and(notBe(OpenRewriteTestSupport.class)) + ); ; } diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/build/api/ApplicationModulesTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/build/api/ApplicationModulesTest.java index b0c992427..32f389520 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/build/api/ApplicationModulesTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/build/api/ApplicationModulesTest.java @@ -17,11 +17,14 @@ import org.intellij.lang.annotations.Language; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.openrewrite.maven.tree.Scope; import org.springframework.sbm.project.resource.TestProjectContext; import java.nio.file.Path; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.stream.Stream; @@ -163,6 +166,13 @@ void componentModule() { assertThat(applicationModule.getModulePath()).isEqualTo(Path.of("module1")); assertThat(applicationModule.getBuildFile().getCoordinates()).isEqualTo("org.example:module1:1.0-SNAPSHOT"); } + + @Test + @DisplayName("should return depending modules") + void shouldReturnDependingModules() { + Map> modulesWithDeclaredDependencyTo = sut.findModulesWithDeclaredDependencyTo("org.example:module2:1.0-SNAPSHOT"); + assertThat(modulesWithDeclaredDependencyTo.containsKey(Scope.Compile)).isTrue(); + } // TODO: add test for getTopmostApplicationModules with packaging != jar diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/build/api/SpringManagedDependenciesTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/build/api/SpringManagedDependenciesTest.java index bf648e82a..fd91c2aea 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/build/api/SpringManagedDependenciesTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/build/api/SpringManagedDependenciesTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; import org.openrewrite.ExecutionContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import static org.assertj.core.api.Assertions.assertThat; @@ -31,7 +31,7 @@ public void pullBootStarter274Dependencies_expectJakartaAnnotationDependency(){ assertThat(SpringManagedDependencies.by("org.springframework.boot", "spring-boot-starter", "2.7.4", executionContext) .stream() - .map(Dependency::getCoordinates) + .map(Dependency::getGav) .anyMatch(jakartaCoordinates::equals) ).isTrue(); } diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/build/impl/MavenSettingsInitializerTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/build/impl/MavenSettingsInitializerTest.java index efb00fa8b..21c46bb27 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/build/impl/MavenSettingsInitializerTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/build/impl/MavenSettingsInitializerTest.java @@ -18,7 +18,7 @@ import org.junit.jupiter.api.*; import org.openrewrite.maven.MavenExecutionContextView; import org.openrewrite.maven.tree.MavenRepository; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import java.net.URI; import java.net.URISyntaxException; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/build/migration/actions/BumpParentPomVersionTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/build/migration/actions/BumpParentPomVersionTest.java index 2994f61fa..736d10c21 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/build/migration/actions/BumpParentPomVersionTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/build/migration/actions/BumpParentPomVersionTest.java @@ -80,7 +80,7 @@ void bumpVersion() { sut.setToVersion("2.7.0"); sut.apply(context); - assertThat(context.getBuildFile().getParentPomDeclaration().get().getVersion()).isEqualTo("2.7.0"); + assertThat(context.getApplicationModules().getRootModule().getBuildFile().getParentPomDeclaration().get().getVersion()).isEqualTo("2.7.0"); } @Test diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/build/migration/actions/RemoveManagedDependenciesTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/build/migration/actions/RemoveManagedDependenciesTest.java index 5f54d4b04..21f8bd16d 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/build/migration/actions/RemoveManagedDependenciesTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/build/migration/actions/RemoveManagedDependenciesTest.java @@ -43,7 +43,7 @@ public void givenProjectWithManagedDependency_removeSpringManagedDependencies_ex .verify(projectContext -> assertThat(projectContext.getBuildFile() .getDeclaredDependencies() .stream() - .map(Dependency::getCoordinates) + .map(Dependency::getGav) .anyMatch(hibernateCoordinates::equals)).isFalse() ); @@ -64,7 +64,7 @@ public void givenProjectWithLowerVersionedManagedDependency_removeSpringManagedD assertThat(projectContext.getBuildFile() .getDeclaredDependencies() .stream() - .map(Dependency::getCoordinates) + .map(Dependency::getGav) .anyMatch(hibernateCoordinates::equals) ).isFalse(); } @@ -90,7 +90,7 @@ public void givenProjectWithSameVersionedManagedDependency_removeSpringManagedDe // dependency to older hibernate was removed assertThat(declaredDependencies .get(0) - .getCoordinates()) + .getGav()) .isEqualTo(springBootDataJpaCoordinates); }); } @@ -117,11 +117,11 @@ public void givenProjectWithHigherVersionedManagedDependency_removeSpringManaged assertThat(declaredDependencies.size()).isEqualTo(2); assertThat(declaredDependencies .get(0) - .getCoordinates()) + .getGav()) .isEqualTo(hibernateCoordinates); assertThat(declaredDependencies .get(1) - .getCoordinates()) + .getGav()) .isEqualTo(springBootDataJpaCoordinates); }); } diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/build/util/PomBuilder.java b/components/sbm-core/src/test/java/org/springframework/sbm/build/util/PomBuilder.java index de5f9c17c..0b630a352 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/build/util/PomBuilder.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/build/util/PomBuilder.java @@ -17,12 +17,7 @@ import org.springframework.sbm.project.parser.DependencyHelper; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; import com.fasterxml.jackson.core.JsonProcessingException; @@ -40,7 +35,7 @@ public class PomBuilder { private String parent; private String artifactId; private Map properties = new HashMap<>(); - private Map dependencies = new LinkedHashMap(); + private Map> dependencies = new LinkedHashMap<>(); private List plugins = new ArrayList<>(); private DependencyHelper dependencyHelper = new DependencyHelper(); @@ -88,6 +83,7 @@ public static PomBuilder buildRootWithParent(String parentCoordinate, String pom * @param moduleArtifactNames one or more module artifactIds */ public PomBuilder withModules(String... moduleArtifactNames) { + this.packaging = "pom"; this.modules = Arrays.asList(moduleArtifactNames); if(this.modules.stream().anyMatch(m -> m.contains(":"))) throw new RuntimeException("Found ':' in artifact name but artifact names of modules must not be provided as coordinate."); return this; @@ -174,11 +170,11 @@ String buildProperties(Map properties) { } } - String renderDependencies(Map dependencies) { + String renderDependencies(Map> dependencies) { StringBuilder dependenciesSection = new StringBuilder(); dependenciesSection.append(" ").append("").append("\n"); dependencies.entrySet().forEach(e -> { - renderDependency(dependenciesSection, e.getKey(), e.getValue()); + e.getValue().forEach(dep -> renderDependency(dependenciesSection, e.getKey(), dep)); }); dependenciesSection.append(" ").append("").append("\n"); String dependenciesText = dependenciesSection.toString(); @@ -261,21 +257,21 @@ public PomBuilder packaging(String type) { public PomBuilder unscopedDependencies(String... coordinates) { dependencyHelper.mapCoordinatesToDependencies(Arrays.asList(coordinates)) .stream() - .forEach(c -> this.dependencies.put(Scope.None, c)); + .forEach(dep -> this.dependencies.computeIfAbsent(Scope.None, r -> new HashSet<>()).add(dep)); return this; } public PomBuilder compileScopeDependencies(String... coordinates) { dependencyHelper.mapCoordinatesToDependencies(Arrays.asList(coordinates)) .stream() - .forEach(c -> this.dependencies.put(Scope.Compile, c)); + .forEach(dep -> this.dependencies.computeIfAbsent(Scope.Compile, r -> new HashSet<>()).add(dep)); return this; } public PomBuilder testScopeDependencies(String... coordinates) { dependencyHelper.mapCoordinatesToDependencies(Arrays.asList(coordinates)) .stream() - .forEach(c -> this.dependencies.put(Scope.Test, c)); + .forEach(dep -> this.dependencies.computeIfAbsent(Scope.Test, r -> new HashSet<>()).add(dep)); return this; } diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/engine/recipe/OpenRewriteDeclarativeRecipeAdapterIntegrationTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/engine/recipe/OpenRewriteDeclarativeRecipeAdapterIntegrationTest.java index 9dbb61e2e..13164711f 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/engine/recipe/OpenRewriteDeclarativeRecipeAdapterIntegrationTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/engine/recipe/OpenRewriteDeclarativeRecipeAdapterIntegrationTest.java @@ -20,7 +20,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.RewriteSourceFileWrapper; import org.springframework.sbm.project.resource.ResourceHelper; import org.springframework.sbm.project.resource.TestProjectContext; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/engine/recipe/OpenRewriteNamedRecipeAdapterIntegrationTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/engine/recipe/OpenRewriteNamedRecipeAdapterIntegrationTest.java index a1fd15d8e..c6bb48f40 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/engine/recipe/OpenRewriteNamedRecipeAdapterIntegrationTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/engine/recipe/OpenRewriteNamedRecipeAdapterIntegrationTest.java @@ -21,7 +21,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.RewriteSourceFileWrapper; import org.springframework.sbm.project.resource.ResourceHelper; import org.springframework.sbm.project.resource.TestProjectContext; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/ClasspathRegistryTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/ClasspathRegistryTest.java index 94424d38d..61e5103a9 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/ClasspathRegistryTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/ClasspathRegistryTest.java @@ -24,7 +24,7 @@ import org.openrewrite.xml.tree.Xml; import org.springframework.sbm.build.impl.MavenSettingsInitializer; import org.springframework.sbm.build.impl.RewriteMavenParser; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import java.util.List; import java.util.Set; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/DependencyChangeHandlerTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/DependencyChangeHandlerTest.java new file mode 100644 index 000000000..a6750ce95 --- /dev/null +++ b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/DependencyChangeHandlerTest.java @@ -0,0 +1,97 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.java.impl; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.sbm.build.api.BuildFile; +import org.springframework.sbm.build.api.Dependency; +import org.springframework.sbm.build.impl.OpenRewriteMavenBuildFile; +import org.springframework.sbm.build.util.PomBuilder; +import org.springframework.sbm.engine.context.ProjectContext; +import org.springframework.sbm.engine.context.ProjectContextHolder; +import org.springframework.sbm.parsers.RewriteExecutionContext; +import org.springframework.sbm.parsers.JavaParserBuilder; +import org.springframework.sbm.project.resource.TestProjectContext; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * @author Fabian Krüger + */ +class DependencyChangeHandlerTest { + @Test + @DisplayName("Adding a dependency Should recompile affected modules") + void shouldRecompileAffectedModules() { + String parentPom = PomBuilder.buildPom("com.example:parent:1.0") + .withModules("a", "b", "c") + .build(); + // a -> b + String aPom = PomBuilder.buildPom("com.example:parent:1.0", "a") + .compileScopeDependencies("com.example:b:1.0") + .build(); + + String bPom = PomBuilder.buildPom("com.example:parent:1.0", "b") + .build(); + + String cPom = PomBuilder.buildPom("com.example:parent:1.0", "c") + .build(); + + ProjectContext projectContext = TestProjectContext.buildProjectContext() + .withProjectResource("pom.xml", parentPom) + .withProjectResource("a/pom.xml", aPom) + .withJavaSource("a/src/main/java", + """ + package com.example.a; + import com.example.b.BModuleClass; + + public class AModuleClass { + private BModuleClass b; + } + """) + .withJavaSource("a/src/test/java", + """ + package com.example.a; + + public class AModuleClassTest { + private AModuleClass a; + } + """) + .withProjectResource("b/pom.xml", bPom) + .withJavaSource("b/src/main/java", + """ + package com.example.b; + + public class BModuleClass { + } + """) + .withProjectResource("c/pom.xml", cPom) + .build(); + + ProjectContextHolder projectContextHolder = new ProjectContextHolder(); + projectContextHolder.setProjectContext(projectContext); + BuildFile buildFile = projectContext.getApplicationModules().getModule("c").getBuildFile(); + buildFile.addDependency(Dependency.builder() + .groupId("javax.validation") + .artifactId("validation-api") + .version("2.0.1.Final") + .scope("Test") + .build() + ); + DependencyChangeHandler sut = new DependencyChangeHandler(projectContextHolder, new JavaParserBuilder(), new RewriteExecutionContext()); + sut.handleDependencyChanges((OpenRewriteMavenBuildFile) buildFile); + } +} \ No newline at end of file diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/OpenRewriteMemberTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/OpenRewriteMemberTest.java index 95d012302..411d64e60 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/OpenRewriteMemberTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/OpenRewriteMemberTest.java @@ -15,13 +15,18 @@ */ package org.springframework.sbm.java.impl; +import org.openrewrite.java.marker.JavaSourceSet; +import org.openrewrite.java.tree.JavaType; import org.springframework.sbm.java.api.JavaSource; import org.springframework.sbm.java.api.Member; import org.springframework.sbm.engine.context.ProjectContext; +import org.springframework.sbm.java.api.Type; import org.springframework.sbm.project.resource.TestProjectContext; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; class OpenRewriteMemberTest { @@ -78,25 +83,49 @@ void testHasAnnotationWithDependency() { @Test void testAddMemberAnnotation() { - final String sourceCode = - "package com.foo;\n" + - "public class Class1 {\n" + - " private String var1;\n" + - " private String var2;\n" + - "}"; - ProjectContext projectContext = TestProjectContext.buildProjectContext() .withBuildFileHavingDependencies("javax.validation:validation-api:2.0.1.Final") - .withJavaSources(sourceCode) + .withJavaSources( + """ + package com.foo; + public class Class1 { + private String var1; + private String var2; + } + """ + ) .build(); + // find Class1 JavaSource javaSource = projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.foo.Class1").get(); - javaSource.getTypes().get(0).getMembers().get(0).addAnnotation("javax.validation.constraints.Min"); + // Precondition: javax.validation.constraints.Min on classpath + List classpath = javaSource.getResource().getSourceFile() + .getMarkers() + .findFirst(JavaSourceSet.class) + .get() + .getClasspath() + .stream() + .map(JavaType.FullyQualified::getFullyQualifiedName) + .toList(); + + String minAnnotation = "javax.validation.constraints.Min"; + + assertThat(classpath).contains(minAnnotation); + + // add annotation + Type type = javaSource.getTypes().get(0); + type.getMembers().get(0).addAnnotation(minAnnotation); + + boolean isTypeInUse = ((OpenRewriteJavaSource)javaSource).getSourceFile().getTypesInUse().getTypesInUse().stream() + .anyMatch(t -> ((JavaType.FullyQualified)t).getFullyQualifiedName().equals(minAnnotation)); + assertThat(isTypeInUse).isTrue(); + + // correct import added assertThat(javaSource.getImports()).hasSize(1); - assertThat(javaSource.hasImportStartingWith("javax.validation.constraints.Min")).isTrue(); - assertThat(javaSource.getTypes().get(0).getMembers().get(0).getAnnotation("javax.validation.constraints.Min")).isNotNull(); - assertThat(javaSource.getTypes().get(0).getMembers().get(1).getAnnotation("javax.validation.constraints.Min")).isNull(); + assertThat(javaSource.hasImportStartingWith(minAnnotation)).isTrue(); + assertThat(type.getMembers().get(0).getAnnotation(minAnnotation)).isNotNull(); + assertThat(type.getMembers().get(1).getAnnotation(minAnnotation)).isNull(); } @Test diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/OpenRewriteSearchAndCommentTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/OpenRewriteSearchAndCommentTest.java index d547557c7..5c4a3b2e0 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/OpenRewriteSearchAndCommentTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/OpenRewriteSearchAndCommentTest.java @@ -19,7 +19,7 @@ import org.openrewrite.internal.InMemoryLargeSourceSet; import org.openrewrite.java.JavaParser; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.Test; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/ProjectJavaSourcesImplTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/ProjectJavaSourcesImplTest.java index 3b421dc5a..1b09ba9dc 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/ProjectJavaSourcesImplTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/ProjectJavaSourcesImplTest.java @@ -20,6 +20,7 @@ import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.java.api.JavaSourceAndType; +import org.springframework.sbm.parsers.MavenExecutionResultException; import org.springframework.sbm.project.resource.TestProjectContext; import java.util.List; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/RewriteJavaParserTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/RewriteJavaParserTest.java index 7737fcfc2..a5d422c3f 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/RewriteJavaParserTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/java/impl/RewriteJavaParserTest.java @@ -23,7 +23,7 @@ import org.openrewrite.java.tree.J; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.SbmApplicationProperties; import java.io.ByteArrayOutputStream; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/java/migration/conditions/HasMemberAnnotationTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/java/migration/conditions/HasMemberAnnotationTest.java index 862eda79f..3ec5232d1 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/java/migration/conditions/HasMemberAnnotationTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/java/migration/conditions/HasMemberAnnotationTest.java @@ -16,6 +16,8 @@ package org.springframework.sbm.java.migration.conditions; import org.openrewrite.java.marker.JavaSourceSet; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.JavaType; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.Test; @@ -42,11 +44,18 @@ class AnnotatedClass { .withBuildFileHavingDependencies("javax.validation:validation-api:2.0.1.Final") .build(); - boolean isTypeResolved = context.getProjectJavaSources().list().get(0).getResource().getSourceFile().getMarkers().findFirst(JavaSourceSet.class).get().getClasspath().stream().map(fq -> fq.getFullyQualifiedName()).anyMatch(fq -> fq.startsWith("javax.validation")); + J.CompilationUnit sourceFile = context.getProjectJavaSources().list().get(0).getResource().getSourceFile(); + boolean isTypeResolved = sourceFile.getMarkers().findFirst(JavaSourceSet.class).get().getClasspath().stream().map(fq -> fq.getFullyQualifiedName()).anyMatch(fq -> fq.startsWith("javax.validation")); assertThat(isTypeResolved).isTrue(); + + String annotation = "javax.validation.constraints.Min"; HasMemberAnnotation sut = new HasMemberAnnotation(); - sut.setAnnotation("javax.validation.constraints.Min"); + sut.setAnnotation(annotation); + + boolean isTypeInUse = sourceFile.getTypesInUse().getTypesInUse().stream() + .anyMatch(t -> ((JavaType.FullyQualified)t).getFullyQualifiedName().equals(annotation)); + assertThat(isTypeInUse).isTrue(); assertThat(sut.evaluate(context)).isTrue(); } diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/AddDependencyTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/AddDependencyTest.java index 8a10e98bc..8a012269e 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/AddDependencyTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/AddDependencyTest.java @@ -17,28 +17,50 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.*; +import org.openrewrite.ExecutionContext; +import org.openrewrite.RecipeRun; +import org.openrewrite.SourceFile; +import org.openrewrite.internal.InMemoryLargeSourceSet; +import org.openrewrite.java.ChangeType; import org.openrewrite.java.JavaParser; +import org.openrewrite.java.marker.JavaSourceSet; +import org.openrewrite.java.tree.J; import org.openrewrite.java.tree.JavaType; +import org.openrewrite.maven.tree.MavenResolutionResult; +import org.openrewrite.maven.tree.ResolvedDependency; import org.openrewrite.maven.tree.Scope; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationEventPublisher; +import org.springframework.sbm.SbmCoreConfig; +import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; import org.springframework.sbm.build.api.BuildFile; import org.springframework.sbm.build.api.Dependency; +import org.springframework.sbm.build.impl.RewriteMavenParser; +import org.springframework.sbm.build.util.PomBuilder; import org.springframework.sbm.engine.context.ProjectContext; +import org.springframework.sbm.engine.context.ProjectContextFactory; import org.springframework.sbm.engine.context.ProjectContextHolder; +import org.springframework.sbm.java.api.JavaSource; import org.springframework.sbm.java.impl.ClasspathRegistry; import org.springframework.sbm.java.impl.DependenciesChangedEventHandler; -import org.springframework.sbm.java.impl.RewriteJavaParser; +import org.springframework.sbm.java.impl.DependencyChangeHandler; +import org.springframework.sbm.parsers.JavaParserBuilder; +import org.springframework.sbm.project.parser.DependencyHelper; +import org.springframework.sbm.project.parser.ProjectContextInitializer; +import org.springframework.sbm.project.resource.ProjectResourceWrapperRegistry; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; +import org.springframework.sbm.scopes.ExecutionScope; +import org.springframework.sbm.scopes.ScanScope; +import org.springframework.sbm.test.TestProjectContextInfo; import org.springframework.test.util.ReflectionTestUtils; import java.nio.file.Path; -import java.util.HashMap; -import java.util.Optional; +import java.util.*; +import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; @@ -47,13 +69,20 @@ * * @author Fabian Krüger */ -@SpringBootTest(classes ={ +@SpringBootTest(classes = { + SbmCoreConfig.class, + ScopeConfiguration.class, + ExecutionScope.class, + ScanScope.class, DependenciesChangedEventHandler.class, + DependencyChangeHandler.class, ProjectContextHolder.class, - RewriteJavaParser.class, - SbmApplicationProperties.class + JavaParserBuilder.class, + SbmApplicationProperties.class, + ProjectContextInitializer.class, + ProjectContextFactory.class, + ProjectResourceWrapperRegistry.class }) -@Disabled("See comment in test") public class AddDependencyTest { @Autowired @@ -66,35 +95,403 @@ public class AddDependencyTest { ProjectContextHolder contextHolder; @Autowired - RewriteJavaParser rewriteJavaParser; + JavaParserBuilder javaParserBuilder; + + @Autowired + ConfigurableListableBeanFactory beanFactory; + + @Autowired + ExecutionContext executionContext; /** - * Test that after adding a dependency... * - * * The ClasspathRegistry was updated - * * The types are in the type cache of encapsulated JavaParser - * * The new types can be resolved + */ + @Test + @DisplayName("type from dependency is accessible") + void typeFromDependencyIsAccessible() { + String javacode = + """ + package com.acme; + import javax.validation.constraints.Email; + class SomeClass { + @Email + String someMember; + } + """; + ProjectContext context = TestProjectContext + .buildProjectContext(beanFactory) + .withBuildFileHavingDependencies("javax.validation:validation-api:2.0.1.Final") + .withJavaSource("src/main/java", javacode) + .build(); + + String fullyQualifiedName = context.getProjectJavaSources().list().get(0).getTypes().get(0).getMembers().get(0).getAnnotations() + .get(0) + .getFullyQualifiedName(); + + assertThat(fullyQualifiedName).isEqualTo("javax.validation.constraints.Email"); + } + + @Test + @DisplayName("Compile should make types available") + void compileShouldMakeTypesAvailable() { + Path localRepo = Path.of(System.getProperty("user.home")).resolve(".m2/repository/javax/validation/validation-api/2.0.1.Final/validation-api-2.0.1.Final.jar"); + List classpath = List.of(localRepo); + JavaParser javaParser = javaParserBuilder + .classpath(classpath) + .build(); + SourceFile sourceFile = javaParser + .parse( + """ + import javax.validation.constraints.Email; + public class SomeClass { + @Email + private String email; + } + """ + ) + .toList() + .get(0); + J.CompilationUnit cu = (J.CompilationUnit) sourceFile; + List types = cu.getTypesInUse().getTypesInUse().stream().map(t -> ((JavaType.Class) t).getFullyQualifiedName()).toList(); + assertThat(types).containsExactlyInAnyOrder("java.lang.String", "javax.validation.constraints.Email"); + } + + @Test + @DisplayName("Compile should make types available") + void compileShouldMakeTypesAvailable2() { + Path localRepo = Path.of(System.getProperty("user.home")).resolve(".m2/repository/javax/validation/validation-api/2.0.1.Final/validation-api-2.0.1.Final.jar"); + List classpath = List.of(localRepo); + JavaParser javaParser = javaParserBuilder + .classpath(classpath) + .build(); + SourceFile sourceFile = javaParser + .parse( + """ + public class SomeClass { + @Deprecated + private String email; + } + """ + ) + .toList() + .get(0); + J.CompilationUnit cu = (J.CompilationUnit) sourceFile; + List types = cu.getTypesInUse().getTypesInUse().stream().map(t -> ((JavaType.Class) t).getFullyQualifiedName()).toList(); + assertThat(types).containsExactlyInAnyOrder("java.lang.String", "java.lang.Deprecated"); + + + RecipeRun recipeRun = new ChangeType( + "java.lang.Deprecated", + "javax.validation.constraints.Email", + true + ).run(new InMemoryLargeSourceSet(List.of(cu)), executionContext); + + Set typesInUse = ((J.CompilationUnit) recipeRun.getChangeset().getAllResults().get(0).getAfter()).getTypesInUse().getTypesInUse().stream() + .map(t -> ((JavaType.Class) t).getFullyQualifiedName()) + .collect(Collectors.toSet()); + assertThat(typesInUse).containsExactlyInAnyOrder("java.lang.String", "javax.validation.constraints.Email"); + + SourceFile sourceFile2 = javaParser + .parse( + """ + import javax.validation.constraints.Email; + public class SomeClass2 { + @Email + private String email; + } + """ + ) + .toList() + .get(0); + J.CompilationUnit cu2 = (J.CompilationUnit) sourceFile2; + List types2 = cu2.getTypesInUse().getTypesInUse().stream().map(t -> ((JavaType.Class) t).getFullyQualifiedName()).toList(); + assertThat(types2).containsExactlyInAnyOrder("java.lang.String", "javax.validation.constraints.Email"); + } + + + @Nested + @TestMethodOrder(MethodOrderer.OrderAnnotation.class) + @TestInstance(TestInstance.Lifecycle.PER_CLASS) + public class UsingTypeFromExternalDependency { + + private static final String JAVA_SOURCE_CODE = """ + package com.acme; + class SomeClass { + String someMember; + } + """; + + private ProjectContext context = createProjectContext(); + + /* + * Given a type (annotation) from an external dependency + * When using the annotation + * Then the code is correct but the type can't be resolved + */ + @Test + @Order(1) + @DisplayName("Adding an annotation of unknown type is possible") + void addingAnAnnotationOfUnkownTypeIsPossible() { + addAnnotation(); + String fullyQualifiedName = getFullyQualifiedName(); + assertCodeTransformation(); + assertThat(fullyQualifiedName).isNull(); + } + + /* + * Given the type is used but the dependency is missing + * When the dependency gets added + * Then the type can be resolved + */ + @Test + @Order(2) + @DisplayName("Adding the dependency resolves the missing type") + void addingTheDependencyResolvesTheMissingType() { + addDependency(); + String fullyQualifiedName = getFullyQualifiedName(); + assertThat(fullyQualifiedName).isEqualTo("javax.validation.constraints.Email"); + } + + /** + * Given a project without dependencies + * When a new dependency gets added + * and then a type from the dependency is used + * Then the type can be resolved + */ + @Test + @DisplayName("Adding a new dependency makes types available") + void addingANewDependencyMakesTypesAvailable() { + context = createProjectContext(); + // Adding the dependency makes the type resolvable + addDependency(); + addAnnotation(); + String fullyQualifiedName = getFullyQualifiedName(); + assertCodeTransformation(); + assertThat(fullyQualifiedName).isEqualTo("javax.validation.constraints.Email"); + } + + private ProjectContext createProjectContext() { + return TestProjectContext + .buildProjectContext(beanFactory) + .withJavaSource("src/main/java", JAVA_SOURCE_CODE) + .build(); + } + + private void addAnnotation() { + context.getProjectJavaSources().findJavaSourceDeclaringType("com.acme.SomeClass").get() + .getTypes().get(0) + .getMembers().get(0) + .addAnnotation("@Email", "javax.validation.constraints.Email"); + } + + private String getFullyQualifiedName() { + return context.getProjectJavaSources().findJavaSourceDeclaringType("com.acme.SomeClass").get() + .getTypes().get(0) + .getMembers().get(0) + .getAnnotations().get(0) + .getFullyQualifiedName(); + } + + private void addDependency() { + context.getApplicationModules().getRootModule().getBuildFile().addDependency( + Dependency.builder() + .groupId("javax.validation") + .artifactId("validation-api") + .version("2.0.1.Final") + .build() + ); + } + + private void assertCodeTransformation() { + assertThat(context.getProjectJavaSources().findJavaSourceDeclaringType("com.acme.SomeClass").get().print()) + .isEqualTo( + """ + package com.acme; + + import javax.validation.constraints.Email; + + class SomeClass { + @Email + String someMember; + } + """); + } + } + + /* + * * - * Also see {@link DependenciesChangedEventHandler} */ + @Test + @DisplayName("flow") + void flow() { + // create project with four modules + /* + parent + / | \ + moduleA -> moduleB -> moduleC + + */ + String parent = PomBuilder.buildPom("com.example:parent:1.0") + .withModules("moduleA", "moduleB", "moduleC") + .build(); + + String moduleC = PomBuilder.buildParentPom("com.example:parent:1.0", "com.example:moduleC:1.0").build(); + String moduleB = PomBuilder.buildParentPom("com.example:parent:1.0", "com.example:moduleB:1.0").unscopedDependencies("com.example:moduleC:1.0").build(); + String moduleA = PomBuilder.buildParentPom("com.example:parent:1.0", "com.example:moduleA:1.0").unscopedDependencies("com.example:moduleB:1.0").build(); + + System.out.println(parent); + System.out.println(moduleA); + System.out.println(moduleB); + System.out.println(moduleC); + + ProjectContext projectContext = TestProjectContext.buildProjectContext() + .withProjectResource("pom.xml", parent) + .withProjectResource("moduleA/pom.xml", moduleA) + .withJavaSource("moduleA/src/main/java", + """ + package com.example.a; + import com.example.b.B; + public class A { + B b; + } + """ + ) + .withProjectResource("moduleB/pom.xml", moduleB) + .withJavaSource("moduleB/src/main/java", + """ + package com.example.b; + import com.example.c.C; + public class B { + C c; + } + """ + ) + .withProjectResource("moduleC/pom.xml", moduleC) + .withJavaSource("moduleC/src/main/java", + """ + package com.example.c; + public class C { + } + """ + ) + .build(); + + List list = projectContext.getProjectJavaSources().list(); + List classpathA = projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.example.a.A").get().getResource().getSourceFile().getMarkers().findFirst(JavaSourceSet.class).get().getClasspath().stream().map(fq -> fq.getFullyQualifiedName()).toList(); + assertThat(classpathA).contains("com.example.b.B", "com.example.c.C"); + List classpathB = projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.example.b.B").get().getResource().getSourceFile().getMarkers().findFirst(JavaSourceSet.class).get().getClasspath().stream().map(fq -> fq.getFullyQualifiedName()).toList(); + assertThat(classpathB).contains("com.example.c.C"); + String typeFqNameA = projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.example.a.A").get().getTypes().get(0).getMembers().get(0).getTypeFqName(); + assertThat(typeFqNameA).isEqualTo("com.example.b.B"); + + // ok, cool + // let's add validation-api to moduleC and see if types are available in dependant modules + projectContext.getApplicationModules().getModule("moduleC").getBuildFile().addDependency( + Dependency.builder() + .groupId("javax.validation") + .artifactId("validation-api") + .version("2.0.1.Final") + .build() + ); + + list = projectContext.getProjectJavaSources().list(); + classpathA = projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.example.a.A").get().getResource().getSourceFile().getMarkers().findFirst(JavaSourceSet.class).get().getClasspath().stream().map(fq -> fq.getFullyQualifiedName()).toList(); + assertThat(classpathA).contains("com.example.b.B", "com.example.c.C", "javax.validation.constraints.Email"); + classpathB = projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.example.b.B").get().getResource().getSourceFile().getMarkers().findFirst(JavaSourceSet.class).get().getClasspath().stream().map(fq -> fq.getFullyQualifiedName()).toList(); + assertThat(classpathB).contains("com.example.c.C"); + typeFqNameA = projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.example.a.A").get().getTypes().get(0).getMembers().get(0).getTypeFqName(); + assertThat(typeFqNameA).isEqualTo("com.example.b.B"); + + } + + @Test void whenDependencyIsAdded_thenJavaParserTypeCacheGetsUpdated() { // simple ProjectContext - String javaSourceCode = "import jakarta.validation.constraints.Email; class Y {@Email String email;}"; - ProjectContext context = TestProjectContext - .buildProjectContext(eventPublisher, rewriteJavaParser) + String javaSourceCode = + """ + import javax.validation.constraints.Email; + class Y { + @Email String email; + } + """; + + TestProjectContextInfo contextInfo = TestProjectContext + .buildProjectContext(beanFactory) + .withBuildFileHavingDependencies("javax.validation:validation-api:2.0.1.Final") +// .buildProjectContext(eventPublisher, javaParser) .withJavaSource("src/main/java", javaSourceCode) + .buildProjectContextInfo(); + + ProjectContext context = contextInfo.projectContext(); + + Map> resolvedDependenciesMap = context.getApplicationModules().getRootModule().getBuildFile().getResolvedDependenciesMap(); + + JavaParser javaParser = javaParserBuilder + .classpath(resolvedDependenciesMap.get(Scope.Compile)) .build(); + + SourceFile sourceFile1 = JavaParser.fromJavaVersion() + .classpath(resolvedDependenciesMap.get(Scope.Compile)) + .build() + .parse(javaSourceCode) + .toList() + .get(0); + + + String javaxValidationEmail = "javax.validation.constraints.Email"; + + Set typesInUse = ((J.CompilationUnit) sourceFile1).getTypesInUse().getTypesInUse() + .stream() + .map(t -> ((JavaType.Class) t).getFullyQualifiedName()) + .collect(Collectors.toSet()); + + assertThat(typesInUse).containsExactlyInAnyOrder(javaxValidationEmail, "java.lang.String"); + + // Add a new dependency introducing new type + RewriteMavenParser parser = contextInfo.beanFactory().getBean(RewriteMavenParser.class); + String pom = PomBuilder.buildPom("com.example:app:1.0") + .compileScopeDependencies( + "javax.validation:validation-api:2.0.1.Final", + "javax.el:javax.el-api:3.0.0" + ).build(); + SourceFile parsedPom = parser.parse(pom).toList().get(0); + Optional mavenResolutionResult = parsedPom.getMarkers().findFirst(MavenResolutionResult.class); + + Map> dependenciesMap = new HashMap<>(); + Arrays.stream(Scope.values()).forEach(scope -> { + List resolvedDependencies = mavenResolutionResult.get().getDependencies().get(scope); + if (resolvedDependencies != null) { + final DependencyHelper rewriteMavenArtifactDownloader = contextInfo.beanFactory().getBean(DependencyHelper.class); + Set paths = resolvedDependencies + .stream() + .map(rewriteMavenArtifactDownloader::downloadArtifact) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toSet()); + dependenciesMap.put(scope, paths); + } + }); + Set newClasspath = dependenciesMap.get(Scope.Compile); + JavaParser javaParser2 = javaParserBuilder + .classpath(newClasspath) + .build(); + SourceFile sourceFile = javaParser2.parse(javaSourceCode).toList().get(0); + // provide ProjectContext to Spring beans contextHolder.setProjectContext(context); - String javaxValidationEmail = "javax.validation.constraints.Email"; - HashMap typeCache0 = retrieveTypeCache(rewriteJavaParser.getJavaParser()); + HashMap typeCache0 = retrieveTypeCache(javaParser); assertThat(typeCache0).isEmpty(); + // classpath + List classpath = context.getProjectJavaSources().list().get(0).getResource().getSourceFile().getMarkers().findFirst(JavaSourceSet.class).get().getClasspath().stream().map(fq -> fq.toString()).toList(); + assertThat(classpath).contains("javax.validation.constraints.Email"); + // Parse the java source to fill the type cache - rewriteJavaParser.parse(javaSourceCode); - HashMap typeCache = retrieveTypeCache(rewriteJavaParser.getJavaParser()); + javaParser.parse(javaSourceCode); + HashMap typeCache = retrieveTypeCache(javaParser); assertThat(typeCache).hasSize(17_590); // javax.validation.Email not in type cache @@ -106,12 +503,12 @@ void whenDependencyIsAdded_thenJavaParserTypeCacheGetsUpdated() { // add dependency - BuildFile buildFile = context.getBuildFile(); + BuildFile buildFile = context.getApplicationModules().getRootModule().getBuildFile(); buildFile.addDependency(Dependency.builder() - .groupId("javax.validation") - .artifactId("validation-api") - .version("2.0.1.Final") - .build()); + .groupId("javax.validation") + .artifactId("validation-api") + .version("2.0.1.Final") + .build()); System.out.println(buildFile.print()); assertThat(buildFile.getDeclaredDependencies(Scope.Compile).get(0).getArtifactId()).isEqualTo("validation-api"); @@ -121,13 +518,13 @@ void whenDependencyIsAdded_thenJavaParserTypeCacheGetsUpdated() { assertThat(ClasspathRegistry.getInstance().getCurrentDependencies().iterator().next().toString()).contains("validation-api"); // type cache contains the new types as classes were recompiled in DependenciesChangeEventListener - //rewriteJavaParser.getJavaParser().parse(javaSourceCode); + //javaParser.getJavaParser().parse(javaSourceCode); context.getApplicationModules().getRootModule().getMainJavaSourceSet().addJavaSource(TestProjectContext.getDefaultProjectRoot(), - Path.of("src/main/java"), - "import jakarta.validation.constraints.Email; class X {@Email String email;}"); + Path.of("src/main/java"), + "import javax.validation.constraints.Email; class X {@Email String email;}"); // The Email annotation can now be resolved - HashMap typeCacheAfter = retrieveTypeCache(rewriteJavaParser.getJavaParser()); + HashMap typeCacheAfter = retrieveTypeCache(javaParser); Optional emailType = findInTypeCache(typeCacheAfter, javaxValidationEmail); assertThat(emailType).isPresent(); // currently failing assertThat(typeCacheAfter).hasSize(17697); diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/OpenRewriteMavenBuildFileTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/OpenRewriteMavenBuildFileTest.java index e8f2891c2..5242a80b4 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/OpenRewriteMavenBuildFileTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/project/buildfile/OpenRewriteMavenBuildFileTest.java @@ -21,6 +21,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.openrewrite.ExecutionContext; +import org.openrewrite.maven.tree.Scope; import org.springframework.context.ApplicationEventPublisher; import org.springframework.sbm.GitHubIssue; import org.springframework.sbm.build.api.BuildFile; @@ -33,18 +34,15 @@ import org.springframework.sbm.engine.context.ProjectContextHolder; import org.springframework.sbm.java.api.Member; import org.springframework.sbm.java.impl.DependenciesChangedEventHandler; +import org.springframework.sbm.java.impl.DependencyChangeHandler; import org.springframework.sbm.java.impl.RewriteJavaParser; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.parsers.JavaParserBuilder; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; +import java.util.*; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; @@ -94,7 +92,7 @@ void coordinatesForRequestedDependencies_withVersionProperty_shouldHaveResolvedV .get(0) .getBuildFile(); - assertThat(buildFile.getRequestedDependencies().get(0).getCoordinates()).isEqualTo("javax.validation:validation-api:2.0.1.Final"); + assertThat(buildFile.getRequestedDependencies().get(0).getGav()).isEqualTo("javax.validation:validation-api:2.0.1.Final"); } @Nested @@ -361,6 +359,8 @@ void testGetResolvedDependenciesPaths() { BuildFile sut = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); List dependenciesPaths = sut.getResolvedDependenciesPaths(); @@ -413,6 +413,8 @@ void testResolvedDependenciesWithPomTypeDependency() { BuildFile sut = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); List unifiedPaths = sut.getResolvedDependenciesPaths().stream() @@ -540,7 +542,7 @@ public class Cat { ) .build(); - BuildFile buildFile = context.getBuildFile(); + BuildFile buildFile = context.getApplicationModules().getRootModule().getBuildFile(); Member member = context.getProjectJavaSources().list().get(0).getTypes().get(0).getMembers().get(0); @@ -561,13 +563,13 @@ public class Cat { assertEventPublished(eventPublisher, argumentCaptor, event, 1); DependenciesChangedEvent fireEvent = argumentCaptor.getValue(); - assertThat(fireEvent.getResolvedDependencies().get(0).toString()).endsWith("javax/validation/validation-api/2.0.1.Final/validation-api-2.0.1.Final.jar"); + assertThat(fireEvent.resolvedDependencies().get(0).toString()).endsWith("javax/validation/validation-api/2.0.1.Final/validation-api-2.0.1.Final.jar"); // call DependenciesChangedEventHandler to trigger recompile JavaParserBuilder rewriteJavaParser = new JavaParserBuilder(); ProjectContextHolder projectContextHolder = new ProjectContextHolder(); projectContextHolder.setProjectContext(context); - DependenciesChangedEventHandler handler = new DependenciesChangedEventHandler(projectContextHolder, rewriteJavaParser, executionContext); + DependenciesChangedEventHandler handler = new DependenciesChangedEventHandler(new DependencyChangeHandler(projectContextHolder, rewriteJavaParser, executionContext)); handler.onDependenciesChanged(fireEvent); Member member2 = context.getProjectJavaSources().list().get(0).getTypes().get(0).getMembers().get(0); @@ -600,6 +602,8 @@ void testHasDependency() { BuildFile sut = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); assertThat(sut.hasDeclaredDependencyMatchingRegex("javax\\.transaction.*")).isTrue(); @@ -631,6 +635,8 @@ void testAddDependency() { BuildFile sut = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); sut.addDependency(Dependency.builder() @@ -670,6 +676,8 @@ void addDependency() { BuildFile sut = TestProjectContext.buildProjectContext(eventPublisher) .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); Dependency dependency = Dependency.builder() @@ -691,8 +699,8 @@ void addDependency() { // Don't know about a better way, see https://github.com/mockito/mockito/issues/565 assertEventPublished(eventPublisher, argumentCaptor, DependenciesChangedEvent.class, 1); - assertThat(argumentCaptor.getValue().getResolvedDependencies()).hasSize(1); - assertThat(argumentCaptor.getValue().getResolvedDependencies().get(0).toString()).endsWith("org/apiguardian/apiguardian-api/1.1.0/apiguardian-api-1.1.0.jar"); + assertThat(argumentCaptor.getValue().resolvedDependencies()).hasSize(1); + assertThat(argumentCaptor.getValue().resolvedDependencies().get(0).toString()).endsWith("org/apiguardian/apiguardian-api/1.1.0/apiguardian-api-1.1.0.jar"); } private void assertEventPublished(ApplicationEventPublisher eventPublisher, ArgumentCaptor argumentCaptor, Class eventClass, int times) { @@ -724,6 +732,8 @@ void testAddDependencies() { BuildFile sut = TestProjectContext.buildProjectContext(eventPublisher) .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); sut.addDependencies(List.of( @@ -817,7 +827,7 @@ void testDeleteDependencies() { " \n" + "\n"; - BuildFile sut = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile sut = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); sut.removeDependencies(List.of( Dependency.builder() @@ -1079,7 +1089,7 @@ void getEffectiveDependencies() { private Dependency findDependencyByCoordinate(List dependenciesEffectiveInModule1, String anObject) { return dependenciesEffectiveInModule1 .stream() - .filter(d -> d.getCoordinates().equals(anObject)) + .filter(d -> d.getGav().equals(anObject)) .findFirst() .get(); } @@ -1138,7 +1148,7 @@ void getRequestedDependencies() { .withMavenRootBuildFileSource(pomSource) .build(); - List dependencies = build.getBuildFile().getRequestedDependencies(); + List dependencies = build.getApplicationModules().getRootModule().getBuildFile().getRequestedDependencies(); assertThat(dependencies).hasSize(4); @@ -1218,7 +1228,8 @@ void testGetDeclaredDependencies() { .withMavenRootBuildFileSource(pomSource) .build(); - List dependencies = build.getBuildFile().getDeclaredDependencies(); + List dependencies = build.getApplicationModules() + .getRootModule().getBuildFile().getDeclaredDependencies(); assertThat(dependencies).hasSize(4); @@ -1276,6 +1287,8 @@ void testDeleteTypePomDependencies() { BuildFile sut = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); assertThat(sut.getEffectiveDependencyManagement()).hasSize(0); assertThat(sut.getDeclaredDependencies()).hasSize(2); @@ -1332,7 +1345,7 @@ void testDeleteTypePomDependenciesAll() { long beforeCreatingContext = System.currentTimeMillis(); - BuildFile sut = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile sut = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); sut.removeDependencies(List.of( Dependency.builder() @@ -1410,28 +1423,29 @@ void testAddToDependencyManagement() { .build(); // call sut - projectContext.getBuildFile().addDependency(addedDependency); + projectContext.getApplicationModules() + .getRootModule().getBuildFile().addDependency(addedDependency); // assert that DependenciesChangedEvent has been published with the list of dependencies ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(DependenciesChangedEvent.class); assertEventPublished(eventPublisher, argumentCaptor, DependenciesChangedEvent.class, 1); - List resolvedDependencies = argumentCaptor.getValue().getResolvedDependencies(); + Map> resolvedDependencies = argumentCaptor.getValue().resolvedDependencies(); assertThat(resolvedDependencies).hasSize(1); Path pathInMavenRepo = Path.of("org/slf4j/slf4j-api/1.7.32/slf4j-api-1.7.32.jar"); assertThat(resolvedDependencies.get(0)).endsWith(pathInMavenRepo); // assert that the dependency has been added to in pom.xml - assertThat(projectContext.getBuildFile().print()).isEqualTo(expectedPomXmlSource); + assertThat(projectContext.getApplicationModules().getRootModule().getBuildFile().print()).isEqualTo(expectedPomXmlSource); // assert that resolved dependencies path contains added dependency - List resolvedDependenciesPaths = projectContext.getBuildFile().getResolvedDependenciesPaths(); + List resolvedDependenciesPaths = projectContext.getApplicationModules().getRootModule().getBuildFile().getResolvedDependenciesPaths(); assertThat(resolvedDependenciesPaths.get(0)).endsWith(pathInMavenRepo); // assert that dependency management contains dependency - Dependency retrievedDependency = projectContext.getBuildFile().getDeclaredDependencies().get(0); + Dependency retrievedDependency = projectContext.getApplicationModules().getRootModule().getBuildFile().getDeclaredDependencies().get(0); assertThat(retrievedDependency).isEqualTo(addedDependency); assertThat(addedDependency.getGroupId()).isEqualTo("org.slf4j"); assertThat(addedDependency.getArtifactId()).isEqualTo("slf4j-api"); @@ -1472,7 +1486,7 @@ void shouldAddMavenPluginWhenNoPluginSectionExists() { plugin.setGroupId("group.id"); plugin.setArtifactId("some.artifact"); - BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); buildFile.addPlugin(plugin); assertEquals(refactoredPomXml, buildFile.print()); } @@ -1515,7 +1529,7 @@ void shouldAddMavenPluginWhenEmptyPluginSectionExists() { plugin.setGroupId("group.id"); plugin.setArtifactId("some.artifact"); - BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); buildFile.addPlugin(plugin); assertEquals(refactoredPomXml, buildFile.print()); } @@ -1562,7 +1576,7 @@ void shouldNotAddMavenPluginWhenSamePluginExists() { plugin.setGroupId("group.id"); plugin.setArtifactId("some.artifact"); - BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); buildFile.addPlugin(plugin); assertEquals(refactoredPomXml, buildFile.print()); } @@ -1613,7 +1627,7 @@ void shouldAddMavenPluginWhenAnotherPluginExists() { plugin.setGroupId("group.id"); plugin.setArtifactId("some.artifact"); - BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); buildFile.addPlugin(plugin); assertEquals(refactoredPomXml, buildFile.print()); } @@ -1660,7 +1674,7 @@ public void shouldCreateDependencyManagementWithDependencyWhenNoneExists() { .version("5.6.2") .build(); - BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(before).build().getBuildFile(); + BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(before).build().getApplicationModules().getRootModule().getBuildFile(); buildFile.addToDependencyManagement(dependency); assertEquals(expected, buildFile.print()); } @@ -1715,7 +1729,7 @@ public void shouldAddDependencyWhenDependencyManagementAlreadyExists() { Dependency dependency = Dependency.builder().groupId("org.projectlombok").artifactId("lombok").version("1.18.12").build(); - BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(before).build().getBuildFile(); + BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(before).build().getApplicationModules().getRootModule().getBuildFile(); buildFile.addToDependencyManagement(dependency); assertEquals(expected, buildFile.print()); } @@ -1773,7 +1787,7 @@ public void shouldUpdateVersionIfDifferent() { .build(); ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class); - BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(before).build().getBuildFile(); + BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(before).build().getApplicationModules().getRootModule().getBuildFile(); buildFile.addToDependencyManagement(dependency); assertEquals(expected, buildFile.print()); } @@ -1830,7 +1844,7 @@ public void shouldUpdateScopeIfDifferent() { .scope("test") .build(); - BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(before).build().getBuildFile(); + BuildFile buildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(before).build().getApplicationModules().getRootModule().getBuildFile(); buildFile.addToDependencyManagement(dependency); assertEquals(expected, buildFile.print()); } @@ -1890,6 +1904,8 @@ public void shouldRemoveScopeIfRemoved() { BuildFile buildFile = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(before) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); buildFile.addToDependencyManagement(dependency); @@ -1924,6 +1940,8 @@ public void packagingType() { BuildFile buildFile = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(before) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); assertThat(buildFile.getPackaging()).isEqualTo("war"); @@ -1956,6 +1974,8 @@ void testHasPlugin() { BuildFile buildFile = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile(); OpenRewriteMavenPlugin plugin = OpenRewriteMavenPlugin.builder() @@ -1985,6 +2005,8 @@ void testGetNameWithNameShouldReturnName() { Optional name = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile() .getName(); @@ -2007,6 +2029,8 @@ void testGetNameWithNoNameShouldReturnEmptyOptional() { Optional name = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) .build() + .getApplicationModules() + .getRootModule() .getBuildFile() .getName(); @@ -2067,7 +2091,7 @@ void getPlugins() { " \n" + ""; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); List plugins = openRewriteMavenBuildFile.getPlugins(); @@ -2127,7 +2151,7 @@ void deserializePluginConfiguration() { " \n" + ""; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); Plugin compilerPlugin = openRewriteMavenBuildFile.getPlugins() .stream() @@ -2187,7 +2211,7 @@ void serializePluginConfiguration() { " \n" + ""; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); Plugin compilerPlugin = openRewriteMavenBuildFile.getPlugins() .stream() @@ -2252,7 +2276,7 @@ void deleteProperty_withSingleModule() { " \n" + ""; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); openRewriteMavenBuildFile.deleteProperty("java.version"); @@ -2469,7 +2493,7 @@ void removePluginsMatchingRegex() { " \n" + ""; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); openRewriteMavenBuildFile.removePluginsMatchingRegex("com\\.mulesoft\\..*"); @@ -2555,7 +2579,7 @@ void removePlugins() { " \n" + ""; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); openRewriteMavenBuildFile.removePlugins("com.mulesoft.munit.tools:munit-maven-plugin"); @@ -2607,7 +2631,7 @@ void hasParentWithParentShouldReturnTrue() { " \n" + "\n"; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); assertThat(openRewriteMavenBuildFile.hasParent()).isTrue(); } @@ -2628,7 +2652,7 @@ void hasParentWithoutParentShouldReturnFalse() { " \n" + "\n"; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); assertThat(openRewriteMavenBuildFile.hasParent()).isFalse(); } @@ -2655,7 +2679,7 @@ void hasParentWithParentShouldReturnParent() { " \n" + "\n"; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); assertThat(openRewriteMavenBuildFile.getParentPomDeclaration()).isNotEmpty(); assertThat(openRewriteMavenBuildFile.getParentPomDeclaration().get().getGroupId()).isEqualTo("org.springframework.boot"); @@ -2687,7 +2711,7 @@ void upgradeParentVersion() { """; - BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getBuildFile(); + BuildFile openRewriteMavenBuildFile = TestProjectContext.buildProjectContext().withMavenRootBuildFileSource(pomXml).build().getApplicationModules().getRootModule().getBuildFile(); openRewriteMavenBuildFile.upgradeParentVersion("2.5.6"); diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/JavaProvenanceMarkerFactoryTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/JavaProvenanceMarkerFactoryTest.java index fece87f45..86fe15c2f 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/JavaProvenanceMarkerFactoryTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/JavaProvenanceMarkerFactoryTest.java @@ -24,7 +24,7 @@ import org.openrewrite.xml.tree.Xml; import org.springframework.sbm.build.impl.MavenSettingsInitializer; import org.springframework.sbm.build.impl.RewriteMavenParser; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import java.nio.file.Path; import java.util.List; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/ResourceParserTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/ResourceParserTest.java index 13102f6a5..1298a2555 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/ResourceParserTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/ResourceParserTest.java @@ -30,7 +30,7 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.Resource; import org.springframework.sbm.engine.events.StartedScanningProjectResourceEvent; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.TestDummyResource; import org.springframework.sbm.properties.parser.RewritePropertiesParser; import org.springframework.sbm.xml.parser.RewriteXmlParser; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/RewriteXmlParserTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/RewriteXmlParserTest.java index 65a01dc61..dfd07946c 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/RewriteXmlParserTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/RewriteXmlParserTest.java @@ -18,7 +18,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openrewrite.xml.tree.Xml; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.TestDummyResource; import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.sbm.xml.parser.RewriteXmlParser; diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/project/resource/TestProjectContext.java b/components/sbm-core/src/test/java/org/springframework/sbm/project/resource/TestProjectContext.java index cfe92fc96..81d0424a9 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/project/resource/TestProjectContext.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/project/resource/TestProjectContext.java @@ -21,6 +21,7 @@ import org.jetbrains.annotations.NotNull; import org.openrewrite.ExecutionContext; import org.openrewrite.Parser; +import org.openrewrite.java.JavaParser; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationEventPublisher; @@ -236,7 +237,7 @@ public static Builder buildProjectContext(ApplicationEventPublisher eventPublish * * @param eventPublisher the eventPublisher to use */ - public static Builder buildProjectContext(ApplicationEventPublisher eventPublisher, RewriteJavaParser rewriteJavaParser) { + public static Builder buildProjectContext(ApplicationEventPublisher eventPublisher, JavaParser rewriteJavaParser) { return new Builder(DEFAULT_PROJECT_ROOT, eventPublisher, rewriteJavaParser); } @@ -276,7 +277,7 @@ public static ProjectContext buildFromDir(Path of) { public static class Builder { @Deprecated - private RewriteJavaParser javaParser; + private JavaParser javaParser; private ConfigurableListableBeanFactory beanFactory; private Path projectRoot; private List resourceWrapperList = new ArrayList<>(); @@ -299,7 +300,7 @@ public Builder(Path projectRoot, ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } - public Builder(Path defaultProjectRoot, ApplicationEventPublisher eventPublisher, RewriteJavaParser rewriteJavaParser) { + public Builder(Path defaultProjectRoot, ApplicationEventPublisher eventPublisher, JavaParser rewriteJavaParser) { this(defaultProjectRoot, eventPublisher); this.javaParser = rewriteJavaParser; } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_24_25/actions/Boot_24_25_SqlScriptDataSourceInitializationActionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_24_25/actions/Boot_24_25_SqlScriptDataSourceInitializationActionTest.java index 992a6c93b..d9acf5f3b 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_24_25/actions/Boot_24_25_SqlScriptDataSourceInitializationActionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_24_25/actions/Boot_24_25_SqlScriptDataSourceInitializationActionTest.java @@ -20,7 +20,7 @@ import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.boot.properties.search.SpringBootApplicationPropertiesResourceListFilter; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.Test; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_24_25/report/Boot_24_25_SqlScriptDataSourceInitializationTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_24_25/report/Boot_24_25_SqlScriptDataSourceInitializationTest.java index 51b5b36f8..93ab084e9 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_24_25/report/Boot_24_25_SqlScriptDataSourceInitializationTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_24_25/report/Boot_24_25_SqlScriptDataSourceInitializationTest.java @@ -18,7 +18,7 @@ import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.Test; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/actions/Boot_27_30_AddLoggingDateFormatTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/actions/Boot_27_30_AddLoggingDateFormatTest.java index 884eec4a1..9418f2326 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/actions/Boot_27_30_AddLoggingDateFormatTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/actions/Boot_27_30_AddLoggingDateFormatTest.java @@ -21,7 +21,7 @@ import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties; import org.springframework.sbm.boot.properties.search.SpringBootApplicationPropertiesResourceListFilter; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import java.util.List; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/actions/Boot_27_30_JmxEndpointExposureActionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/actions/Boot_27_30_JmxEndpointExposureActionTest.java index 10eac2fd4..7b8436cb3 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/actions/Boot_27_30_JmxEndpointExposureActionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/actions/Boot_27_30_JmxEndpointExposureActionTest.java @@ -21,7 +21,7 @@ import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties; import org.springframework.sbm.boot.properties.search.SpringBootApplicationPropertiesResourceListFilter; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import java.util.List; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/conditions/JmxEndpointExposureConditionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/conditions/JmxEndpointExposureConditionTest.java index 69c23a6b5..fff8e532d 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/conditions/JmxEndpointExposureConditionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/conditions/JmxEndpointExposureConditionTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import java.nio.file.Path; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/conditions/LoggingDateFormatConditionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/conditions/LoggingDateFormatConditionTest.java index 6dbecdec9..b177d0530 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/conditions/LoggingDateFormatConditionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/conditions/LoggingDateFormatConditionTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import java.nio.file.Path; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/filter/JmxEndpointExposureFinderTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/filter/JmxEndpointExposureFinderTest.java index 1b36114c1..184200f8b 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/filter/JmxEndpointExposureFinderTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/filter/JmxEndpointExposureFinderTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.properties.api.PropertiesSource; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/filter/LoggingDateFormatPropertyFinderTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/filter/LoggingDateFormatPropertyFinderTest.java index d37e520bf..72a32a249 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/filter/LoggingDateFormatPropertyFinderTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/filter/LoggingDateFormatPropertyFinderTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.properties.api.PropertiesSource; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportActionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportActionTest.java index 60347915d..a2f1411ab 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportActionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportActionTest.java @@ -24,7 +24,7 @@ import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.test.RecipeIntegrationTestSupport; import org.w3c.dom.NodeList; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ChangesToDataPropertiesReportSectionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ChangesToDataPropertiesReportSectionTest.java index e01c42cfe..5d2cc2311 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ChangesToDataPropertiesReportSectionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ChangesToDataPropertiesReportSectionTest.java @@ -21,7 +21,7 @@ import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.boot.upgrade_27_30.report.SpringBootUpgradeReportTestSupport; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/LoggingDateFormatHelperTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/LoggingDateFormatHelperTest.java index 4da30e82d..5153afc92 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/LoggingDateFormatHelperTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/LoggingDateFormatHelperTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.properties.api.PropertiesSource; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/LoggingDateFormatReportSectionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/LoggingDateFormatReportSectionTest.java index b89678bf5..d8b0577dc 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/LoggingDateFormatReportSectionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/LoggingDateFormatReportSectionTest.java @@ -20,7 +20,7 @@ import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.boot.upgrade_27_30.report.SpringBootUpgradeReportTestSupport; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; /** diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceMediaTypeTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceMediaTypeTest.java index c584be0ba..6c5a933f6 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceMediaTypeTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceMediaTypeTest.java @@ -20,7 +20,7 @@ import org.springframework.sbm.java.api.JavaSource; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.java.impl.RewriteJavaParser; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.testhelper.common.utils.TestDiff; diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseBuilderTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseBuilderTest.java index 2dec8b755..30cd81332 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseBuilderTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseBuilderTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.engine.recipe.AbstractAction; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.java.impl.RewriteJavaParser; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.testhelper.common.utils.TestDiff; diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseEntityReplacementTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseEntityReplacementTest.java index 1a230c430..de811c342 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseEntityReplacementTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseEntityReplacementTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.engine.recipe.AbstractAction; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.java.impl.RewriteJavaParser; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.testhelper.common.utils.TestDiff; diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseStatusTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseStatusTest.java index 95b9a2c30..eddf52bcc 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseStatusTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseStatusTest.java @@ -18,7 +18,7 @@ import org.springframework.sbm.engine.recipe.AbstractAction; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.java.impl.RewriteJavaParser; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.testhelper.common.utils.TestDiff; diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxws/WebServiceDescriptorTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxws/WebServiceDescriptorTest.java index 983a6fd0a..274a723a4 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxws/WebServiceDescriptorTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxws/WebServiceDescriptorTest.java @@ -18,7 +18,7 @@ import org.springframework.sbm.GitHubIssue; import org.springframework.sbm.java.api.Type; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; diff --git a/components/sbm-recipes-mule-to-boot/src/main/java/org/springframework/sbm/mule/resource/MuleXmlProjectResourceRegistrar.java b/components/sbm-recipes-mule-to-boot/src/main/java/org/springframework/sbm/mule/resource/MuleXmlProjectResourceRegistrar.java index 8e2e33259..3e18a9545 100644 --- a/components/sbm-recipes-mule-to-boot/src/main/java/org/springframework/sbm/mule/resource/MuleXmlProjectResourceRegistrar.java +++ b/components/sbm-recipes-mule-to-boot/src/main/java/org/springframework/sbm/mule/resource/MuleXmlProjectResourceRegistrar.java @@ -22,7 +22,7 @@ import org.openrewrite.xml.XmlParser; import org.openrewrite.xml.tree.Xml; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.ProjectResourceWrapper; import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.stereotype.Component; diff --git a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/JavaDSLActionBaseTest.java b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/JavaDSLActionBaseTest.java index 15fd42f22..98244d640 100644 --- a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/JavaDSLActionBaseTest.java +++ b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/JavaDSLActionBaseTest.java @@ -45,7 +45,7 @@ import org.springframework.sbm.mule.api.toplevel.configuration.ConfigurationTypeAdapterFactory; import org.springframework.sbm.mule.api.toplevel.configuration.MuleConfigurationsExtractor; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceRegistrar; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; diff --git a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/MigrateMulesoftFileTest.java b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/MigrateMulesoftFileTest.java index 50b3f19ef..f8b9dcb90 100644 --- a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/MigrateMulesoftFileTest.java +++ b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/MigrateMulesoftFileTest.java @@ -18,7 +18,7 @@ import org.springframework.sbm.common.filter.AbsolutePathResourceFinder; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceRegistrar; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.ProjectResource; import org.springframework.sbm.project.resource.TestProjectContext; import freemarker.cache.FileTemplateLoader; diff --git a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/amqp/AmqpInboundEndpointTranslatorTest.java b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/amqp/AmqpInboundEndpointTranslatorTest.java index 14217e9bf..9cb1af39c 100644 --- a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/amqp/AmqpInboundEndpointTranslatorTest.java +++ b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/amqp/AmqpInboundEndpointTranslatorTest.java @@ -26,7 +26,7 @@ import org.springframework.sbm.mule.resource.MuleXml; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceFilter; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceRegistrar; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import javax.xml.bind.JAXBElement; diff --git a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/amqp/AmqpOutboundEndpointTranslatorTest.java b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/amqp/AmqpOutboundEndpointTranslatorTest.java index 12de05ab7..43d340b43 100644 --- a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/amqp/AmqpOutboundEndpointTranslatorTest.java +++ b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/amqp/AmqpOutboundEndpointTranslatorTest.java @@ -26,7 +26,7 @@ import org.springframework.sbm.mule.resource.MuleXml; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceFilter; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceRegistrar; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import javax.xml.bind.JAXBElement; diff --git a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/http/HttpListenerTranslatorTest.java b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/http/HttpListenerTranslatorTest.java index 25b26f3fc..427374db3 100644 --- a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/http/HttpListenerTranslatorTest.java +++ b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/http/HttpListenerTranslatorTest.java @@ -25,7 +25,7 @@ import org.springframework.sbm.mule.resource.MuleXml; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceFilter; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceRegistrar; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import javax.xml.bind.JAXBElement; diff --git a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/logging/LoggingTranslatorTest.java b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/logging/LoggingTranslatorTest.java index bcb468871..2412d5833 100644 --- a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/logging/LoggingTranslatorTest.java +++ b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/javadsl/translators/logging/LoggingTranslatorTest.java @@ -26,7 +26,7 @@ import org.springframework.sbm.mule.resource.MuleXml; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceFilter; import org.springframework.sbm.mule.resource.MuleXmlProjectResourceRegistrar; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import javax.xml.bind.JAXBElement; diff --git a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/resource/MuleXmlProjectResourceRegistrarTest.java b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/resource/MuleXmlProjectResourceRegistrarTest.java index 7863c5e35..57d072d4a 100644 --- a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/resource/MuleXmlProjectResourceRegistrarTest.java +++ b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/resource/MuleXmlProjectResourceRegistrarTest.java @@ -16,7 +16,7 @@ package org.springframework.sbm.mule.resource; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.Test; diff --git a/components/sbm-recipes-spring-cloud/src/test/java/org/springframework/sbm/sccs/MigrateToSpringCloudConfigServerHelperTest.java b/components/sbm-recipes-spring-cloud/src/test/java/org/springframework/sbm/sccs/MigrateToSpringCloudConfigServerHelperTest.java index 0fbbe72e3..648cd46cf 100644 --- a/components/sbm-recipes-spring-cloud/src/test/java/org/springframework/sbm/sccs/MigrateToSpringCloudConfigServerHelperTest.java +++ b/components/sbm-recipes-spring-cloud/src/test/java/org/springframework/sbm/sccs/MigrateToSpringCloudConfigServerHelperTest.java @@ -15,7 +15,7 @@ */ package org.springframework.sbm.sccs; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.test.ProjectContextFileSystemTestSupport; import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; diff --git a/components/sbm-recipes-spring-framework/src/main/java/org/springframework/sbm/actions/spring/xml/migration/Helper.java b/components/sbm-recipes-spring-framework/src/main/java/org/springframework/sbm/actions/spring/xml/migration/Helper.java index 65e5a734c..3f3c72692 100644 --- a/components/sbm-recipes-spring-framework/src/main/java/org/springframework/sbm/actions/spring/xml/migration/Helper.java +++ b/components/sbm-recipes-spring-framework/src/main/java/org/springframework/sbm/actions/spring/xml/migration/Helper.java @@ -34,6 +34,12 @@ @Component // FIXME: no member, all methods can be static (?) -> no component class Helper { + + /** + * @deprecated + * Use org.springframework.sbm.utils.JavaHelper instead + */ + @Deprecated() static String lowercaseFirstChar(String name) { return Character.toLowerCase(name.charAt(0)) + name.substring(1); } diff --git a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationProperties.java b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationProperties.java index 047016e55..cc2ff8b3c 100644 --- a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationProperties.java +++ b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationProperties.java @@ -23,7 +23,7 @@ import org.openrewrite.marker.Markers; import org.openrewrite.properties.tree.Properties.File; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.properties.api.PropertiesSource; import org.springframework.util.Assert; diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrarTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrarTest.java index 51c026c0c..810eee221 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrarTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/SpringBootApplicationPropertiesRegistrarTest.java @@ -16,7 +16,7 @@ package org.springframework.sbm.boot.properties; import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.sbm.properties.parser.RewritePropertiesParser; import org.junit.jupiter.api.Test; diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesActionTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesActionTest.java index 5da08e7f7..fb43d8a12 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesActionTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/actions/AddSpringBootApplicationPropertiesActionTest.java @@ -18,7 +18,7 @@ import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties; import org.springframework.sbm.boot.properties.search.SpringBootApplicationPropertiesResourceListFilter; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationPropertiesTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationPropertiesTest.java index 50886ddb0..94e21497a 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationPropertiesTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/api/SpringBootApplicationPropertiesTest.java @@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; import org.openrewrite.properties.PropertiesParser; import org.openrewrite.properties.tree.Properties; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import java.nio.file.Path; import java.util.List; diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/finder/SpringBootDefaultPropertiesFinderTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/finder/SpringBootDefaultPropertiesFinderTest.java index 0331e8781..0b6f3b27e 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/finder/SpringBootDefaultPropertiesFinderTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/finder/SpringBootDefaultPropertiesFinderTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.boot.properties.SpringApplicationPropertiesPathMatcher; import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import java.nio.file.Path; diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/search/SpringBootApplicationPropertiesResourceFilterTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/search/SpringBootApplicationPropertiesResourceFilterTest.java index 1bdac9644..d69b58ea8 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/search/SpringBootApplicationPropertiesResourceFilterTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/properties/search/SpringBootApplicationPropertiesResourceFilterTest.java @@ -19,7 +19,7 @@ import org.springframework.sbm.boot.properties.SpringBootApplicationPropertiesRegistrar; import org.springframework.sbm.boot.properties.api.SpringBootApplicationProperties; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.Test; diff --git a/components/test-helper/pom.xml b/components/test-helper/pom.xml index 721f81a35..b6e68aa0a 100644 --- a/components/test-helper/pom.xml +++ b/components/test-helper/pom.xml @@ -30,6 +30,7 @@ org.springframework.boot spring-boot-starter-test + compile org.assertj diff --git a/components/test-helper/src/main/java/org/springframework/sbm/java/OpenRewriteTestSupport.java b/components/test-helper/src/main/java/org/springframework/sbm/java/OpenRewriteTestSupport.java index 6eca61960..38d7f0205 100644 --- a/components/test-helper/src/main/java/org/springframework/sbm/java/OpenRewriteTestSupport.java +++ b/components/test-helper/src/main/java/org/springframework/sbm/java/OpenRewriteTestSupport.java @@ -15,16 +15,16 @@ */ package org.springframework.sbm.java; +import org.assertj.core.api.Assertions; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.openrewrite.*; import org.openrewrite.internal.InMemoryLargeSourceSet; -import org.springframework.sbm.java.util.JavaSourceUtil; -import org.springframework.sbm.testhelper.common.utils.TestDiff; -import org.assertj.core.api.Assertions; import org.openrewrite.java.JavaIsoVisitor; import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.tree.J; +import org.springframework.sbm.java.util.JavaSourceUtil; +import org.springframework.sbm.testhelper.common.utils.TestDiff; import java.io.File; import java.nio.file.Path; @@ -36,8 +36,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.fail; - public class OpenRewriteTestSupport { @@ -251,7 +249,7 @@ private static

RecipeRun refactor(J.CompilationUnit given, JavaVisitor> recipe = new GenericOpenRewriteTestRecipe<>(visitor); return recipe.run( new InMemoryLargeSourceSet(List.of(given)), - new InMemoryExecutionContext(t -> fail(t)) + new InMemoryExecutionContext(t -> Assertions.fail(t.getMessage())) ); } diff --git a/pom.xml b/pom.xml index e9a71bb13..b992ed13f 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ UTF-8 8.1.8 3.1.2 - 2.5.0 + 17 17 3.10.1 @@ -29,7 +29,7 @@ UTF-8 UTF-8 src/generated/java - 1.33 + 0.1.0-SNAPSHOT 0.0.5 @@ -38,7 +38,7 @@ scm:git:https://github.com/spring-projects-experimental/spring-boot-migrator.git scm:git:https://github.com/spring-projects-experimental/spring-boot-migrator https://github.com/spring-projects-experimental/spring-boot-migrator - 0.15.0 + 0.15.1 @@ -48,12 +48,34 @@ + + + components/sbm-openrewrite + components/sbm-core + components/test-helper + components/recipe-test-support + - org.yaml - snakeyaml - ${snakeyaml.version} + org.apache.maven.wagon + wagon-http + 3.5.3 + + + org.apache.maven.resolver + maven-resolver-transport-http + 1.9.14 + + + org.apache.maven.resolver + maven-resolver-api + 1.9.14 + + + org.apache.maven.resolver + maven-resolver-impl + 1.9.14 @@ -79,12 +101,6 @@ ${project.version} test - - org.springframework.sbm - recipe-test-support - ${project.version} - test - org.springframework.boot spring-boot-dependencies @@ -108,36 +124,11 @@ - - - - - - - - - - - - - - org.testcontainers - testcontainers - ${testcontainers.version} - test - - - junit - junit - - - org.apache.maven.shared maven-invoker ${maven-invoker.version} - org.openrewrite rewrite-core @@ -243,24 +234,12 @@ sbm-support-rewrite ${sbm-support-rewrite.version} + + org.springframework.experimental + sbm-support-rewrite + ${sbm-support-rewrite.version} + - - - - - - - - components/sbm-openrewrite - components/test-helper - components/recipe-test-support - components/sbm-core - - - - - - ${jar.name} @@ -385,6 +364,7 @@ limitations under the License. + sbm-support-rewrite/** **/demo/** **/.sdkmanrc **/*.adoc diff --git a/sbm-support-rewrite/pom.xml b/sbm-support-rewrite/pom.xml index 0a1785b84..c34d8072b 100644 --- a/sbm-support-rewrite/pom.xml +++ b/sbm-support-rewrite/pom.xml @@ -21,8 +21,7 @@ 17 UTF-8 3.1.3 - 8.4.2 - 5.0.5 + 8.5.1 0.15.0-SNAPSHOT 5.3.2 3.9.1 @@ -94,6 +93,15 @@ + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-configuration-processor + true + com.squareup.okhttp3 okhttp @@ -138,15 +146,6 @@ rewrite-maven-plugin ${rewrite-maven-plugin.version} - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-configuration-processor - true - org.projectlombok lombok @@ -177,16 +176,6 @@ maven-resolver-provider ${maven.version} - - org.apache.maven - maven-core - ${maven.version} - - - org.apache.maven - maven-artifact - ${maven.version} - org.apache.maven maven-compat @@ -208,20 +197,11 @@ plexus-cipher ${plexus-cypher.version} - - org.apache.maven - maven-model - ${maven.version} - - - org.apache.maven - maven-model-builder - ${maven.version} - org.apache.maven.shared maven-invoker ${maven-invoker.version} + test javax.xml.bind @@ -494,6 +474,48 @@ limitations under the License. true + + org.codehaus.mojo + flatten-maven-plugin + 1.4.1 + + + flatten + process-resources + + flatten + + + true + oss + + remove + remove + remove + remove + + + + + flatten-clean + clean + + clean + + + + + + org.apache.maven.plugins + maven-release-plugin + 3.0.0 + + sonatype + false + @{project.version} + true + + diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/SbmSupportRewriteConfiguration.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/SbmSupportRewriteConfiguration.java index 1baf190c3..e45c901dd 100644 --- a/sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/SbmSupportRewriteConfiguration.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/SbmSupportRewriteConfiguration.java @@ -22,6 +22,6 @@ * @author Fabian Krüger */ @AutoConfiguration -@Import(DiscoveryConfiguration.class) +@Import({DiscoveryConfiguration.class, ScannerConfiguration.class}) public class SbmSupportRewriteConfiguration { } diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/ScopeConfiguration.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/ScopeConfiguration.java index 3e589d8e5..d9d1cdf84 100644 --- a/sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/ScopeConfiguration.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/boot/autoconfigure/ScopeConfiguration.java @@ -20,6 +20,7 @@ import org.openrewrite.maven.MavenExecutionContextView; import org.openrewrite.maven.cache.MavenPomCache; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.sbm.scopes.ExecutionScope; @@ -63,6 +64,7 @@ ProjectMetadata projectMetadata() { } @Bean + @ConditionalOnMissingBean(name = "executionContextSupplier") Supplier executionContextSupplier() { return () -> new InMemoryExecutionContext(t -> {throw new RuntimeException(t);}); } diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java index 5004179a0..8f8c9a039 100644 --- a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java @@ -17,29 +17,97 @@ import lombok.Getter; import lombok.Setter; +import org.openrewrite.ExecutionContext; import org.openrewrite.java.JavaParser; +import org.openrewrite.java.internal.JavaTypeCache; import org.springframework.sbm.scopes.annotations.ScanScope; import org.springframework.stereotype.Component; -import java.util.function.Supplier; +import java.nio.charset.Charset; +import java.util.Collection; + -/** - * @author Fabian Krüger - */ -@Component -@ScanScope public class JavaParserBuilder extends JavaParser.Builder{ @Getter @Setter - private JavaParser.Builder builder; + private JavaParser.Builder delegate = JavaParser.fromJavaVersion(); - public Supplier getSupplier() { - return () -> builder; + @Override + public JavaParser build() { + return delegate.build(); } @Override - public JavaParser build() { - return builder.build(); + public JavaParser.Builder charset(Charset charset) { + return delegate.charset(charset); + } + + @Override + public JavaParser.Builder classpath(Collection classpath) { + return delegate.classpath(classpath); + } + + @Override + public JavaParser.Builder classpath(String... classpath) { + return delegate.classpath(classpath); + } + + @Override + public JavaParser.Builder classpathFromResources(ExecutionContext ctx, String... classpath) { + return delegate.classpathFromResources(ctx, classpath); + } + + @Override + public JavaParser.Builder classpath(byte[]... classpath) { + return delegate.classpath(classpath); + } + + @Override + public JavaParser.Builder logCompilationWarningsAndErrors(boolean logCompilationWarningsAndErrors) { + return delegate.logCompilationWarningsAndErrors(logCompilationWarningsAndErrors); + } + + @Override + public JavaParser.Builder typeCache(JavaTypeCache javaTypeCache) { + return delegate.typeCache(javaTypeCache); + } + + @Override + public JavaParser.Builder dependsOn(Collection collection) { + return delegate.dependsOn(collection); + } + + @Override + public JavaParser.Builder dependsOn(String... inputsAsStrings) { + return delegate.dependsOn(inputsAsStrings); + } + + @Override + public JavaParser.Builder styles(Iterable iterable) { + return delegate.styles(iterable); } + + @Override + public String getDslName() { + return delegate.getDslName(); + } + + // +// public Supplier getSupplier() { +// return () -> builder; +// } +// +// @Override +// public JavaParser build() { +// if(builder == null) { +// builder = JavaParser.fromJavaVersion(); +// } +// return builder.build(); +// } +// +// @Override +// public JavaParser.Builder classpath(Collection classpath) { +// return delegate.classpath(classpath); +// } } diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/MavenPasswordDecrypter.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/MavenPasswordDecrypter.java new file mode 100644 index 000000000..81aa7f57c --- /dev/null +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/MavenPasswordDecrypter.java @@ -0,0 +1,62 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.parsers; + +import lombok.RequiredArgsConstructor; +import org.openrewrite.maven.MavenSettings; +import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher; +import org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException; +import org.springframework.stereotype.Component; + +import java.nio.file.Path; +import java.util.List; + +/** + * Decrypt Maven Server passwords. + * + * Requires access to Maven security settings file (~/.settings-security.xml) to decrypt the server passwords provided in + * the server settings in Maven settings file (~/.m2/settings.xml) which are provided with {@link MavenSettings}. + * + * @author Fabian Krüger + */ +@Component +@RequiredArgsConstructor +// TODO: should be package private +public class MavenPasswordDecrypter { + + public void decryptMavenServerPasswords(SecDispatcher secDispatcher, MavenSettings mavenSettings, Path mavenSecuritySettingsFile) { + System.setProperty("settings.security", mavenSecuritySettingsFile.toString()); + if (mavenSettings.getServers() != null && mavenSettings.getServers().getServers() != null) { + List servers = mavenSettings.getServers().getServers(); + for (int i = 0; i < servers.size(); i++) { + MavenSettings.Server server = servers.get(i); + if (server.getPassword() != null) { + MavenSettings.Server serverWithDecodedPw = decryptPassword(secDispatcher, server); + servers.set(i, serverWithDecodedPw); + } + } + } + } + + private MavenSettings.Server decryptPassword(SecDispatcher secDispatcher, MavenSettings.Server server) { + try { + String decryptionResult = secDispatcher.decrypt(server.getPassword()); + return server.withPassword(decryptionResult); + } catch (SecDispatcherException e) { + throw new RuntimeException(e); + } + } +} diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/ProjectScanner.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/ProjectScanner.java index 894d6b748..46329739b 100644 --- a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/ProjectScanner.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/ProjectScanner.java @@ -40,32 +40,31 @@ */ @Slf4j @RequiredArgsConstructor -public -class ProjectScanner { +public class ProjectScanner { private final ResourceLoader resourceLoader; private final ParserProperties parserProperties; - public List scan(Path givenBaseDir) { - if(!givenBaseDir.isAbsolute()) { - givenBaseDir = givenBaseDir.toAbsolutePath().normalize(); + public List scan(Path baseDir) { + if(!baseDir.isAbsolute()) { + baseDir = baseDir.toAbsolutePath().normalize(); } - if(!givenBaseDir.toFile().exists()) { - throw new IllegalArgumentException("Provided path does not exist: " + givenBaseDir); + if(!baseDir.toFile().exists()) { + throw new IllegalArgumentException("Provided path does not exist: " + baseDir); } - final Path baseDir = givenBaseDir; - String unifiedPath = new LinuxWindowsPathUnifier().unifyPath(baseDir.toString() + "/**"); + Path absoluteRootPath = baseDir.toAbsolutePath(); + String unifiedPath = new LinuxWindowsPathUnifier().unifyPath(absoluteRootPath.toString() + "/**"); String pattern = "file:" + unifiedPath; try { Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources(pattern); - log.debug("Scanned %d resources in dir: '%s'".formatted(resources.length, baseDir.toString())); + log.debug("Scanned %d resources in dir: '%s'".formatted(resources.length, absoluteRootPath.toString())); - List resultingResources = filterIgnoredResources(baseDir, resources); + List resultingResources = filterIgnoredResources(absoluteRootPath, resources); int numResulting = resultingResources.size(); int numIgnored = resources.length - numResulting; log.debug("Scan returns %s resources, %d resources were ignored.".formatted(numResulting, numIgnored)); - log.trace("Resources resulting from scan: %s".formatted(resultingResources.stream().map(r -> baseDir.relativize(ResourceUtil.getPath(r)).toString()).collect(Collectors.joining(", ")))); + log.trace("Resources resulting from scan: %s".formatted(resultingResources.stream().map(r -> absoluteRootPath.relativize(ResourceUtil.getPath(r)).toString()).collect(Collectors.joining(", ")))); return resultingResources; } catch (IOException e) { @@ -103,7 +102,7 @@ private boolean isAccepted(Path baseDir, Resource r, List pathMatch }) .findFirst(); if(isIgnored.isPresent() && log.isInfoEnabled()) { - log.info("Ignoring resource '%s'.".formatted(baseDir.relativize(ResourceUtil.getPath(r)))); + log.info("Ignoring scanned resource '%s'.".formatted(baseDir.relativize(ResourceUtil.getPath(r)))); } return isIgnored.isEmpty(); } diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/openrewrite/RewriteExecutionContext.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteExecutionContext.java similarity index 98% rename from components/sbm-core/src/main/java/org/springframework/sbm/openrewrite/RewriteExecutionContext.java rename to sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteExecutionContext.java index cdcdb8f4b..466957d28 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/openrewrite/RewriteExecutionContext.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteExecutionContext.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.sbm.openrewrite; +package org.springframework.sbm.parsers; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @@ -29,7 +29,6 @@ import java.util.function.Supplier; - @Getter @Slf4j public class RewriteExecutionContext implements ExecutionContext { diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/openrewrite/RewriteExecutionContextErrorHandler.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteExecutionContextErrorHandler.java similarity index 97% rename from components/sbm-core/src/main/java/org/springframework/sbm/openrewrite/RewriteExecutionContextErrorHandler.java rename to sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteExecutionContextErrorHandler.java index b3545b1b8..b8a7aea5f 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/openrewrite/RewriteExecutionContextErrorHandler.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteExecutionContextErrorHandler.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.sbm.openrewrite; +package org.springframework.sbm.parsers; import lombok.Getter; import lombok.Setter; diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteParserConfiguration.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteParserConfiguration.java index 3dfe72928..b173406ed 100644 --- a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteParserConfiguration.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteParserConfiguration.java @@ -29,6 +29,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.sbm.boot.autoconfigure.ParserPropertiesPostProcessor; +import org.springframework.sbm.boot.autoconfigure.ScannerConfiguration; import org.springframework.sbm.parsers.events.RewriteParsingEventListenerAdapter; import org.springframework.sbm.scopes.ProjectMetadata; import org.springframework.sbm.scopes.ScanScope; @@ -47,7 +48,7 @@ * @author Fabian Krüger */ @Slf4j -@AutoConfiguration(after = ScopeConfiguration.class) +@AutoConfiguration(after = {ScopeConfiguration.class}) @EnableConfigurationProperties(ParserProperties.class) @Import({ScanScope.class, ScopeConfiguration.class}) public class RewriteParserConfiguration { @@ -81,8 +82,14 @@ MavenMojoProjectParserFactory projectParserFactory() { } @Bean - ProvenanceMarkerFactory provenanceMarkerFactory(MavenMojoProjectParserFactory orojectParserFactory) { - return new ProvenanceMarkerFactory(orojectParserFactory); + ProvenanceMarkerFactory provenanceMarkerFactory(MavenMojoProjectParserFactory projectParserFactory) { + return new ProvenanceMarkerFactory(projectParserFactory); + } + + @Bean + @org.springframework.sbm.scopes.annotations.ScanScope + JavaParserBuilder javaParserBuilder() { + return new JavaParserBuilder(); } @Bean @@ -119,8 +126,8 @@ MavenMojoProjectParserPrivateMethods mavenMojoProjectParserPrivateMethods(MavenM } @Bean - SourceFileParser sourceFileParser(MavenModelReader modelReader, MavenMojoProjectParserPrivateMethods mavenMojoProjectParserPrivateMethods) { - return new SourceFileParser(modelReader, parserProperties, mavenMojoProjectParserPrivateMethods); + SourceFileParser sourceFileParser(MavenModelReader modelReader, MavenMojoProjectParserPrivateMethods mavenMojoProjectParserPrivateMethods, JavaParserBuilder javaParserBuilder) { + return new SourceFileParser(parserProperties, mavenMojoProjectParserPrivateMethods, javaParserBuilder); } @Bean @@ -152,23 +159,27 @@ RewriteProjectParser rewriteProjectParser( ProvenanceMarkerFactory provenanceMarkerFactory, BuildFileParser buildFileParser, SourceFileParser sourceFileParser, - StyleDetector styleDeteector, + StyleDetector styleDetector, ParserProperties parserProperties, ParsingEventListener parsingEventListener, ApplicationEventPublisher eventPublisher, ScanScope scanScope, - ConfigurableListableBeanFactory beanFactory) { + ConfigurableListableBeanFactory beanFactory, + ProjectScanner projectScanner, + ExecutionContext executionContext) { return new RewriteProjectParser( mavenExecutor, provenanceMarkerFactory, buildFileParser, sourceFileParser, - styleDeteector, + styleDetector, parserProperties, parsingEventListener, eventPublisher, scanScope, - beanFactory); + beanFactory, + projectScanner, + executionContext); } @Bean diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteProjectParser.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteProjectParser.java index 7edd4fcaf..684e99d0c 100644 --- a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteProjectParser.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/RewriteProjectParser.java @@ -22,6 +22,7 @@ import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.openrewrite.ExecutionContext; +import org.openrewrite.InMemoryExecutionContext; import org.openrewrite.SourceFile; import org.openrewrite.marker.Marker; import org.openrewrite.maven.AbstractRewriteMojo; @@ -88,6 +89,15 @@ public class RewriteProjectParser { private final ApplicationEventPublisher eventPublisher; private final ScanScope scanScope; private final ConfigurableListableBeanFactory beanFactory; + private final ProjectScanner scanner; + private final ExecutionContext executionContext; + + + public RewriteProjectParsingResult parse(Path baseDir) { + Set ignorePatterns = parserProperties.getIgnoredPathPatterns(); + List resources = scanner.scan(baseDir); + return this.parse(baseDir, resources, executionContext); + } /** * Parse given {@link Resource}s in {@code baseDir} to OpenRewrite AST representation. @@ -127,10 +137,6 @@ public RewriteProjectParsingResult parse(Path givenBaseDir, List resou // TODO: where to retrieve styles from? --> see AbstractRewriteMojo#getActiveStyles() & AbstractRewriteMojo#loadStyles() List styles = List.of(); - // retrieve all pom files from all modules in the active reactor build - // TODO: Move this to a build file sort and filter component, for now it could use Maven's DefaultGraphBuilder - // this requires File to be used and thus binds the component to file access. - AtomicReference atomicReference = new AtomicReference<>(); withMavenSession(baseDir, mavenSession -> { @@ -171,7 +177,7 @@ public RewriteProjectParsingResult parse(Path givenBaseDir, List resou } private void withMavenSession(Path baseDir, Consumer consumer) { - List goals = List.of("clean", "install"); + List goals = List.of("clean", "package"); log.debug("Successfully finished goals %s".formatted(goals)); mavenExecutor.onProjectSucceededEvent(baseDir, goals, event -> consumer.accept(event.getSession())); } diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/SourceFileParser.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/SourceFileParser.java index 99c8369ec..757b64688 100644 --- a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/SourceFileParser.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/SourceFileParser.java @@ -28,7 +28,6 @@ import org.openrewrite.xml.tree.Xml; import org.springframework.core.io.Resource; import org.springframework.sbm.utils.ResourceUtil; -import org.springframework.stereotype.Component; import java.nio.file.Path; import java.nio.file.PathMatcher; @@ -42,11 +41,11 @@ @Slf4j @RequiredArgsConstructor -class SourceFileParser { +public class SourceFileParser { - private final MavenModelReader modelReader; private final ParserProperties parserProperties; private final MavenMojoProjectParserPrivateMethods mavenMojoProjectParserPrivateMethods; + private final JavaParserBuilder javaParserBuilder; public List parseOtherSourceFiles( Path baseDir, @@ -186,10 +185,5 @@ private Set pathsToOtherMavenProjects(MavenProject mavenProject, Path modu .filter(p -> !p.getFile().toPath().equals(moduleBuildFile)) .map(p -> p.getFile().toPath().getParent()) .collect(Collectors.toSet()); - // FIXME: - // filter build files - // create relative paths to all other build files - // return result -// return Set.of(); } } diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/utils/JavaHelper.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/utils/JavaHelper.java new file mode 100644 index 000000000..25214fb9e --- /dev/null +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/utils/JavaHelper.java @@ -0,0 +1,30 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.utils; + +/** + * @author Fabian Krüger + */ +public class JavaHelper { + public static String lowercaseFirstChar(String name) { + return Character.toLowerCase(name.charAt(0)) + name.substring(1); + } + + public static String uppercaseFirstChar(String name) { + if(name.isEmpty()) return name; + return Character.toUpperCase(name.charAt(0)) + name.substring(1); + } +} diff --git a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/MavenPomCacheTest.java b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/MavenPomCacheTest.java index c890aa1b9..de9de8713 100644 --- a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/MavenPomCacheTest.java +++ b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/MavenPomCacheTest.java @@ -27,6 +27,7 @@ import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; +import org.springframework.sbm.boot.autoconfigure.ScannerConfiguration; import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.util.ReflectionTestUtils; @@ -48,7 +49,7 @@ public class MavenPomCacheTest { class GivenA64BitSystem { @Nested - @SpringBootTest(classes = {RewriteParserConfiguration.class, ScopeConfiguration.class}, properties = {"parser.pomCacheEnabled=true", "parser.pomCacheDirectory=target"}) + @SpringBootTest(classes = {ScannerConfiguration.class}, properties = {"parser.pomCacheEnabled=true", "parser.pomCacheDirectory=target"}) @DirtiesContext class WhenPomCacheIsEnabledIsTrue { @@ -76,7 +77,7 @@ void compositePomCacheShouldBeUsed2() { } @Nested - @SpringBootTest(classes = RewriteParserConfiguration.class, properties = {"parser.pomCacheEnabled=false"}) + @SpringBootTest(classes = ScannerConfiguration.class, properties = {"parser.pomCacheEnabled=false"}) @DirtiesContext class WhenPomCacheIsEnabledIsFalse { @@ -94,7 +95,7 @@ void InMemoryMavenPomCacheShouldBeUsed() { @Nested @DirtiesContext - @SpringBootTest(classes = RewriteParserConfiguration.class, properties = {"parser.pomCacheEnabled=true"}) + @SpringBootTest(classes = ScannerConfiguration.class, properties = {"parser.pomCacheEnabled=true"}) @SetSystemProperty(key = "sun.arch.data.model", value = "32") class GivenA32BitSystem { @@ -111,7 +112,7 @@ void shouldUseInMemoryMavenPomCache() { @Nested @DirtiesContext @Import(GivenCustomCacheProvided.CustomCacheConfig.class) - @SpringBootTest(classes = RewriteParserConfiguration.class, properties = {"parser.pomCacheEnabled=true", "customCache=true"}) + @SpringBootTest(classes = ScannerConfiguration.class, properties = {"parser.pomCacheEnabled=true", "customCache=true"}) class GivenCustomCacheProvided { @Autowired diff --git a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/ParserPropertiesTest.java b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/ParserPropertiesTest.java index c79d570f0..a21b8df72 100644 --- a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/ParserPropertiesTest.java +++ b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/ParserPropertiesTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.sbm.boot.autoconfigure.ScannerConfiguration; import static org.assertj.core.api.Assertions.assertThat; @@ -28,7 +29,7 @@ class ParserPropertiesTest { @Nested - @SpringBootTest(classes = {RewriteParserConfiguration.class}) + @SpringBootTest(classes = {ScannerConfiguration.class}) public class GivenDefaultProperties { @Autowired diff --git a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserIntegrationTest.java b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserIntegrationTest.java index 56cff4d43..de0ca36f3 100644 --- a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserIntegrationTest.java +++ b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserIntegrationTest.java @@ -22,6 +22,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.event.EventListener; +import org.springframework.sbm.boot.autoconfigure.ScannerConfiguration; import org.springframework.sbm.parsers.events.FinishedParsingResourceEvent; import java.nio.file.Path; @@ -33,7 +34,7 @@ /** * @author Fabian Krüger */ -@SpringBootTest(classes = {RewriteParserConfiguration.class, RewriteMavenProjectParserIntegrationTest.TestEventListener.class}) +@SpringBootTest(classes = {ScannerConfiguration.class, RewriteMavenProjectParserIntegrationTest.TestEventListener.class}) public class RewriteMavenProjectParserIntegrationTest { @Autowired diff --git a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserTest.java b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserTest.java index 5240749fa..4d2fbd02f 100644 --- a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserTest.java +++ b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteMavenProjectParserTest.java @@ -16,6 +16,7 @@ package org.springframework.sbm.parsers; import org.intellij.lang.annotations.Language; +import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; @@ -27,7 +28,6 @@ import org.openrewrite.InMemoryExecutionContext; import org.openrewrite.Parser; import org.openrewrite.SourceFile; -import org.openrewrite.internal.lang.Nullable; import org.openrewrite.java.marker.JavaProject; import org.openrewrite.java.marker.JavaSourceSet; import org.openrewrite.java.marker.JavaVersion; @@ -39,6 +39,7 @@ import org.openrewrite.marker.ci.GithubActionsBuildEnvironment; import org.openrewrite.maven.MavenExecutionContextView; import org.openrewrite.maven.MavenSettings; +import org.openrewrite.maven.cache.*; import org.openrewrite.maven.cache.InMemoryMavenPomCache; import org.openrewrite.maven.cache.LocalMavenArtifactCache; import org.openrewrite.maven.cache.MavenArtifactCache; @@ -51,6 +52,7 @@ import org.openrewrite.xml.tree.Xml; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationEventPublisher; +import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.core.io.Resource; import org.springframework.sbm.parsers.events.RewriteParsingEventListenerAdapter; @@ -169,6 +171,8 @@ public static void main(String[] args){ ResourceUtil.write(tempDir, resources); parserProperties.setIgnoredPathPatterns(Set.of("**/testcode/**", "testcode/**", ".rewrite-cache/**")); + parserProperties.setPomCacheEnabled(true); // org.openrewrite.maven.pomCache will be CompositeMavenPomCache + // call SUT RewriteProjectParsingResult parsingResult = sut.parse( tempDir, @@ -269,24 +273,26 @@ void parseMultiModule1_WithCustomParser() { Path baseDir = getMavenProject("multi-module-1"); ExecutionContext ctx; ctx = new InMemoryExecutionContext(t -> t.printStackTrace()); - MavenModelReader mavenModelReader = new MavenModelReader(); MavenMojoProjectParserFactory mavenMojoProjectParserFactory = new MavenMojoProjectParserFactory(parserProperties); MavenArtifactCache mavenArtifactCache = new LocalMavenArtifactCache(Paths.get(System.getProperty("user.home"), ".m2", "repository")); @Nullable MavenSettings mavenSettings = null; Consumer onError = (t) -> {throw new RuntimeException(t);}; MavenMojoProjectParserPrivateMethods mavenMojoParserPrivateMethods = new MavenMojoProjectParserPrivateMethods(mavenMojoProjectParserFactory, new RewriteMavenArtifactDownloader(mavenArtifactCache, mavenSettings, onError)); + JavaParserBuilder javaParserBuilder = new JavaParserBuilder(); RewriteProjectParser rpp = new RewriteProjectParser( new MavenExecutor(new MavenExecutionRequestFactory(new MavenConfigFileParser()), new MavenPlexusContainer()), new ProvenanceMarkerFactory(mavenMojoProjectParserFactory), new BuildFileParser(), - new SourceFileParser(mavenModelReader, parserProperties, mavenMojoParserPrivateMethods), + new SourceFileParser(parserProperties, mavenMojoParserPrivateMethods, javaParserBuilder), new StyleDetector(), parserProperties, mock(ParsingEventListener.class), mock(ApplicationEventPublisher.class), scanScope, - beanFactory + beanFactory, + new ProjectScanner(new DefaultResourceLoader(), parserProperties), + ctx ); Set ignoredPatters = Set.of(); @@ -368,10 +374,10 @@ private static void verifyExecutionContext(RewriteProjectParsingResult parsingRe assertThat( messages.get("org.openrewrite.parser.charset") ) - .isSameAs( - ParsingExecutionContextView.view(resultingExecutionContext).getCharset() - ); - assertThat(ParsingExecutionContextView.view(resultingExecutionContext).getCharset()).isEqualTo(Charset.defaultCharset()); + .isSameAs( + ParsingExecutionContextView.view(resultingExecutionContext).getCharset() + ); + assertThat(ParsingExecutionContextView.view(resultingExecutionContext).getCharset()).isEqualTo(Charset.forName("UTF-8")); // 4 assertThat( @@ -410,8 +416,8 @@ private static void verifyExecutionContext(RewriteProjectParsingResult parsingRe // 8 assertThat( messages.get("org.openrewrite.maven.pomCache") - ).isNull(); - assertThat(MavenExecutionContextView.view(resultingExecutionContext).getPomCache()).isInstanceOf(InMemoryMavenPomCache.class); + ).isInstanceOf(CompositeMavenPomCache.class); + assertThat(MavenExecutionContextView.view(resultingExecutionContext).getPomCache()).isInstanceOf(CompositeMavenPomCache.class); // assertThat(MavenExecutionContextView.view(resultingExecutionContext).getPomCache()).isInstanceOf(CompositeMavenPomCache.class); // 9 diff --git a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserIntegrationTest.java b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserIntegrationTest.java index 5e36ac82a..5dd11d14c 100644 --- a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserIntegrationTest.java +++ b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserIntegrationTest.java @@ -15,15 +15,22 @@ */ package org.springframework.sbm.parsers; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.openrewrite.InMemoryExecutionContext; +import org.openrewrite.java.tree.J; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; import org.springframework.sbm.boot.autoconfigure.ScannerConfiguration; +import org.springframework.sbm.parsers.events.FinishedParsingResourceEvent; +import org.springframework.sbm.parsers.events.StartedParsingProjectEvent; +import org.springframework.sbm.parsers.events.SuccessfullyParsedProjectEvent; +import org.springframework.sbm.boot.autoconfigure.ScannerConfiguration; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -40,6 +47,9 @@ public class RewriteProjectParserIntegrationTest { @Autowired ProjectScanner projectScanner; + @Autowired + RewriteMavenProjectParser mavenProjectParser; + @Test @DisplayName("parseCheckstyle") void parseCheckstyle() { @@ -49,7 +59,6 @@ void parseCheckstyle() { assertThat(parsingResult.sourceFiles().stream().map(sf -> sf.getSourcePath().toString()).toList()).contains("checkstyle/rules.xml"); assertThat(parsingResult.sourceFiles().stream().map(sf -> sf.getSourcePath().toString()).toList()).contains("checkstyle/suppressions.xml"); } - @Test @DisplayName("parse4Modules") void parse4Modules() { @@ -62,8 +71,16 @@ void parse4Modules() { assertThat(parsingResult.sourceFiles()).hasSize(4); } - @Autowired - RewriteMavenProjectParser mavenProjectParser; + @Test + @DisplayName("testFailingProject") + // FIXME: Succeeds with RewriteMavenProjectParser + void testFailingProject() { + Path baseDir = Path.of("./testcode/maven-projects/failing"); + RewriteProjectParsingResult parsingResult = sut.parse(baseDir); + assertThat(parsingResult.sourceFiles().get(1)).isInstanceOf(J.CompilationUnit.class); + J.CompilationUnit cu = (J.CompilationUnit) parsingResult.sourceFiles().get(1); + assertThat(cu.getTypesInUse().getTypesInUse().stream().map(t -> t.toString()).anyMatch(t -> t.equals("javax.validation.constraints.Min"))).isTrue(); + } @Test @DisplayName("parseResources") diff --git a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserTest.java b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserTest.java index bc6b5a7ee..9a8a09aef 100644 --- a/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserTest.java +++ b/sbm-support-rewrite/src/test/java/org/springframework/sbm/parsers/RewriteProjectParserTest.java @@ -31,6 +31,7 @@ import org.openrewrite.tree.ParsingExecutionContextView; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationEventPublisher; +import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.sbm.scopes.ScanScope; import org.springframework.sbm.test.util.DummyResource; @@ -101,19 +102,22 @@ void parseSimpleMavenProject(@TempDir Path tempDir) { throw new RuntimeException(t); }; MavenMojoProjectParserPrivateMethods mavenMojoParserPrivateMethods = new MavenMojoProjectParserPrivateMethods(mavenMojoProjectParserFactory, new RewriteMavenArtifactDownloader(mavenArtifactCache, mavenSettings, onError)); + ExecutionContext executionContext = new InMemoryExecutionContext(t -> {throw new RuntimeException(t);}); RewriteProjectParser projectParser = new RewriteProjectParser( new MavenExecutor(new MavenExecutionRequestFactory(new MavenConfigFileParser()), new MavenPlexusContainer()), new ProvenanceMarkerFactory(mavenMojoProjectParserFactory), new BuildFileParser(), - new SourceFileParser(mavenModelReader, parserProperties, mavenMojoParserPrivateMethods), + new SourceFileParser(parserProperties, mavenMojoParserPrivateMethods, new JavaParserBuilder()), new StyleDetector(), parserProperties, mock(ParsingEventListener.class), mock(ApplicationEventPublisher.class), new ScanScope(), - mock(ConfigurableListableBeanFactory.class) + mock(ConfigurableListableBeanFactory.class), + new ProjectScanner(new DefaultResourceLoader(), parserProperties), + executionContext ); - ExecutionContext executionContext = new InMemoryExecutionContext(t -> t.printStackTrace()); + List parsedFiles = new ArrayList<>(); ParsingExecutionContextView.view(executionContext).setParsingListener( new ParsingEventListener() { @@ -124,6 +128,8 @@ public void parsed(Parser.Input input, SourceFile sourceFile) { } ); + // TODO: Provide Scanner with excludes + // TODO: Make RewriteProjectParser publish ApplicationEvents List resources = List.of( new DummyResource(basePath.resolve("pom.xml"), pomXml), new DummyResource(basePath.resolve("src/main/java/com/example/MyMain.java"), javaClass));