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..090ae61d4 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 @@ -126,7 +126,7 @@ public void recipeUpdatesBootDependenciesAndParentVersion() throws IOException { sut.apply(projectContext); - assertThat(expectedPom).isEqualTo(projectContext.getBuildFile().print()); + assertThat(expectedPom).isEqualToNormalizingNewlines(projectContext.getBuildFile().print()); SpringBootApplicationProperties applicationProperties = projectContext.search(new SpringBootApplicationPropertiesResourceListFilter()).get(0); assertThat(applicationProperties.hasChanges()).isFalse(); @@ -200,7 +200,7 @@ public void recipeJpaInitPropertyAdded() throws IOException { ); SpringBootApplicationProperties applicationProperties = projectContext.search(new SpringBootApplicationPropertiesResourceListFilter()).get(0); - assertThat(applicationProperties.getProperty("spring.datasource.initialization-order").get()).isEqualTo("after-jpa"); + assertThat(applicationProperties.getProperty("spring.datasource.initialization-order")).hasValue("after-jpa"); verify(ui).askUserYesOrNo(InitDataSourceAfterJpaInitAction.QUESTION); verifyNoMoreInteractions(ui); @@ -218,7 +218,7 @@ public void recipeJpaInitPropertyAddedForSchemaSql() throws IOException { // sut.apply(projectContext); // // SpringBootApplicationProperties applicationProperties = projectContext.getFilteredResources(new SpringBootApplicationPropertiesResourceListFilter()).get(0); -// assertThat(applicationProperties.getProperty("spring.datasource.initialization-order").get()).isEqualTo("after-jpa"); +// assertThat(applicationProperties.getProperty("spring.datasource.initialization-order")).hasValue("after-jpa"); // // verify(ui).askUserYesOrNo(InitDataSourceAfterJpaInitAction.QUESTION); // verifyNoMoreInteractions(ui); diff --git a/components/recipe-test-support/src/main/java/org/springframework/sbm/test/RecipeIntegrationTestSupport.java b/components/recipe-test-support/src/main/java/org/springframework/sbm/test/RecipeIntegrationTestSupport.java index 3b868ecba..c01356229 100644 --- a/components/recipe-test-support/src/main/java/org/springframework/sbm/test/RecipeIntegrationTestSupport.java +++ b/components/recipe-test-support/src/main/java/org/springframework/sbm/test/RecipeIntegrationTestSupport.java @@ -34,7 +34,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; -import java.util.stream.Collectors; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @@ -50,6 +49,7 @@ public static Path getResultDir(String toDirName) { } private static final String TARGET_DIR = "./target/testcode"; + private static final String TEMPLATES = "./src/main/resources/templates"; @Setter(AccessLevel.PRIVATE) private Path rootDir; @Setter(AccessLevel.PRIVATE) @@ -68,10 +68,10 @@ public static RecipeIntegrationTestSupport withTargetDir(Path targetDir) { public static RecipeIntegrationTestSupport initializeProject(Path sourceDir, String targetDirName) { try { Resource classPathResource = new FileSystemResource(sourceDir.toString()); - File to = getResultDir(targetDirName).toFile(); + File to = getResultDir(targetDirName).toFile().getCanonicalFile(); FileUtils.deleteDirectory(to); FileUtils.forceMkdir(to); - FileUtils.copyDirectory(classPathResource.getFile(), to); + FileUtils.copyDirectory(classPathResource.getFile().getCanonicalFile(), to); RecipeIntegrationTestSupport recipeIntegrationTestSupport = new RecipeIntegrationTestSupport(); recipeIntegrationTestSupport.setRootDir(to.toPath()); recipeIntegrationTestSupport.setSourceDir(sourceDir); @@ -91,9 +91,11 @@ public static RecipeIntegrationTestSupport initializeProject(String targetDirNam public void andApplyRecipe(String recipeName) { SpringBeanProvider.run(ctx -> { - if (new File("./src/main/resources/templates").exists()) { - Configuration configuration = ctx.getBean("configuration", Configuration.class); // FIXME: two freemarker configurations exist - configuration.setDirectoryForTemplateLoading(new File("./src/main/resources/templates")); + Path templatesPath = Path.of(TEMPLATES).normalize().toAbsolutePath(); + if (Files.exists(templatesPath)) { + // FIXME: two freemarker configurations exist + Configuration configuration = ctx.getBean("configuration", Configuration.class); + configuration.setDirectoryForTemplateLoading(templatesPath.toFile().getCanonicalFile()); } ScanCommand scanCommand = ctx.getBean(ScanCommand.class); @@ -108,7 +110,7 @@ public void andApplyRecipe(String recipeName) { Recipe recipe = recipesFound.stream() .filter(r -> r.getName().equals(recipeName)) .findFirst() - .orElseThrow(() -> new RuntimeException("Could not find recipe '" + recipeName + "' in list of recipes found: " + recipesFound)); + .orElseThrow(() -> new RuntimeException("Could not find recipe '%s' in list of recipes found: %s".formatted(recipeName, recipesFound))); ApplyCommand applyCommand = ctx.getBean(ApplyCommand.class); applyCommand.execute(projectContext, recipe.getName()); }, @@ -134,12 +136,12 @@ public void andApplyRecipeComparingWithExpected(String recipeName) { List result; try (Stream walk = Files.walk(expectedProject)) { result = walk.filter(Files::isRegularFile) - .map(f -> expectedProject.relativize(f)) - .collect(Collectors.toList()); + .map(expectedProject::relativize) + .toList(); } - result.stream() - .forEach(r -> assertThat(expectedProject.resolve(r)).hasSameTextualContentAs(migratedProject.resolve(r))); + result.forEach(r -> assertThat(expectedProject.resolve(r).normalize().toAbsolutePath()) + .hasSameTextualContentAs(migratedProject.resolve(r).normalize().toAbsolutePath())); } catch (Exception exception) { throw new RuntimeException(exception); } diff --git a/components/sbm-core/pom.xml b/components/sbm-core/pom.xml index ad5daf447..fe2cb2f5a 100644 --- a/components/sbm-core/pom.xml +++ b/components/sbm-core/pom.xml @@ -172,6 +172,11 @@ jackson-dataformat-xml 2.14.1 + + org.openrewrite + rewrite-test + test + diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/build/migration/actions/AddMinimalPomXml.java b/components/sbm-core/src/main/java/org/springframework/sbm/build/migration/actions/AddMinimalPomXml.java index 0dbf77410..496baa350 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/build/migration/actions/AddMinimalPomXml.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/build/migration/actions/AddMinimalPomXml.java @@ -30,6 +30,7 @@ import org.springframework.sbm.engine.recipe.AbstractAction; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Path; @@ -59,7 +60,7 @@ public class AddMinimalPomXml extends AbstractAction { @Override public void apply(ProjectContext context) { String projectDir = context.getProjectRootDirectory().toString(); - String projectName = projectDir.replace(" ", "-").substring(projectDir.lastIndexOf("/") + 1); + String projectName = projectDir.replace(" ", "-").substring(projectDir.lastIndexOf(File.separator) + 1); Map params = new HashMap<>(); params.put("groupId", "com.example.change"); params.put("artifactId", projectName); diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/common/migration/actions/DocumentationExtraction.java b/components/sbm-core/src/main/java/org/springframework/sbm/common/migration/actions/DocumentationExtraction.java index 94c0a556b..40728845b 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/common/migration/actions/DocumentationExtraction.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/common/migration/actions/DocumentationExtraction.java @@ -23,6 +23,7 @@ import org.springframework.sbm.java.api.Member; import org.springframework.sbm.java.impl.OpenRewriteType; +import java.io.File; import java.nio.file.Path; import java.util.List; @@ -36,7 +37,7 @@ public void apply(ProjectContext context) { Path sourcePath = module.getBaseJavaSourceLocation().getSourceFolder(); Path sourceDir = rootDirectory.relativize(sourcePath); module.getMainJavaSources().stream() - .filter(js -> js.getResource().getAbsolutePath().endsWith(sourceDir.resolve(js.getPackageName().replace(".", "/") + "/" + js.getResource().getAbsolutePath().getFileName()))) + .filter(js -> filterPath(js, sourceDir)) .map(JavaSource::getTypes) .flatMap(List::stream) .filter(t -> OpenRewriteType.class.isAssignableFrom(t.getClass())) @@ -52,6 +53,12 @@ public void apply(ProjectContext context) { } + private static boolean filterPath(JavaSource js, Path sourceDir) { + String packageName = js.getPackageName().replace(".", File.separator); + Path resolved = sourceDir.resolve(packageName).resolve(js.getResource().getAbsolutePath().getFileName()); + return js.getResource().getAbsolutePath().endsWith(resolved); + } + private boolean filterActions(OpenRewriteType javaSource) { Class aClass = getaClass(javaSource); return Action.class.isAssignableFrom(aClass); diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/engine/context/ProjectContext.java b/components/sbm-core/src/main/java/org/springframework/sbm/engine/context/ProjectContext.java index 975de0c69..4fa0d1c4c 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/engine/context/ProjectContext.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/engine/context/ProjectContext.java @@ -54,7 +54,7 @@ public class ProjectContext { private final RewriteMigrationResultMerger resultMerger; public ProjectContext(JavaRefactoringFactory javaRefactoringFactory, Path projectRootDirectory, ProjectResourceSet projectResources, BasePackageCalculator basePackageCalculator, JavaParser javaParser, ExecutionContext executionContext, RewriteMigrationResultMerger resultMerger) { - this.projectRootDirectory = projectRootDirectory.toAbsolutePath(); + this.projectRootDirectory = projectRootDirectory.normalize().toAbsolutePath(); this.projectResources = projectResources; this.javaRefactoringFactory = javaRefactoringFactory; this.basePackageCalculator = basePackageCalculator; diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/ResourceParser.java b/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/ResourceParser.java index ae093f58a..a43eaaa35 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/ResourceParser.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/project/parser/ResourceParser.java @@ -34,6 +34,7 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.Resource; import org.springframework.sbm.engine.events.StartedScanningProjectResourceEvent; +import org.springframework.sbm.utils.LinuxWindowsPathUnifier; import org.springframework.stereotype.Component; import java.io.IOException; @@ -107,7 +108,7 @@ public List parse(Path baseDir, List relevantResources, Li parserAndParserInputMappings.put(plainTextParser, new ArrayList<>()); parserInputs.forEach(r -> { - Parser parser = parserAndParserInputMappings.keySet().stream() + Parser parser = parserAndParserInputMappings.keySet().stream() .filter(p -> p.accept(r)) .findFirst() .orElseThrow(() -> new RuntimeException("Could not find matching parser for " + r.getPath())); @@ -141,7 +142,7 @@ private Stream getSourceFileStream(Path baseDir, ExecutionContext ct .getValue() .stream() .map(resource -> (List) parseSingleResource(baseDir, ctx, e, resource)) - .flatMap(elem -> Stream.ofNullable(elem)) + .flatMap(Stream::ofNullable) .flatMap(List::stream); } @@ -149,7 +150,7 @@ private List parseSingleResource(Path baseDir, ExecutionCo try { return e.getKey().parseInputs(List.of(resource), baseDir, ctx); } catch(Exception ex) { - if(resource.getPath().toString().contains("src/test/resources")) { + if (LinuxWindowsPathUnifier.unifyPath(resource.getPath()).contains("src/test/resources")) { log.error("Could not parse resource '%s' using parser %s. Exception was: %s".formatted(resource.getPath(), e.getKey().getClass().getName(), ex.getMessage())); return null; } else { diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/project/resource/ProjectResourceSet.java b/components/sbm-core/src/main/java/org/springframework/sbm/project/resource/ProjectResourceSet.java index 4c34c768e..53a1ab1a3 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/project/resource/ProjectResourceSet.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/project/resource/ProjectResourceSet.java @@ -19,9 +19,7 @@ import java.nio.file.Path; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; -import java.util.stream.Collectors; import java.util.stream.Stream; // TODO: make package private @@ -65,63 +63,18 @@ public int size() { return projectResources.size(); } -// /** -// * @deprecated use {@link ProjectContext#getFilteredResources(ProjectResourcesFilter)} -// * with {@link org.springframework.sbm.project.resource.filter.GenericTypeFilter} -// */ -// @Deprecated(forRemoval = true) -// public List> getProjections(Class projectionClass) { -// return typeFilteredList(projectionClass); -// } - public int indexOf(Path absolutePath) { return projectResources.stream() .map(ProjectResource::getAbsolutePath) - .collect(Collectors.toList()) + .toList() .indexOf(absolutePath); } void clearDeletedResources() { - Iterator> iterator = this.projectResources.iterator(); - while(iterator.hasNext()) { - RewriteSourceFileHolder current = iterator.next(); - if(current.isDeleted()) { - iterator.remove(); - } - } + this.projectResources.removeIf(BaseProjectResource::isDeleted); } public Stream> streamIncludingDeleted() { return projectResources.stream(); } -// -// public Stream filteredStream(ProjectResourceFilter filter) { -// return projectResources.stream() -// .filter(filter::satisfies); -// } - -// public Stream classFilteredStream(Class clazz) { -// return filteredStream(pr -> clazz.isAssignableFrom(pr.getClass())) -// .map(clazz::cast); -// } -// -// public Stream> typeFilteredStream(Class type) { -// return filteredStream(pr -> Objects.nonNull(pr.getType()) && type.isAssignableFrom(pr.getType())) -// .map(pr -> (RewriteSourceFileHolder)pr); -// } -// -// public List filteredList(ProjectResourceFilter filter) { -// return filteredStream(filter) -// .collect(Collectors.toList()); -// } -// -// public List classFilteredList(Class clazz) { -// return classFilteredStream(clazz) -// .collect(Collectors.toList()); -// } -// -// public List> typeFilteredList(Class type) { -// return typeFilteredStream(type) -// .collect(Collectors.toList()); -// } } diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/build/Issue54Test.java b/components/sbm-core/src/test/java/org/springframework/sbm/build/Issue54Test.java index a559cb1b5..fda498354 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/build/Issue54Test.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/build/Issue54Test.java @@ -15,20 +15,16 @@ */ package org.springframework.sbm.build; -import org.assertj.core.api.Assertions; import org.intellij.lang.annotations.Language; import org.junit.jupiter.api.Test; import org.openrewrite.maven.MavenParser; -import org.openrewrite.maven.internal.RawPom; import org.openrewrite.maven.tree.Dependency; import org.openrewrite.maven.tree.MavenResolutionResult; -import org.openrewrite.maven.tree.Pom; import org.openrewrite.xml.tree.Xml; import org.springframework.sbm.GitHubIssue; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; -import java.io.ByteArrayInputStream; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -83,9 +79,9 @@ void scanMultiModuleProjectWithOptionalPropertyProvidedByParent() { List poms = MavenParser.builder().build().parse(pomA, pomB); - assertThat( - poms.get(1).getMarkers().findFirst(MavenResolutionResult.class).get().getPom().getProperties().get("boolean-variable") - ).isEqualTo("false"); + assertThat(poms.get(1).getMarkers().findFirst(MavenResolutionResult.class)) + .hasValueSatisfying(mrr -> assertThat(mrr.getPom().getProperties()).containsEntry("boolean-variable", "false") + ); List requestedDependencies = poms.get(1).getMarkers().findFirst(MavenResolutionResult.class).get().getPom().getRequestedDependencies(); diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/build/api/Module_searchTestJava_Test.java b/components/sbm-core/src/test/java/org/springframework/sbm/build/api/Module_searchTestJava_Test.java index 6980086aa..e98b04306 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/build/api/Module_searchTestJava_Test.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/build/api/Module_searchTestJava_Test.java @@ -66,9 +66,7 @@ void withNoClassesInSrcTestJava_providesEmptyProjectResources() { ProjectContext context = builder.build(); - verifySearchTest(context, projectResourceSet -> { - assertThat(projectResourceSet.list()).isEmpty(); - }, ""); + verifySearchTest(context, projectResourceSet -> assertThat(projectResourceSet.list()).isEmpty(), ""); } @Test 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 81a9eedea..72fff7378 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 @@ -2134,9 +2134,9 @@ void deserializePluginConfiguration() { plugin.getArtifactId().equals("maven-compiler-plugin")) .findAny().orElseThrow(); - assertThat(compilerPlugin.getConfiguration().getDeclaredStringValue("source").get()).isEqualTo("${source}"); - assertThat(compilerPlugin.getConfiguration().getDeclaredStringValue("target").get()).isEqualTo("17"); - assertThat(compilerPlugin.getConfiguration().getDeclaredStringValue("fork").get()).isEqualTo("false"); + assertThat(compilerPlugin.getConfiguration().getDeclaredStringValue("source")).hasValue("${source}"); + assertThat(compilerPlugin.getConfiguration().getDeclaredStringValue("target")).hasValue("17"); + assertThat(compilerPlugin.getConfiguration().getDeclaredStringValue("fork")).hasValue("false"); } @Test diff --git a/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/ForgivingParsingOfTestResourcesTest.java b/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/ForgivingParsingOfTestResourcesTest.java index d3bb48170..c3d3e3e25 100644 --- a/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/ForgivingParsingOfTestResourcesTest.java +++ b/components/sbm-core/src/test/java/org/springframework/sbm/project/parser/ForgivingParsingOfTestResourcesTest.java @@ -23,6 +23,7 @@ import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.sbm.project.resource.TestProjectContext; import org.springframework.sbm.test.TestProjectContextInfo; +import org.springframework.sbm.utils.LinuxWindowsPathUnifier; import java.util.List; @@ -53,9 +54,9 @@ void test_renameMe() { List> parsedResources = context.getProjectResources().list(); assertThat(parsedResources).hasSize(3); assertThat(parsedResources.get(0).getSourcePath().toString()).isEqualTo("pom.xml"); - assertThat(parsedResources.get(1).getSourcePath().toString()).isEqualTo("src/test/resources/one.yaml"); + assertThat(LinuxWindowsPathUnifier.unifyPath(parsedResources.get(1).getSourcePath())).isEqualTo("src/test/resources/one.yaml"); // src/test/resources/error.yaml is ignored - assertThat(parsedResources.get(2).getSourcePath().toString()).isEqualTo("src/test/resources/three.yaml"); + assertThat(LinuxWindowsPathUnifier.unifyPath(parsedResources.get(2).getSourcePath())).isEqualTo("src/test/resources/three.yaml"); ParsingExecutionContextView contextView = ParsingExecutionContextView.view(projectContextInfo.executionContext()); assertThat(contextView.getParseFailures()).hasSize(1); assertThat(contextView.getParseFailures().get(0).getText()).isEqualTo(""" 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..45a65d5bd 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 @@ -42,7 +42,7 @@ void parse() { String xml = "content"; RewriteSourceFileHolder parse = sut.parse(Path.of(".").toAbsolutePath(), Path.of("some.xml"), xml); assertThat(parse.getSourceFile().getRoot().getName()).isEqualTo("foo"); - assertThat(parse.getSourceFile().getRoot().getValue().get()).isEqualTo("content"); + assertThat(parse.getSourceFile().getRoot().getValue()).hasValue("content"); } @Test @@ -51,7 +51,7 @@ void testParse() { List> rewriteSourceFileHolders = sut.parse(List.of(file), Path.of("./testcode").toAbsolutePath().normalize(), new RewriteExecutionContext()); RewriteSourceFileHolder sourceFileHolder = rewriteSourceFileHolders.get(0); assertThat(sourceFileHolder.getSourceFile().getRoot().getName()).isEqualTo("shiporder"); - assertThat(sourceFileHolder.getSourceFile().getRoot().getChild("orderperson").get().getValue().get()).isEqualTo("John Smith"); + assertThat(sourceFileHolder.getSourceFile().getRoot().getChild("orderperson").get().getValue()).hasValue("John Smith"); } @Test 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 99973a6c8..62ab38ff2 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 @@ -17,6 +17,7 @@ import freemarker.template.Configuration; import org.apache.commons.lang3.SystemUtils; +import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.openrewrite.ExecutionContext; import org.openrewrite.maven.cache.InMemoryMavenPomCache; @@ -337,12 +338,12 @@ public Builder addRegistrar(ProjectResourceWrapper projectResourceWrapper) { * The source Path is 'src/main/java' in the root module and the path inside is calculated from package declaration if it exists. */ @Deprecated - public Builder withJavaSource(String sourceCode) { + public Builder withJavaSource(@Language("java") String sourceCode) { return withJavaSources(sourceCode); } - public Builder withJavaSource(Path sourcePathDir, String sourceCode) { + public Builder withJavaSource(Path sourcePathDir, @Language("java") String sourceCode) { if (sourcePathDir.isAbsolute()) { throw new IllegalArgumentException("Source path must be relative to project root dir."); } @@ -352,11 +353,11 @@ public Builder withJavaSource(Path sourcePathDir, String sourceCode) { return this; } - public Builder withJavaSource(String sourcePath, String sourceCode) { + public Builder withJavaSource(String sourcePath, @Language("java") String sourceCode) { return withJavaSource(Path.of(sourcePath), sourceCode); } - public Builder withJavaSourceInModule(String modulePath, String sourceCode) { + public Builder withJavaSourceInModule(String modulePath, @Language("java") String sourceCode) { Path path = Path.of(modulePath); if (path.isAbsolute()) { throw new IllegalArgumentException("Source path must be relative to project root dir."); @@ -371,7 +372,7 @@ public Builder withJavaSourceInModule(String modulePath, String sourceCode) { * Adds the given Java sources to the list of compiled Java sources. * The source Path is 'src/main/java' in the root module and the path inside is calculated from package declaration if exists. */ - public Builder withJavaSources(String... sourceCodes) { + public Builder withJavaSources(@Language("java") String... sourceCodes) { Arrays.asList(sourceCodes).forEach(sourceCode -> { String fqName = JavaSourceUtil.retrieveFullyQualifiedClassFileName(sourceCode); Path sourcePath = Path.of("src/main/java").resolve(fqName); @@ -386,7 +387,7 @@ public Builder withJavaSources(String... sourceCodes) { * Adds the given Java sources to the list of compiled Java sources. * The source Path is 'src/test/java' in the root module and the path inside is calculated from package declaration if exists. */ - public Builder withJavaTestSources(String... sourceCodes) { + public Builder withJavaTestSources(@Language("java") String... sourceCodes) { Arrays.asList(sourceCodes).forEach(sourceCode -> { String fqName = JavaSourceUtil.retrieveFullyQualifiedClassFileName(sourceCode); Path sourcePath = Path.of("src/test/java").resolve(fqName); @@ -408,18 +409,18 @@ public Builder withBuildFileHavingDependencies(String... dependencyCoordinate) { return this; } - public Builder withMavenRootBuildFileSource(String pomSource) { + public Builder withMavenRootBuildFileSource(@Language("xml") String pomSource) { this.resourcesWithRelativePaths.put(Path.of("pom.xml"), pomSource); return this; } @Deprecated - public Builder withMavenBuildFileSource(Path path, String pomSource) { + public Builder withMavenBuildFileSource(Path path, @Language("xml") String pomSource) { this.withProjectResource(projectRoot.resolve(path).normalize(), pomSource); return this; } - public Builder withMavenBuildFileSource(String sourceDir, String pomSource) { + public Builder withMavenBuildFileSource(String sourceDir, @Language("xml") String pomSource) { Path sourcePath = Path.of(sourceDir); if (!sourceDir.endsWith("pom.xml")) { sourcePath = sourcePath.resolve("pom.xml"); @@ -443,6 +444,7 @@ public Builder withDummyRootBuildFile() { throw new IllegalArgumentException("ProjectContext already contains pom.xml files."); } + @Language("xml") String xml = """ @@ -479,7 +481,10 @@ public ProjectContext serializeProjectContext(Path targetDir) { public ProjectContext build() { verifyValidBuildFileSetup(); + Path pathOfPomXml = Path.of("pom.xml"); + if (!containsAnyPomXml()) { + @Language("xml") String xml = """ @@ -497,7 +502,7 @@ public ProjectContext build() { .replace("{{dependencies}}", getDependenciesSection()) .replace("{{springParentPom}}", getSpringParentPomSection()); - resourcesWithRelativePaths.put(Path.of("pom.xml"), xml); + resourcesWithRelativePaths.put(pathOfPomXml, xml); } @@ -545,9 +550,8 @@ public ProjectContext build() { // replace with mocks if (mockedBuildFile != null) { // TODO: add javadoc. - Path pomPath = Path.of("pom.xml"); - when(mockedBuildFile.getSourcePath()).thenReturn(pomPath); - projectContext.getProjectResources().replace(projectRoot.resolve(pomPath).normalize(), mockedBuildFile); + when(mockedBuildFile.getSourcePath()).thenReturn(pathOfPomXml); + projectContext.getProjectResources().replace(projectRoot.resolve(pathOfPomXml).normalize(), mockedBuildFile); } return projectContext; diff --git a/components/sbm-openrewrite/pom.xml b/components/sbm-openrewrite/pom.xml index a7daaa8e0..f67f80e72 100644 --- a/components/sbm-openrewrite/pom.xml +++ b/components/sbm-openrewrite/pom.xml @@ -104,6 +104,11 @@ spring-boot-starter-test test + + org.openrewrite + rewrite-test + test + diff --git a/components/sbm-openrewrite/src/test/java/org/springframework/sbm/java/OpenRewriteTestSupport.java b/components/sbm-openrewrite/src/test/java/org/springframework/sbm/java/OpenRewriteTestSupport.java index ff9bc94ca..3960674e7 100644 --- a/components/sbm-openrewrite/src/test/java/org/springframework/sbm/java/OpenRewriteTestSupport.java +++ b/components/sbm-openrewrite/src/test/java/org/springframework/sbm/java/OpenRewriteTestSupport.java @@ -15,8 +15,10 @@ */ package org.springframework.sbm.java; +import org.intellij.lang.annotations.Language; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.openrewrite.*; +import org.openrewrite.test.RewriteTest; import org.springframework.sbm.java.util.JavaSourceUtil; import org.springframework.sbm.testhelper.common.utils.TestDiff; import org.assertj.core.api.Assertions; @@ -42,7 +44,7 @@ public class OpenRewriteTestSupport { * The first class name and package is used to retrieve the file path of the J.CompilationUnit. * * @param classpath entries in artifact:gruopId:version format. - * @param sourceCodes + * @param sourceCodes source code * @return list of J.CompilationUnits */ public static List createCompilationUnitsFromStrings(List classpath, String... sourceCodes) { @@ -61,7 +63,7 @@ public static List createCompilationUnitsFromStrings(List * The first class name and package is used to retrieve the file path of the J.CompilationUnit. * - * @param sourceCodes + * @param sourceCodes source code * @return list of J.CompilationUnits */ public static List createCompilationUnitsFromStrings(String... sourceCodes) { @@ -73,7 +75,7 @@ public static List createCompilationUnitsFromStrings(String.. *

* The first class name and package is used to retrieve the file path of the J.CompilationUnit. * - * @param sourceCode + * @param sourceCode source code * @return the created J.CompilationUnit */ public static J.CompilationUnit createCompilationUnitFromString(String sourceCode) { @@ -112,7 +114,7 @@ public static

void verifyChange(Supplier> v * @param expected source code after applying the visitor * @param classpath required for resolving dependencies to create a CompilationUnit from given */ - public static

void verifyChange(JavaIsoVisitor visitor, String given, String expected, String... classpath) { + public static void verifyChange(JavaIsoVisitor visitor, String given, String expected, String... classpath) { J.CompilationUnit compilationUnit = createCompilationUnit(given, classpath); verifyChange(visitor, compilationUnit, expected); } @@ -133,7 +135,7 @@ public static

void verifyChange(JavaIsoVisitor visitor, St * @param given CompilationUnit the visitor will be applied on * @param expected source code after applying the visitor */ - public static

void verifyChange(JavaIsoVisitor visitor, J.CompilationUnit given, String expected) { + public static void verifyChange(JavaIsoVisitor visitor, J.CompilationUnit given, String expected) { final Collection newChanges = refactor(given, visitor).getResults(); Assertions.assertThat(newChanges.iterator().hasNext()).as("No change was found.").isTrue(); Assertions.assertThat(given.printAll()) @@ -148,7 +150,7 @@ public static

void verifyChange(JavaIsoVisitor visitor, J. /** * Verifies that applying the visitor to given results in expected. *

- * It's does not check that given equals before in the change. + * It does not check that given equals before in the change. * Use this method if you had to create a CompilationUnit, e.g. to define a scope for the tested visitor. * If the visitor is not scoped it is probably easier (and less caller code) * to use @@ -160,7 +162,7 @@ public static

void verifyChange(JavaIsoVisitor visitor, J. * @param given CompilationUnit the visitor will be applied on * @param expected source code after applying the visitor */ - public static

void verifyChangeIgnoringGiven(JavaIsoVisitor visitor, String given, String expected, String... classpath) { + public static void verifyChangeIgnoringGiven(JavaIsoVisitor visitor, String given, String expected, String... classpath) { J.CompilationUnit compilationUnit = createCompilationUnit(given, classpath); final Collection newChanges = refactor(compilationUnit, visitor).getResults(); Assertions.assertThat(newChanges.iterator().hasNext()).as("No change was found.").isTrue(); @@ -176,7 +178,7 @@ public static

void verifyChangeIgnoringGiven(JavaIsoVisitor void verifyNoChange(Supplier> visitor, String given, String... classpath) { + public static void verifyNoChange(Supplier> visitor, String given, String... classpath) { J.CompilationUnit compilationUnit = createCompilationUnit(given, classpath); final Collection newChanges = refactor(compilationUnit, visitor.get()).getResults(); Assertions.assertThat(newChanges).isEmpty(); @@ -189,7 +191,7 @@ public static

void verifyNoChange(Supplier> * @param given the source code to apply the visitor on * @param classpath required to compile the given sourceCode in 'groupId:artifactId:version' format */ - public static

void verifyNoChange(JavaIsoVisitor visitor, String given, String... classpath) { + public static void verifyNoChange(JavaIsoVisitor visitor, String given, String... classpath) { J.CompilationUnit compilationUnit = createCompilationUnit(given, classpath); final Collection newChanges = refactor(compilationUnit, visitor).getResults(); Assertions.assertThat(newChanges).isEmpty(); @@ -201,7 +203,7 @@ public static

void verifyNoChange(JavaIsoVisitor visitor, * @param given sourceCode * @param classpath provided in 'groupId:artifactId:version' format */ - public static J.CompilationUnit createCompilationUnit(String given, String... classpath) { + public static J.CompilationUnit createCompilationUnit(@Language("java") String given, String... classpath) { JavaParser javaParser = getJavaParser(classpath); List compilationUnits = javaParser @@ -241,30 +243,8 @@ public static List getClasspathFiles(String... classpath) { .collect(Collectors.toList()); } - private static

RecipeRun refactor(J.CompilationUnit given, JavaVisitor visitor) { - GenericOpenRewriteTestRecipe> recipe = new GenericOpenRewriteTestRecipe<>(visitor); + private static RecipeRun refactor(J.CompilationUnit given, JavaVisitor visitor) { + Recipe recipe = RewriteTest.toRecipe(() -> visitor); return recipe.run(List.of(given)); } - - /** - * Helper class to avoid circular dependency to the module containing {@code GenericOpenRewriteRecipe} - */ - private static class GenericOpenRewriteTestRecipe> extends Recipe { - - private final V visitor; - - public GenericOpenRewriteTestRecipe(V visitor) { - this.visitor = visitor; - } - - @Override - protected TreeVisitor getVisitor() { - return visitor; - } - - @Override - public String getDisplayName() { - return visitor.getClass().getSimpleName(); - } - } } diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportAction.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportAction.java index 252a28830..b8ebe6e46 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportAction.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportAction.java @@ -38,7 +38,6 @@ import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; -import java.util.stream.Stream; /** * Special Action generates a Spring Boot Upgrade report. @@ -117,14 +116,10 @@ public Condition getCondition() { @Override public void apply(ProjectContext context) { - - List renderedSections = new ArrayList<>(); sections.stream() .filter(s -> s.shouldRender(context)) - .forEach(section -> { - renderedSections.add(section.render(context)); - }); + .forEach(section -> renderedSections.add(section.render(context))); Map data = dataProvider.getData(context, sections); String renderedHeader = renderTemplate("header", header, data); @@ -160,15 +155,12 @@ private String renderReport(String renderedHeader, List sections, String } private String renderRunAllRecipesButton() { - - StringBuilder sb = new StringBuilder(); - List recipes = sections .stream() .flatMap(section -> section.getRemediation().getPossibilities().stream()) - .map(p -> p.getRecipe()) + .map(RemediationPossibility::getRecipe) .filter(recipe -> recipe != null && !recipe.isEmpty()) - .collect(Collectors.toList()); + .toList(); String renderedRecipeInputs = IntStream .range(0, recipes.size()) @@ -196,15 +188,12 @@ private String renderRunAllRecipesButton() { } private String renderTemplate(String key, String content, Map data) { - try (StringWriter writer = new StringWriter()) { freemarkerSupport.getStringLoader().putTemplate(key, content); Template report = freemarkerSupport.getConfiguration().getTemplate(key); report.process(data, writer); return writer.toString(); - } catch (IOException e) { - throw new RuntimeException(e); - } catch (TemplateException e) { + } catch (IOException | TemplateException e) { throw new RuntimeException(e); } } diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportSection.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportSection.java index 4c88f35d7..7836802ca 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportSection.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportSection.java @@ -16,7 +16,6 @@ package org.springframework.sbm.boot.upgrade_27_30.report; import com.fasterxml.jackson.annotation.JsonIgnore; -import freemarker.core.ParseException; import freemarker.template.*; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -24,9 +23,7 @@ import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.sbm.build.api.BuildFile; import org.springframework.sbm.engine.context.ProjectContext; -import org.springframework.sbm.engine.recipe.Condition; import javax.validation.constraints.NotEmpty; import java.io.IOException; @@ -38,8 +35,9 @@ /** * A section in a generated report for Spring Boot 3 upgrade, rendered as Asciidoc from a freemarker template string. - * The {@link Helper} is condition and evaluates if the section should be rendered. - * If the section should be rendered, the {@link Helper} provides the data extracted from {@link ProjectContext} to render the template. + * The {@link SpringBootUpgradeReportSectionHelper Helper} is condition and evaluates if the section should be rendered. + * If the section should be rendered, the {@link SpringBootUpgradeReportSectionHelper Helper} provides the data extracted + * from {@link ProjectContext} to render the template. * * @author Fabian Krüger */ @@ -50,7 +48,17 @@ public class SpringBootUpgradeReportSection { public static final String CHANGE_HEADER = "What Changed"; public static final String AFFECTED = "Why is the application affected"; public static final String REMEDIATION = "Remediation"; + private static final String GITHUB_ISSUE = "**Issue:** https://github.com/spring-projects-experimental/spring-boot-migrator/issues/%1$d[#%1$d^, role=\"ext-link\"] + %n"; + private static final String GITHUB_CONTRIBUTOR = "https://github.com/%1$s[@%1$s^, role=\"ext-link\"]"; private static final String ls = System.lineSeparator(); + + public static final String BUTTON_CODE = """ + ++++ +

+
+ ++++ + """.replace("\n", System.lineSeparator()); + /** * The spring project(s)/modules this change comes from. * @@ -99,8 +107,6 @@ public boolean shouldRender(ProjectContext context) { return helper.evaluate(context); } - - public String render(ProjectContext context) { if (getHelper().evaluate(context)) { Map params = getHelper().getData(); @@ -109,19 +115,12 @@ public String render(ProjectContext context) { String templateContent = buildTemplate(); renderTemplate(params, writer, templateContent); return writer.toString(); - } catch (TemplateException e) { - throw new RuntimeException(e); - } catch (TemplateNotFoundException e) { - throw new RuntimeException(e); - } catch (ParseException e) { - throw new RuntimeException(e); - } catch (MalformedTemplateNameException e) { - throw new RuntimeException(e); - } catch (IOException e) { + } catch (TemplateException | IOException e) { throw new RuntimeException(e); } } - throw new IllegalArgumentException("Could not render Section '"+ getTitle()+"', evaluating the context returned false"); + + throw new IllegalArgumentException("Could not render Section '%s', evaluating the context returned false".formatted(getTitle())); } private void renderTemplate(Map params, StringWriter writer, String templateContent) throws IOException, TemplateException { @@ -160,7 +159,7 @@ private void renderRemediationDescription(StringBuilder sb) { } private void renderRemediationTitle(StringBuilder sb) { - sb.append("==== " + REMEDIATION).append(ls); + sb.append("==== %s%n".formatted(REMEDIATION)); } private void renderAffectedSubSection(StringBuilder sb) { @@ -169,7 +168,7 @@ private void renderAffectedSubSection(StringBuilder sb) { } private void renderAffectedDescription(StringBuilder sb) { - sb.append(getAffected()).append(ls); + sb.append("%s%n".formatted(getAffected())); } private void renderChangeSubSection(StringBuilder sb) { @@ -178,7 +177,7 @@ private void renderChangeSubSection(StringBuilder sb) { } private void renderAffectedTitle(StringBuilder sb) { - sb.append("==== " + AFFECTED).append(ls); + sb.append("==== %s%n".formatted(AFFECTED)); } private void renderChangeDecription(StringBuilder sb) { @@ -195,23 +194,23 @@ private void renderLineBreak(StringBuilder sb) { } void renderGitHubInfo(StringBuilder sb) { - if(gitHubIssue != null) { - sb.append("**Issue:** https://github.com/spring-projects-experimental/spring-boot-migrator/issues/").append(gitHubIssue).append("[#").append(gitHubIssue).append("^, role=\"ext-link\"] ").append(" + ").append(ls); + if (gitHubIssue != null) { + sb.append(GITHUB_ISSUE.formatted(gitHubIssue)); } - if(contributors != null) { + if (contributors != null) { List authors = getAuthors(); sb.append("**Contributors:** "); - String authorsString = authors.stream().map(a -> "https://github.com/" + a.getHandle() + "[@" + a.getHandle() + "^, role=\"ext-link\"]").collect(Collectors.joining(", ")); - sb.append(authorsString).append(" + ").append(ls); + String authorsString = authors.stream().map(a -> GITHUB_CONTRIBUTOR.formatted(a.getHandle())).collect(Collectors.joining(", ")); + sb.append(authorsString).append("%s + %n".formatted(authorsString)); } - if(projects != null){ - String projectsList = projects.stream().collect(Collectors.joining(", ")); - sb.append("**Projects:** ").append(projectsList).append(ls); + if (projects != null) { + String projectsList = String.join(", ", projects); + sb.append("**Projects:** %s%n".formatted(projectsList)); } } private void renderSectionTitle(StringBuilder sb) { - sb.append("=== ").append(title).append(ls); + sb.append("=== %s%n".formatted(title)); } public List getAuthors() { @@ -235,11 +234,11 @@ public List getAuthors() { private String renderRemediation() { StringBuilder sb = new StringBuilder(); - if(remediation.getDescription() != null) { - sb.append(remediation.getDescription()).append(ls); + if (remediation.getDescription() != null) { + sb.append("%s%n".formatted(remediation.getDescription())); } sb.append(ls); - if(remediation.getPossibilities().isEmpty()) { + if (remediation.getPossibilities().isEmpty()) { renderResourcesList(sb, remediation); renderRecipeButton(sb, remediation.getRecipe()); } else { @@ -249,14 +248,13 @@ private String renderRemediation() { } private void renderRemediationPossibility(StringBuilder sb, RemediationPossibility p) { - sb.append("===== ").append(p.getTitle()).append(ls); - sb.append(p.getDescription()).append(ls).append(ls); + sb.append("===== %s%n%s%n%n".formatted(p.getTitle(), p.getDescription())); renderResourcesList(sb, p); renderRecipeButton(sb, p.getRecipe()); } private void renderRecipeButton(StringBuilder sb, String recipe) { - if(recipe != null && !recipe.isEmpty()) { + if (recipe != null && !recipe.isEmpty()) { sb.append(ls).append(ls); /* - """ + """.replace("\n", System.lineSeparator()) ); } } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/ChangeJavaxPackagesToJakartaTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/ChangeJavaxPackagesToJakartaTest.java index b4d49d011..acab05e8e 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/ChangeJavaxPackagesToJakartaTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/ChangeJavaxPackagesToJakartaTest.java @@ -15,14 +15,15 @@ */ package org.springframework.sbm.boot.upgrade_27_30; +import org.intellij.lang.annotations.Language; import org.junit.jupiter.api.Test; import org.openrewrite.java.ChangePackage; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.java.api.JavaSource; import org.springframework.sbm.project.resource.TestProjectContext; +import org.springframework.sbm.utils.LinuxWindowsPathUnifier; import java.util.List; -import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; @@ -31,34 +32,43 @@ public class ChangeJavaxPackagesToJakartaTest { @Test void collectingJavaxPackages() { - String javaClass1 = - "package com.example;\n" + - "import javax.money.MonetaryAmount;\n" + - "public class SomeClass {\n" + - " public MonetaryAmount convertToEntityAttribute() {\n" + - " return null;\n" + - " }\n" + - "}"; - - String javaClass2 = - "package com.example;\n" + - "import javax.persistence.Converter;\n" + - "public class SomeClass2 {\n" + - " public Converter getConverter() {\n" + - " return null;\n" + - " }\n" + - "}"; + @Language("java") + String javaClass1 = """ + package com.example; + import javax.money.MonetaryAmount; + public class SomeClass { + public MonetaryAmount convertToEntityAttribute() { + return null; + } + } + """; + + @Language("java") + String javaClass2 = """ + package com.example; + import javax.persistence.Converter; + public class SomeClass2 { + public Converter getConverter() { + return null; + } + } + """; + + @Language("java") + String javaClass3 = """ + package com.example; + public class NoImports {} + """; + + @Language("java") + String javaClass4 = """ + package com.example; + import java.math.BigDecimal; + public class OtherImports { + private BigDecimal number; + } + """; - String javaClass3 = - "package com.example;\n" + - "public class NoImports {}"; - - String javaClass4 = - "package com.example;\n" + - "import java.math.BigDecimal;\n" + - "public class OtherImports {\n" + - " private BigDecimal number;\n" + - "}"; ProjectContext context = TestProjectContext.buildProjectContext() .withBuildFileHavingDependencies("javax.money:money-api:1.1") .withJavaSource("src/main/java", javaClass1) @@ -67,13 +77,13 @@ void collectingJavaxPackages() { .withJavaSource("src/main/java", javaClass4) .build(); - List matches = context.getProjectJavaSources().asStream() + List matches = context.getProjectJavaSources().stream() .filter(js -> js.hasImportStartingWith("javax.")) - .collect(Collectors.toList()); + .toList(); assertThat(matches).hasSize(2); - assertThat(matches.get(0).getSourcePath().toString()).isEqualTo("src/main/java/com/example/SomeClass.java"); - assertThat(matches.get(1).getSourcePath().toString()).isEqualTo("src/main/java/com/example/SomeClass2.java"); + assertThat(LinuxWindowsPathUnifier.unifyPath(matches.get(0).getSourcePath())).isEqualTo("src/main/java/com/example/SomeClass.java"); + assertThat(LinuxWindowsPathUnifier.unifyPath(matches.get(1).getSourcePath())).isEqualTo("src/main/java/com/example/SomeClass2.java"); matches.forEach(m -> System.out.println(m.getSourcePath())); } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/ApacheSolrRepositorySectionBuilderTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/ApacheSolrRepositorySectionBuilderTest.java index 96098e894..1e7ded5d3 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/ApacheSolrRepositorySectionBuilderTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/ApacheSolrRepositorySectionBuilderTest.java @@ -55,7 +55,7 @@ void givenAContextWithSolrRepository_applySectionBuilder_validateReport() { Section section = sut.build(context); String rendered = SectionRendererTestUtil.render(section); - assertThat(rendered).isEqualTo( + assertThat(rendered).isEqualToNormalizingNewlines( """ === `Spring Data ApacheSolr` support has been removed Support for `Spring Data ApacheSolr` has been removed in Spring Framework 6 diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/config/ConfigRecipeTestHelper.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/config/ConfigRecipeTestHelper.java index 663451043..90d5b90d2 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/config/ConfigRecipeTestHelper.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/config/ConfigRecipeTestHelper.java @@ -28,16 +28,18 @@ import org.openrewrite.yaml.tree.Yaml; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; +import static org.assertj.core.api.Assertions.assertThat; + public class ConfigRecipeTestHelper { public static List runRecipeOnYaml(@Language("yml") String source, String recipeName) { @@ -57,18 +59,16 @@ public static List runRecipeOnProperties(@Language("properties") String } public static Pair provideIO(String inputFilePath) throws IOException { + String fileContent = Files.readString(Path.of(inputFilePath)); + String[] k = fileContent.split("expected:.*%n".formatted()); - InputStream data = new FileInputStream(inputFilePath); - - String fileContent = new String(data.readAllBytes()); - String[] k = fileContent.split("expected:.*\n"); - - return new ImmutablePair<>(k[0].replaceAll("input:.*\n", ""), k[1]); + return new ImmutablePair<>(k[0].replaceAll("input:.*%n".formatted(), ""), k[1]); } public static Stream provideFiles(String folder, String fileType) throws URISyntaxException { URL url = RemovedPropertyTest.class.getResource(folder); + assertThat(url).isNotNull(); File f = Paths.get(url.toURI()).toFile(); diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportTestSupport.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportTestSupport.java index c2cf043c6..501081262 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportTestSupport.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportTestSupport.java @@ -17,6 +17,7 @@ import lombok.Getter; import lombok.Setter; +import org.intellij.lang.annotations.Language; import org.springframework.sbm.boot.upgrade_27_30.report.yaml.SpringBootUpgradeReportActionDeserializer; import org.springframework.sbm.boot.upgrade_27_30.report.yaml.SpringBootUpgradeReportYamlDeserializationConfiguration; import org.springframework.sbm.engine.context.ProjectContext; @@ -32,6 +33,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -57,7 +59,7 @@ public static SectionProjectContext generatedReport() { } public static class SectionProjectContext { - private BuilderData builderData; + private final BuilderData builderData; public SectionProjectContext(BuilderData builderData) { this.builderData = builderData; @@ -71,20 +73,20 @@ public Assertion fromProjectContext(ProjectContext context) { } public static class Assertion { - private BuilderData builderData; + private final BuilderData builderData; public Assertion(BuilderData builderData) { this.builderData = builderData; } - public void shouldRenderAs(String expectedOutput) { + public void shouldRenderAs(@Language("adoc") String expectedOutput) { shouldRenderAs(expectedOutput, defaultMap()); } - public void shouldRenderAs(String expectedOutput, Map templateVariables) { + public void shouldRenderAs(@Language("adoc") String expectedOutput, Map templateVariables) { String expectedOutputRendered = replacePlaceHolders(expectedOutput, templateVariables); - Consumer assertion = (s) -> assertThat(s).isEqualTo(expectedOutputRendered); + Consumer assertion = (s) -> assertThat(s).isEqualToNormalizingNewlines(expectedOutputRendered); verify(assertion); } @@ -92,17 +94,16 @@ public void shouldNotRender() { verifyDoesNotRender(); } - public void shouldStartWith(String expectedOutput) { + public void shouldStartWith(@Language("adoc") String expectedOutput) { shouldStartWith(expectedOutput, defaultMap()); } - public void shouldStartWith(String expectedOutput, Map templateVariables) { + public void shouldStartWith(@Language("adoc") String expectedOutput, Map templateVariables) { String expectedOutputRendered = replacePlaceHolders(expectedOutput, templateVariables); Consumer assertion = (s) -> assertThat(s).as(TestDiff.of(s, expectedOutputRendered)).startsWith(expectedOutputRendered); verify(assertion); } - private Map defaultMap() { String path = Path .of(".") @@ -113,8 +114,7 @@ private Map defaultMap() { } private void verifyDoesNotRender() { - if(SectionBuilderData.class.isInstance(builderData)) { - SectionBuilderData sectionBuilderData = SectionBuilderData.class.cast(builderData); + if (builderData instanceof SectionBuilderData sectionBuilderData) { withRecipes(recipes -> { Recipe recipe = recipes.getRecipeByName("sbu30-report").get(); SpringBootUpgradeReportAction action = (SpringBootUpgradeReportAction) recipe.getActions().get(0); @@ -122,18 +122,17 @@ private void verifyDoesNotRender() { List matchingSections = sections .stream() .filter(s -> s.getTitle().equals(builderData.getTitle())) - .collect(Collectors.toList()); + .toList(); - if(matchingSections.size() != 1) { - fail("Found " + matchingSections.size() + " Sections with title '" + builderData.getTitle() + "'."); + if (matchingSections.size() != 1) { + fail("Found %d Sections with title '%s'.".formatted(matchingSections.size(), builderData.getTitle())); } SpringBootUpgradeReportSection sectionUnderTest = matchingSections.get(0); bruteForceProjectContextIntoProjectContextHolder(builderData.getContext(), action); assertThat(sectionUnderTest.getHelper().evaluate(sectionBuilderData.getContext())).isFalse(); }); - } else if(ReportBuilderData.class.isInstance(builderData)) { - ReportBuilderData reportBuilderData = ReportBuilderData.class.cast(builderData); + } else if (builderData instanceof ReportBuilderData reportBuilderData) { withRecipes(recipes -> { Recipe recipe = recipes.getRecipeByName("sbu30-report").get(); SpringBootUpgradeReportAction action = (SpringBootUpgradeReportAction) recipe.apply(reportBuilderData.getContext()).get(0); @@ -148,7 +147,7 @@ private void verifyDoesNotRender() { * Another nasty hack required to make the ProjectContext available in ProjectContextHolder which is required by the * hacked implementation of Spring Upgrade report web application. * The {@code SpringBootUpgradeReportFileSystemRenderer} accesses the {@code ProjectContext} through - * {@ProjectContextHolder} but its set in {@code ScanShellCommand} which is not available here. + * {@link ProjectContextHolder} but its set in {@code ScanShellCommand} which is not available here. */ private void bruteForceProjectContextIntoProjectContextHolder(ProjectContext context, SpringBootUpgradeReportAction action) { ProjectContextHolder contextHolder = new ProjectContextHolder(); @@ -157,8 +156,7 @@ private void bruteForceProjectContextIntoProjectContextHolder(ProjectContext con } private void verify(Consumer assertion) { - if(ReportBuilderData.class.isInstance(builderData)) { - ReportBuilderData reportBuilderData = ReportBuilderData.class.cast(builderData); + if (builderData instanceof ReportBuilderData reportBuilderData) { withRecipes(recipes -> { Recipe recipe = recipes.getRecipeByName("sbu30-report").get(); SpringBootUpgradeReportAction action = (SpringBootUpgradeReportAction) recipe.getActions().get(0); @@ -166,19 +164,20 @@ private void verify(Consumer assertion) { // ReflectionTestUtils.setField(action, "upgradeReportProcessor", (SpringBootUpgradeReportFileSystemRenderer) s -> assertion.accept(s)); action.apply(reportBuilderData.getContext()); }); - } else if(SectionBuilderData.class.isInstance(builderData)) { + } else if(builderData instanceof SectionBuilderData) { withRecipes(recipes -> { Recipe recipe = recipes.getRecipeByName("sbu30-report").get(); SpringBootUpgradeReportAction action = (SpringBootUpgradeReportAction) recipe.getActions().get(0); bruteForceProjectContextIntoProjectContextHolder(builderData.getContext(), action); List sections = (List) ReflectionTestUtils.getField(recipe.getActions().get(0), "sections"); + assertThat(sections).isNotNull(); List matchingSections = sections .stream() .filter(s -> s.getTitle().equals(builderData.getTitle())) - .collect(Collectors.toList()); + .toList(); - if(matchingSections.size() != 1) { - fail("Found " + matchingSections.size() + " Sections with title '" + builderData.getTitle() + "'."); + if (matchingSections.size() != 1) { + fail("Found %d Sections with title '%s'.".formatted(matchingSections.size(), builderData.getTitle())); } SpringBootUpgradeReportSection sectionUnderTest = matchingSections.get(0); @@ -198,11 +197,11 @@ private String removeGitHubInfoFromExpectedOutput(SpringBootUpgradeReportSection // if GitHub info is not given StringBuilder sb = new StringBuilder(); sectionUnderTest.renderGitHubInfo(sb); - if( ! renderedSectionWithoutButtonCode.startsWith("=== " + sectionUnderTest.getTitle() +"\n" + sb.toString())) { - fail("Missing GitHub info: " + sb.toString() + " rendered section was: \n " + renderedSectionWithoutButtonCode); + if( ! renderedSectionWithoutButtonCode.startsWith("=== " + sectionUnderTest.getTitle() + System.lineSeparator() + sb)) { + fail("Missing GitHub info: %s rendered section was:%s%s".formatted(sb, System.lineSeparator(), renderedSectionWithoutButtonCode)); } - String asciidocTitle = "=== " + sectionUnderTest.getTitle() + "\n"; - return renderedSectionWithoutButtonCode.replace(asciidocTitle + sb.toString(), asciidocTitle); + String asciidocTitle = "=== " + sectionUnderTest.getTitle() + System.lineSeparator(); + return renderedSectionWithoutButtonCode.replace(asciidocTitle + sb, asciidocTitle); } /** @@ -211,17 +210,10 @@ private String removeGitHubInfoFromExpectedOutput(SpringBootUpgradeReportSection */ private String replaceRecipeButtonCodeFromExpectedOutput(SpringBootUpgradeReportSection sectionUnderTest, String renderedSection) { List buttonCodes = new ArrayList<>(); - if(sectionUnderTest.getRemediation().getPossibilities().isEmpty()) { + if (sectionUnderTest.getRemediation().getPossibilities().isEmpty()) { String recipe = sectionUnderTest.getRemediation().getRecipe(); - if(recipe != null) { - String target = """ - - ++++ -
-
- ++++ - - """; + if (recipe != null) { + String target = "%n%s%n".formatted(SpringBootUpgradeReportSection.BUTTON_CODE); buttonCodes.add(target.replace("", recipe)); } } else { @@ -229,23 +221,16 @@ private String replaceRecipeButtonCodeFromExpectedOutput(SpringBootUpgradeReport .getRemediation() .getPossibilities() .stream() - .filter(p -> p.getRecipe() != null) .map(RemediationPossibility::getRecipe) + .filter(Objects::nonNull) .map(recipe -> { - String target = """ - - ++++ -
-
- ++++ - - """; + String target = "%n%s%n".formatted(SpringBootUpgradeReportSection.BUTTON_CODE); return target.replace("", recipe); }) .collect(Collectors.toList()); } - for(String buttonCode : buttonCodes) { + for (String buttonCode : buttonCodes) { renderedSection = renderedSection.replace(buttonCode, ""); } return renderedSection; @@ -263,9 +248,8 @@ private void withRecipes(Consumer recipesConsumer) { } private String replacePlaceHolders(String expectedOutput, Map templateVariables) { - StringBuffer sb = new StringBuffer(); // hacked, there's most probably a better way but ST couldn't digest html code - for(Map.Entry kv : templateVariables.entrySet()) { + for (Map.Entry kv : templateVariables.entrySet()) { String key = "<" + kv.getKey() + ">"; String replacement = kv.getValue(); expectedOutput = expectedOutput.replace(key, replacement); @@ -276,13 +260,13 @@ private String replacePlaceHolders(String expectedOutput, Map te @Getter @Setter - private static class BuilderData { + public static class BuilderData { private ProjectContext context; private String title; } - private static class SectionBuilderData extends BuilderData { + public static class SectionBuilderData extends BuilderData { } - private static class ReportBuilderData extends BuilderData { + public static class ReportBuilderData extends BuilderData { } } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ActuatorEndpointsSanitizationReportSectionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ActuatorEndpointsSanitizationReportSectionTest.java index 53055a508..f971f1af0 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ActuatorEndpointsSanitizationReportSectionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ActuatorEndpointsSanitizationReportSectionTest.java @@ -15,6 +15,7 @@ */ package org.springframework.sbm.boot.upgrade_27_30.report.helper; +import org.intellij.lang.annotations.Language; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.sbm.boot.upgrade_27_30.report.SpringBootUpgradeReportTestSupport; @@ -22,6 +23,8 @@ import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; +import java.nio.file.Path; + /** * @author Fabian Krüger */ @@ -30,18 +33,22 @@ public class ActuatorEndpointsSanitizationReportSectionTest { @Test @DisplayName("Actuator Endpoints SanitizationReport should render") void shouldRender() { + @Language("xml") String parentPom = PomBuilder .buildParentPom("org.springframework.boot:spring-boot-starter-parent:3.0.0", "com.example:parent:1.0") .withModules("moduleA", "moduleB", "moduleC") .build(); + @Language("xml") String moduleA = PomBuilder .buildPom("com.example:parent:1.0", "moduleA") .compileScopeDependencies("com.example:moduleC:1.0") .build(); + @Language("xml") String moduleB = PomBuilder .buildPom("com.example:parent:1.0", "moduleB") .compileScopeDependencies("com.example:moduleC:1.0") .build(); + @Language("xml") String moduleC = PomBuilder .buildPom("com.example:parent:1.0", "moduleC") .compileScopeDependencies("org.springframework.boot:spring-boot-starter-actuator") @@ -55,6 +62,11 @@ void shouldRender() { .withMavenBuildFileSource("moduleC", moduleC) .build(); + Path projectRoot = context.getProjectRootDirectory(); + Path moduleAPath = Path.of("moduleA", "pom.xml"); + Path moduleBPath = Path.of("moduleB", "pom.xml"); + Path moduleCPath = Path.of("moduleC", "pom.xml"); + SpringBootUpgradeReportTestSupport.generatedSection("Actuator Endpoints Sanitization") .fromProjectContext(context) .shouldRenderAs(""" @@ -66,7 +78,7 @@ void shouldRender() { Instead, this release opts for a more secure default. The keys-based approach has been removed in favor of a role based approach, similar to the health endpoint details. - Whether unsanitized values are shown or not can be configured using a property which can have the following values: + Whether non-sanitized values are shown or not can be configured using a property which can have the following values: - `NEVER` - All values are sanitized. - `ALWAYS` - All values are present in the output (sanitizing functions will apply). @@ -79,9 +91,9 @@ void shouldRender() { ==== Why is the application affected The scan found a dependency to actuator on the classpath. - * file:///moduleA/pom.xml[`moduleA/pom.xml`] - * file:///moduleB/pom.xml[`moduleB/pom.xml`] - * file:///moduleC/pom.xml[`moduleC/pom.xml`] + * %s[`%s`] + * %s[`%s`] + * %s[`%s`] ==== Remediation @@ -95,7 +107,15 @@ void shouldRender() { * https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/html/howto.html#howto.actuator.sanitize-sensitive-values.customizing-sanitization[Customizing Sanitization^, role="ext-link"] - """); + """.formatted( + projectRoot.resolve(moduleAPath).toUri(), + moduleAPath, + projectRoot.resolve(moduleBPath).toUri(), + moduleBPath, + projectRoot.resolve(moduleCPath).toUri(), + moduleCPath + ) + ); } } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/BannerSupportReportSectionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/BannerSupportReportSectionTest.java index cacc7cd03..63a439e3c 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/BannerSupportReportSectionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/BannerSupportReportSectionTest.java @@ -20,6 +20,8 @@ import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; +import java.nio.file.Path; + public class BannerSupportReportSectionTest { @@ -46,8 +48,8 @@ public void rendersBannerSupportInformation() { ==== Why is the application affected The scan found banner image files here: - * `/src/main/resources/banner.gif` - * `/src/main/resources/banner.jpg` + * `%1$s` + * `%2$s` ==== Remediation @@ -55,8 +57,8 @@ public void rendersBannerSupportInformation() { ===== Remove image banner Remove these image banners\s - * `/src/main/resources/banner.gif` - * `/src/main/resources/banner.jpg` + * `%1$s` + * `%2$s` @@ -67,12 +69,16 @@ public void rendersBannerSupportInformation() { ===== Replace image banner Replace these banners\s - * `/src/main/resources/banner.gif` - * `/src/main/resources/banner.jpg` + * `%1$s` + * `%2$s` with `banner.txt` - """); + """.formatted( + context.getProjectRootDirectory().resolve(Path.of("src/main/resources/banner.gif")), + context.getProjectRootDirectory().resolve(Path.of("src/main/resources/banner.jpg")) + ) + ); } } 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..4d8c12661 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 @@ -24,6 +24,8 @@ import org.springframework.sbm.openrewrite.RewriteExecutionContext; import org.springframework.sbm.project.resource.TestProjectContext; +import java.nio.file.Path; + /** * @author Fabian Krüger @@ -40,6 +42,10 @@ void changesToDataPropertiesSection_renders() { .withProjectResource("src/main/resources/application-another.properties", "spring.data.here=there") .build(); + Path projectRoot = context.getProjectRootDirectory(); + Path props1 = Path.of("src", "main", "resources", "application.properties"); + Path props2 = Path.of("src", "main", "resources", "application-another.properties"); + SpringBootUpgradeReportTestSupport.generatedSection("Changes to Data Properties") .fromProjectContext(context) .shouldRenderAs( @@ -53,16 +59,23 @@ void changesToDataPropertiesSection_renders() { ==== Why is the application affected The scan found properties with `spring.data` prefix but no dependency matching `org.springframework.data:.*`. - * file:///src/main/resources/application.properties[`src/main/resources/application.properties`] + * %s[`%s`] ** `spring.data.foo` - * file:///src/main/resources/application-another.properties[`src/main/resources/application-another.properties`] + * %s[`%s`] ** `spring.data.here` ==== Remediation Either add `spring-data` dependency, rename the property or remove it in case it's not required anymore. - """); + """.formatted( + projectRoot.resolve(props1).toUri(), + props1, + projectRoot.resolve(props2).toUri(), + props2 + + ) + ); } @Test diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ConstructorBindingReportSectionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ConstructorBindingReportSectionTest.java index e37838624..c1f0fa32b 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ConstructorBindingReportSectionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/ConstructorBindingReportSectionTest.java @@ -21,6 +21,8 @@ import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; +import java.nio.file.Path; + public class ConstructorBindingReportSectionTest { @Test @@ -86,16 +88,16 @@ is no longer required if the class has a single parameterized constructor. ==== Why is the application affected We found usage of `@ConstructorBinding` in following files: - * /src/main/java/com/example/ConfigProperties.java + * %s ==== Remediation Remove `@ConstructorBinding` if it matches the criteria, please refer issue: https://github.com/spring-projects-experimental/spring-boot-migrator/issues/166[#166] for more information - * https://github.com/spring-projects-experimental/spring-boot-migrator/issues/166[Issue 166] + * https://github.com/spring-projects-experimental/spring-boot-migrator/issues/166[Issue 166] - """ + """.formatted(context.getProjectRootDirectory().resolve(Path.of("src/main/java/com/example/ConfigProperties.java"))) ); } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/PagingAndSortingHelperTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/PagingAndSortingHelperTest.java index f0e44814f..2dce65a87 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/PagingAndSortingHelperTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/PagingAndSortingHelperTest.java @@ -28,21 +28,20 @@ public void reportMigrationGuidanceWhenPagingAndSortingRepositoryIsFound() { String javaClassWithPagingAndSortingRepository = """ package example; - import org.springframework.data.repository.PagingAndSortingRepository; + import org.springframework.data.repository.PagingAndSortingRepository; - import java.util.List; + import java.util.List; - public interface SongStatRepository extends PagingAndSortingRepository { - List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); - } + public interface SongStatRepository extends PagingAndSortingRepository { + List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); + } """; @Language("java") String javaClassWithoutPagingAndSortingRepo = """ - - package example; - public class A {} - """; + package example; + public class A {} + """; ProjectContext context = TestProjectContext.buildProjectContext() .withSpringBootParentOf("2.7.1") @@ -70,14 +69,14 @@ public class A {} ==== Why is the application affected We found classes which uses `PagingAndSortingRepository` in following files: - * `/src/main/java/example/SongStatRepository.java` + * `%s` ==== Remediation If one requires the old behavior one must extend not only the sorting repository, but also the respective CRUD repository explicitly. This was done so the sorting support could easily be combined with the List repositories introduced above. - """ + """.formatted(context.getProjectRootDirectory().resolve("src/main/java/example/SongStatRepository.java")) ); } @@ -87,21 +86,20 @@ public void reportMigrationGuidanceWhenReactiveSortingRepositoryIsFound() { String javaClassWithReactiveSortingRepo = """ package example; - import org.springframework.data.repository.reactive.ReactiveSortingRepository; + import org.springframework.data.repository.reactive.ReactiveSortingRepository; - import java.util.List; + import java.util.List; - public interface SongStatRepository extends ReactiveSortingRepository { - List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); - } + public interface SongStatRepository extends ReactiveSortingRepository { + List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); + } """; @Language("java") String javaClassWithoutReactiveSortingRepo = """ - - package example; - public class A {} - """; + package example; + public class A {} + """; ProjectContext context = TestProjectContext.buildProjectContext() .withSpringBootParentOf("2.7.1") @@ -130,14 +128,14 @@ public class A {} ==== Why is the application affected We found classes which uses `ReactiveSortingRepository` in following files: - * `/src/main/java/example/SongStatRepository.java` + * `%s` ==== Remediation If one requires the old behavior one must extend not only the sorting repository, but also the respective CRUD repository explicitly. This was done so the sorting support could easily be combined with the List repositories introduced above. - """ + """.formatted(context.getProjectRootDirectory().resolve("src/main/java/example/SongStatRepository.java")) ); } @@ -147,21 +145,20 @@ public void reportMigrationGuidanceWhenRxJavaSortingRepositoryIsFound() { String javaClassWithReactiveSortingRepo = """ package example; - import org.springframework.data.repository.reactive.RxJava3SortingRepository; + import org.springframework.data.repository.reactive.RxJava3SortingRepository; - import java.util.List; + import java.util.List; - public interface SongStatRepository extends RxJava3SortingRepository { - List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); - } + public interface SongStatRepository extends RxJava3SortingRepository { + List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); + } """; @Language("java") String javaClassWithoutReactiveSortingRepo = """ - - package example; - public class A {} - """; + package example; + public class A {} + """; ProjectContext context = TestProjectContext.buildProjectContext() .withSpringBootParentOf("2.7.1") @@ -174,8 +171,7 @@ public class A {} SpringBootUpgradeReportTestSupport .generatedSection("Paging and sorting repository") .fromProjectContext(context) - .shouldRenderAs( - """ + .shouldRenderAs(""" === Paging and sorting repository ==== What Changed @@ -190,14 +186,14 @@ public class A {} ==== Why is the application affected We found classes which uses `RxJavaSortingRepository` in following files: - * `/src/main/java/example/SongStatRepository.java` + * `%s` ==== Remediation If one requires the old behavior one must extend not only the sorting repository, but also the respective CRUD repository explicitly. This was done so the sorting support could easily be combined with the List repositories introduced above. - """ + """.formatted(context.getProjectRootDirectory().resolve("src/main/java/example/SongStatRepository.java")) ); } @@ -219,33 +215,32 @@ public interface SongStatRepositoryPagingAndSorting extends PagingAndSortingRepo String javaClassWithReactiveSortingRepo = """ package example; - import org.springframework.data.repository.reactive.ReactiveSortingRepository; + import org.springframework.data.repository.reactive.ReactiveSortingRepository; - import java.util.List; + import java.util.List; - public interface SongStatRepositoryReactive extends ReactiveSortingRepository { - List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); - } + public interface SongStatRepositoryReactive extends ReactiveSortingRepository { + List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); + } """; @Language("java") String javaClassWithRXReactiveSortingRepo = """ package example; - import org.springframework.data.repository.reactive.RxJava3SortingRepository; + import org.springframework.data.repository.reactive.RxJava3SortingRepository; - import java.util.List; + import java.util.List; - public interface SongStatRepositoryReactiveRx extends RxJava3SortingRepository { - List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); - } + public interface SongStatRepositoryReactiveRx extends RxJava3SortingRepository { + List findTop10SongsByRegionOrderByTimesPlayedDesc(String region); + } """; @Language("java") String javaClassWithoutPagingAndSortingRepo = """ - - package example; - public class A {} - """; + package example; + public class A {} + """; ProjectContext context = TestProjectContext.buildProjectContext() .withSpringBootParentOf("2.7.1") @@ -277,22 +272,26 @@ public class A {} ==== Why is the application affected We found classes which uses `PagingAndSortingRepository` in following files: - * `/src/main/java/example/SongStatRepositoryPagingAndSorting.java` + * `%s` We found classes which uses `ReactiveSortingRepository` in following files: - * `/src/main/java/example/SongStatRepositoryReactive.java` + * `%s` We found classes which uses `RxJavaSortingRepository` in following files: - * `/src/main/java/example/SongStatRepositoryReactiveRx.java` + * `%s` ==== Remediation If one requires the old behavior one must extend not only the sorting repository, but also the respective CRUD repository explicitly. This was done so the sorting support could easily be combined with the List repositories introduced above. - - """ + + """.formatted( + context.getProjectRootDirectory().resolve("src/main/java/example/SongStatRepositoryPagingAndSorting.java"), + context.getProjectRootDirectory().resolve("src/main/java/example/SongStatRepositoryReactive.java"), + context.getProjectRootDirectory().resolve("src/main/java/example/SongStatRepositoryReactiveRx.java") + ) ); } @@ -301,10 +300,9 @@ public void doNotReportWhenNoMatchesAreFound() { @Language("java") String javaClassWithoutPagingAndSortingRepo = """ - - package example; - public class A {} - """; + package example; + public class A {} + """; ProjectContext context = TestProjectContext.buildProjectContext() .withSpringBootParentOf("2.7.1") diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringFactoriesHelperTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringFactoriesHelperTest.java index 71c2791ff..ab37a92a5 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringFactoriesHelperTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringFactoriesHelperTest.java @@ -19,6 +19,8 @@ import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; +import java.nio.file.Path; + import static org.assertj.core.api.Assertions.assertThat; class SpringFactoriesHelperTest { @@ -43,6 +45,9 @@ public void detectsFileWithSpringFactories() { assertThat(sut.getData()).isNotNull(); assertThat(sut.getData().get("files")).hasSize(1); - assertThat(sut.getData().get("files").get(0)).contains("src/main/resources/META-INF/spring.factories"); + + Path actual = context.getProjectRootDirectory().resolve(Path.of("src/main/resources/META-INF/spring.factories")); + Path expected = Path.of(sut.getData().get("files").get(0)); + assertThat(expected).isEqualTo(actual); } } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesHelperTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesHelperTest.java index a38720cce..4a29a9e9e 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesHelperTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesHelperTest.java @@ -15,6 +15,7 @@ */ package org.springframework.sbm.boot.upgrade_27_30.report.helper; +import org.intellij.lang.annotations.Language; import org.junit.jupiter.api.Test; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.java.api.JavaSource; @@ -30,6 +31,7 @@ class SpringMVCAndWebFluxUrlMatchingChangesHelperTest { @Test void findsMatches() { + @Language("java") String restController1 = """ package b.example; @@ -40,6 +42,7 @@ public class RestController1 { } """; + @Language("java") String restController2 = """ package a.example; @@ -50,6 +53,7 @@ public class RestController2 { } """; + @Language("java") String anotherClass = """ package com.example; @@ -80,6 +84,7 @@ public class AnotherClass {}; @Test void findNoMatches() { + @Language("java") String anotherClass = """ package com.example; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesReportSectionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesReportSectionTest.java index 4df6e9437..8e1e6ed22 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesReportSectionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesReportSectionTest.java @@ -21,15 +21,19 @@ import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; +import java.nio.file.Path; + /** * @author Fabian Krüger */ public class SpringMVCAndWebFluxUrlMatchingChangesReportSectionTest { @Test void shouldRenderSection() { + @Language("java") String restController1 = """ package b.example; + import org.springframework.web.bind.annotation.RestController; @RestController @@ -37,9 +41,11 @@ public class RestController1 { } """; + @Language("java") String restController2 = """ package a.example; + import org.springframework.web.bind.annotation.RestController; @RestController @@ -47,10 +53,13 @@ public class RestController2 { } """; + @Language("java") String anotherClass = """ package com.example; - public class AnotherClass {}; + + public class AnotherClass { + } """; ProjectContext context = TestProjectContext @@ -62,6 +71,11 @@ public class AnotherClass {}; .withJavaSource("src/main/java", anotherClass) .build(); + Path projectRoot = context.getProjectRootDirectory(); + Path restController1Path = Path.of("src", "main", "java", "b", "example", "RestController1.java"); + Path restController2Path = Path.of("src", "main", "java", "a", "example", "RestController2.java"); + + @Language("adoc") String expectedOutput = """ @@ -76,11 +90,10 @@ public class AnotherClass {}; @RestController public class MyController { - @GetMapping("/some/greeting") - public String greeting { - return "Hello"; - } - + @GetMapping("/some/greeting") + public String greeting { + return "Hello"; + } } ---- @@ -97,23 +110,22 @@ public class WebConfiguration implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { - configurer.setUseTrailingSlashMatch(true); + configurer.setUseTrailingSlashMatch(true); } - } ---- ==== Why is the application affected The scan found classes annotated with `@RestController` which could be affected by this change. - * file:///src/main/java/a/example/RestController2.java[`src/main/java/a/example/RestController2.java`] - * file:///src/main/java/b/example/RestController1.java[`src/main/java/b/example/RestController1.java`] + * %s[`%s`] + * %s[`%s`] ==== Remediation You have different choices to remediate this change. ===== Do Nothing If no clients expect a response for requests with a trailing `/` nothing needs to done. - + ===== Configure explicit redirects/rewrites Configure explicit redirects/rewrites through a proxy, a Servlet/web filter. @@ -144,16 +156,21 @@ public void configurePathMatch(PathMatchConfigurer configurer) { @Configuration public class WebConfiguration implements WebMvcConfigurer { - @Override - public void configurePathMatch(PathMatchConfigurer configurer) { - configurer.setUseTrailingSlashMatch(true); - } - + @Override + public void configurePathMatch(PathMatchConfigurer configurer) { + configurer.setUseTrailingSlashMatch(true); + } } ---- - """; + """.formatted( + // Note the controller order here, sorted by package / absolute path + projectRoot.resolve(restController2Path).toUri(), + restController2Path, + projectRoot.resolve(restController1Path).toUri(), + restController1Path + ); SpringBootUpgradeReportTestSupport.generatedSection("Spring MVC and WebFlux URL matching changes") .fromProjectContext(context) diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jms/AddJmsConfigTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jms/AddJmsConfigTest.java index c1191c4a3..f6cc07e44 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jms/AddJmsConfigTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jms/AddJmsConfigTest.java @@ -15,6 +15,7 @@ */ package org.springframework.sbm.jee.jms; +import org.intellij.lang.annotations.Language; import org.springframework.sbm.jee.jms.actions.AddJmsConfigAction; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; @@ -34,12 +35,11 @@ public class AddJmsConfigTest { private final AddJmsConfigAction sut = new AddJmsConfigAction(); - private Configuration configuration; @BeforeEach void setUp() throws IOException { Version version = new Version("2.3.0"); - configuration = new Configuration(version); + Configuration configuration = new Configuration(version); configuration.setTemplateLoader(new FileTemplateLoader(new File("./src/main/resources/templates"))); sut.setConfiguration(configuration); } @@ -47,67 +47,70 @@ void setUp() throws IOException { @Test void testAddJmsConfig() { - String javaSource = - "package com.example.foo;\n" + - "import javax.ejb.MessageDriven;\n" - + "import javax.jms.Message;\n" - + "import javax.annotation.Resource;\n" - + "import javax.jms.Queue;\n" - + "\n" - + "@MessageDriven\n" - + "public class CargoHandled {\n" - + "\n" - + " @Resource(name = \"ChatBean\")\n" - + " private Queue questionQueue;\n" - + "\n" - + " @Resource(name = \"AnswerQueue\")\n" - + " private Queue answerQueue;\n" - + "}\n" - + ""; - - String expected = - "package com.example.foo;\n" - + "\n" - + "import javax.jms.ConnectionFactory;\n" - + "\n" - + "import javax.jms.Queue;\n" - + "import org.apache.activemq.command.ActiveMQQueue;\n" - + "import javax.jms.JMSException;\n" - + "\n" - + "import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;\n" - + "import org.springframework.context.annotation.Bean;\n" - + "import org.springframework.context.annotation.Configuration;\n" - + "import org.springframework.jms.annotation.EnableJms;\n" - + "import org.springframework.jms.config.DefaultJmsListenerContainerFactory;\n" - + "import org.springframework.jms.config.JmsListenerContainerFactory;\n" - + "\n" - + "@Configuration\n" - + "@EnableJms\n" - + "public class JmsConfig {\n" - + "\n" - + " @Bean\n" - + " public JmsListenerContainerFactory jmsListenerContainerFactory(\n" - + " ConnectionFactory connectionFactory,\n" - + " DefaultJmsListenerContainerFactoryConfigurer configurer) {\n" - + " DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();\n" - + " configurer.configure(factory, connectionFactory);\n" - + " return factory;\n" - + " }\n" - + "\n" - + " @Bean\n" - + " Queue answerQueue(ConnectionFactory connectionFactory) throws JMSException {\n" - + " ActiveMQQueue activeMQQueue = new ActiveMQQueue(\"AnswerQueue\");\n" - + " return activeMQQueue;\n" - + " }\n" - + "\n" - + " @Bean\n" - + " Queue questionQueue(ConnectionFactory connectionFactory) throws JMSException {\n" - + " ActiveMQQueue activeMQQueue = new ActiveMQQueue(\"ChatBean\");\n" - + " return activeMQQueue;\n" - + " }\n" - + "\n" - + "}\n" - + ""; + @Language("java") + String javaSource = """ + package com.example.foo; + + import javax.ejb.MessageDriven; + import javax.jms.Message; + import javax.annotation.Resource; + import javax.jms.Queue; + + @MessageDriven + public class CargoHandled { + + @Resource(name = "ChatBean") + private Queue questionQueue; + + @Resource(name = "AnswerQueue") + private Queue answerQueue; + } + """; + + @Language("java") + String expected = """ + package com.example.foo; + + import javax.jms.ConnectionFactory; + + import javax.jms.Queue; + import org.apache.activemq.command.ActiveMQQueue; + import javax.jms.JMSException; + + import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; + import org.springframework.jms.annotation.EnableJms; + import org.springframework.jms.config.DefaultJmsListenerContainerFactory; + import org.springframework.jms.config.JmsListenerContainerFactory; + + @Configuration + @EnableJms + public class JmsConfig { + + @Bean + public JmsListenerContainerFactory jmsListenerContainerFactory( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); + configurer.configure(factory, connectionFactory); + return factory; + } + + @Bean + Queue answerQueue(ConnectionFactory connectionFactory) throws JMSException { + ActiveMQQueue activeMQQueue = new ActiveMQQueue("AnswerQueue"); + return activeMQQueue; + } + + @Bean + Queue questionQueue(ConnectionFactory connectionFactory) throws JMSException { + ActiveMQQueue activeMQQueue = new ActiveMQQueue("ChatBean"); + return activeMQQueue; + } + + } + """; ProjectContext projectContext = TestProjectContext.buildProjectContext() .withBuildFileHavingDependencies("javax:javaee-api:7.0") @@ -119,57 +122,60 @@ void testAddJmsConfig() { String actual = projectContext.getProjectJavaSources().list().get(1).getResource().print(); assertThat(actual) .as(TestDiff.of(actual, expected)) - .isEqualTo(expected); + .isEqualToNormalizingNewlines(expected); } @Test void testAddJmsConfigNoQueues() { - String javaSource = - "package the.pckg.name;\n" - + "\n" - + "import javax.ejb.MessageDriven;\n" - + "import javax.jms.Message;\n" - + "import javax.annotation.Resource;\n" - + "import javax.jms.Queue;\n" - + "\n" - + "@MessageDriven\n" - + "public class CargoHandled {\n" - + "\n" - + " private Queue questionQueue;\n" - + "\n" - + " @Resource(name = \"AnswerQueue\")\n" - + " private String answerQueue;\n" - + "}\n" - + ""; - - String expected = - "package the.pckg.name;\n" - + "\n" - + "import javax.jms.ConnectionFactory;\n" - + "\n" - + "\n" - + "import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;\n" - + "import org.springframework.context.annotation.Bean;\n" - + "import org.springframework.context.annotation.Configuration;\n" - + "import org.springframework.jms.annotation.EnableJms;\n" - + "import org.springframework.jms.config.DefaultJmsListenerContainerFactory;\n" - + "import org.springframework.jms.config.JmsListenerContainerFactory;\n" - + "\n" - + "@Configuration\n" - + "@EnableJms\n" - + "public class JmsConfig {\n" - + "\n" - + " @Bean\n" - + " public JmsListenerContainerFactory jmsListenerContainerFactory(\n" - + " ConnectionFactory connectionFactory,\n" - + " DefaultJmsListenerContainerFactoryConfigurer configurer) {\n" - + " DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();\n" - + " configurer.configure(factory, connectionFactory);\n" - + " return factory;\n" - + " }\n" - + "\n" - + "}\n"; + @Language("java") + String javaSource = """ + package the.pckg.name; + + import javax.ejb.MessageDriven; + import javax.jms.Message; + import javax.annotation.Resource; + import javax.jms.Queue; + + @MessageDriven + public class CargoHandled { + + private Queue questionQueue; + + @Resource(name = "AnswerQueue") + private String answerQueue; + } + """; + + @Language("java") + String expected = """ + package the.pckg.name; + + import javax.jms.ConnectionFactory; + + + import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; + import org.springframework.jms.annotation.EnableJms; + import org.springframework.jms.config.DefaultJmsListenerContainerFactory; + import org.springframework.jms.config.JmsListenerContainerFactory; + + @Configuration + @EnableJms + public class JmsConfig { + + @Bean + public JmsListenerContainerFactory jmsListenerContainerFactory( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); + configurer.configure(factory, connectionFactory); + return factory; + } + + } + """; ProjectContext projectContext = TestProjectContext.buildProjectContext() .withBuildFileHavingDependencies("javax:javaee-api:7.0") @@ -181,7 +187,7 @@ void testAddJmsConfigNoQueues() { String actual = projectContext.getProjectJavaSources().list().get(1).getResource().print(); assertThat(actual) .as(TestDiff.of(actual, expected)) - .isEqualTo(expected); + .isEqualToNormalizingNewlines(expected); } diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jpa/actions/MigrateEclipseLinkToSpringBootTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jpa/actions/MigrateEclipseLinkToSpringBootTest.java index c1ef87d88..d3dd3b46a 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jpa/actions/MigrateEclipseLinkToSpringBootTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jpa/actions/MigrateEclipseLinkToSpringBootTest.java @@ -15,6 +15,7 @@ */ package org.springframework.sbm.jee.jpa.actions; +import org.intellij.lang.annotations.Language; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.java.util.BasePackageCalculator; import org.springframework.sbm.jee.jpa.resource.PersistenceXmlProjectResourceRegistrar; @@ -34,12 +35,11 @@ class MigrateEclipseLinkToSpringBootTest { private MigrateEclipseLinkToSpringBoot sut; - private Configuration configuration; @BeforeEach void setUp() throws IOException { Version version = new Version("2.3.0"); - configuration = new Configuration(version); + Configuration configuration = new Configuration(version); configuration.setTemplateLoader(new FileTemplateLoader(new File("./src/main/resources/templates"))); SbmApplicationProperties sbmApplicationProperties = new SbmApplicationProperties(); @@ -54,27 +54,28 @@ void setUp() throws IOException { @Test void shouldAddDependencyToSpringBootStarterDataJpaIfNoneExists() { - String pomXml = - "\n" + - "\n" + - " 4.0.0\n" + - " org.example\n" + - " sbm-testproject-jee-eclipselink\n" + - " 1.0-SNAPSHOT\n" + - " \n" + - " 11\n" + - " 11\n" + - " \n" + - " \n" + - " \n" + - " org.eclipse.persistence\n" + - " org.eclipse.persistence.jpa\n" + - " 2.7.10\n" + - " \n" + - " \n" + - ""; + @Language("xml") + String pomXml = """ + + + 4.0.0 + org.example + sbm-testproject-jee-eclipselink + 1.0-SNAPSHOT + + 11 + 11 + + + + org.eclipse.persistence + org.eclipse.persistence.jpa + 2.7.10 + + + """; ProjectContext projectContext = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) @@ -82,69 +83,72 @@ void shouldAddDependencyToSpringBootStarterDataJpaIfNoneExists() { sut.apply(projectContext); - assertThat(projectContext.getBuildFile().print()).isEqualTo( - "\n" + - "\n" + - " 4.0.0\n" + - " org.example\n" + - " sbm-testproject-jee-eclipselink\n" + - " 1.0-SNAPSHOT\n" + - " \n" + - " 11\n" + - " 11\n" + - " \n" + - " \n" + - " \n" + - " org.eclipse.persistence\n" + - " org.eclipse.persistence.jpa\n" + - " 2.7.10\n" + - " \n" + - " \n" + - " org.springframework.boot\n" + - " spring-boot-starter-data-jpa\n" + - " 2.5.9\n" + - " \n" + - " \n" + - " org.hibernate\n" + - " hibernate-core\n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" - ); + @Language("xml") + String expected = """ + + + 4.0.0 + org.example + sbm-testproject-jee-eclipselink + 1.0-SNAPSHOT + + 11 + 11 + + + + org.eclipse.persistence + org.eclipse.persistence.jpa + 2.7.10 + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.5.9 + + + org.hibernate + hibernate-core + + + + + """; + + assertThat(projectContext.getBuildFile().print()).isEqualToNormalizingNewlines(expected); } @Test void shouldAddExcludesToSpringBootStarterDataJpaIfExists() { - String pomXml = - "\n" + - "\n" + - " 4.0.0\n" + - " org.example\n" + - " sbm-testproject-jee-eclipselink\n" + - " 1.0-SNAPSHOT\n" + - " \n" + - " 11\n" + - " 11\n" + - " \n" + - " \n" + - " \n" + - " org.eclipse.persistence\n" + - " org.eclipse.persistence.jpa\n" + - " 2.7.10\n" + - " \n" + - " \n" + - " org.springframework.boot\n" + - " spring-boot-starter-data-jpa\n" + - " 2.5.9\n" + - " \n" + - " \n" + - ""; + @Language("xml") + String pomXml = """ + + + 4.0.0 + org.example + sbm-testproject-jee-eclipselink + 1.0-SNAPSHOT + + 11 + 11 + + + + org.eclipse.persistence + org.eclipse.persistence.jpa + 2.7.10 + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.5.9 + + + """; ProjectContext projectContext = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) @@ -152,188 +156,192 @@ void shouldAddExcludesToSpringBootStarterDataJpaIfExists() { sut.apply(projectContext); - assertThat(projectContext.getBuildFile().print()).isEqualTo( - "\n" + - "\n" + - " 4.0.0\n" + - " org.example\n" + - " sbm-testproject-jee-eclipselink\n" + - " 1.0-SNAPSHOT\n" + - " \n" + - " 11\n" + - " 11\n" + - " \n" + - " \n" + - " \n" + - " org.eclipse.persistence\n" + - " org.eclipse.persistence.jpa\n" + - " 2.7.10\n" + - " \n" + - " \n" + - " org.springframework.boot\n" + - " spring-boot-starter-data-jpa\n" + - " 2.5.9\n" + - " \n" + - " \n" + - " org.hibernate\n" + - " hibernate-core\n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" - ); + @Language("xml") + String expected = """ + + + 4.0.0 + org.example + sbm-testproject-jee-eclipselink + 1.0-SNAPSHOT + + 11 + 11 + + + + org.eclipse.persistence + org.eclipse.persistence.jpa + 2.7.10 + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.5.9 + + + org.hibernate + hibernate-core + + + + + """; + + assertThat(projectContext.getBuildFile().print()).isEqualToNormalizingNewlines(expected); } @Test void shouldAddEclipseLinkConfigurationClass() { - String pomXml = - "\n" + - "\n" + - " 4.0.0\n" + - " org.example\n" + - " sbm-testproject-jee-eclipselink\n" + - " 1.0-SNAPSHOT\n" + - " \n" + - " 11\n" + - " 11\n" + - " \n" + - " \n" + - " \n" + - " org.eclipse.persistence\n" + - " org.eclipse.persistence.jpa\n" + - " 2.7.10\n" + - " \n" + - " \n" + - ""; - - String persistenceXml = - "\n" + - " \n" + - " org.eclipse.persistence.jpa.PersistenceProvider\n" + - " false\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + @Language("xml") + String pomXml = """ + + + 4.0.0 + org.example + sbm-testproject-jee-eclipselink + 1.0-SNAPSHOT + + 11 + 11 + + + + org.eclipse.persistence + org.eclipse.persistence.jpa + 2.7.10 + + + """; + + @Language("xml") + String persistenceXml = """ + + + org.eclipse.persistence.jpa.PersistenceProvider + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + """; ProjectContext projectContext = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(pomXml) @@ -343,165 +351,167 @@ void shouldAddEclipseLinkConfigurationClass() { sut.apply(projectContext); + @Language("java") + String expected = """ + package com.vmware.example; + + import org.eclipse.persistence.config.PersistenceUnitProperties; + import org.eclipse.persistence.logging.SessionLog; + import org.springframework.beans.factory.ObjectProvider; + import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration; + import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; + import org.springframework.context.annotation.EnableLoadTimeWeaving; + import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; + import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; + import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter; + import org.springframework.transaction.jta.JtaTransactionManager; + + import javax.sql.DataSource; + import java.util.HashMap; + import java.util.Map; + + @Configuration + @EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED) + public class EclipseLinkJpaConfiguration extends JpaBaseConfiguration { + + protected EclipseLinkJpaConfiguration(DataSource dataSource, JpaProperties properties, ObjectProvider jtaTransactionManager) { + super(dataSource, properties, jtaTransactionManager); + } + + @Override + protected AbstractJpaVendorAdapter createJpaVendorAdapter() { + return new EclipseLinkJpaVendorAdapter(); + } + + @Override + protected Map getVendorProperties() { + Map map = new HashMap<>(); + + map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE"); + map.put(PersistenceUnitProperties.VALIDATE_EXISTENCE, "PersistenceUnitProperties.VALIDATE_EXISTENCE"); + map.put(PersistenceUnitProperties.SESSION_NAME, "PersistenceUnitProperties.SESSION_NAME"); + map.put("eclipselink.concurrency.manager.waittime", "concurrency.manager.waittime"); + map.put(PersistenceUnitProperties.COORDINATION_JNDI_CONTEXT, "PersistenceUnitProperties.COORDINATION_JNDI_CONTEXT"); + map.put(PersistenceUnitProperties.COORDINATION_JNDI_PASSWORD, "PersistenceUnitProperties.COORDINATION_JNDI_PASSWORD"); + map.put(PersistenceUnitProperties.COORDINATION_JNDI_USER, "PersistenceUnitProperties.COORDINATION_JNDI_USER"); + map.put(PersistenceUnitProperties.WEAVING_LAZY, "PersistenceUnitProperties.WEAVING_LAZY"); + map.put(PersistenceUnitProperties.JPQL_PARSER, "PersistenceUnitProperties.JPQL_PARSER"); + map.put("eclipselink.persisencexml.default", "persisencexml.default"); + map.put(PersistenceUnitProperties.METADATA_SOURCE_RCM_COMMAND, "PersistenceUnitProperties.METADATA_SOURCE_RCM_COMMAND"); + map.put(PersistenceUnitProperties.BATCH_WRITING, "PersistenceUnitProperties.BATCH_WRITING"); + map.put(PersistenceUnitProperties.CACHE_STATEMENTS, "PersistenceUnitProperties.CACHE_STATEMENTS"); + map.put(PersistenceUnitProperties.COMPOSITE_UNIT, "PersistenceUnitProperties.COMPOSITE_UNIT"); + map.put(PersistenceUnitProperties.JPQL_VALIDATION, "PersistenceUnitProperties.JPQL_VALIDATION"); + map.put(PersistenceUnitProperties.TARGET_DATABASE, "PersistenceUnitProperties.TARGET_DATABASE"); + map.put(PersistenceUnitProperties.COMPOSITE_UNIT_MEMBER, "PersistenceUnitProperties.COMPOSITE_UNIT_MEMBER"); + map.put(PersistenceUnitProperties.THROW_EXCEPTIONS, "PersistenceUnitProperties.THROW_EXCEPTIONS"); + map.put(PersistenceUnitProperties.LOGGING_CONNECTION, "PersistenceUnitProperties.LOGGING_CONNECTION"); + map.put(PersistenceUnitProperties.COORDINATION_NAMING_SERVICE, "PersistenceUnitProperties.COORDINATION_NAMING_SERVICE"); + map.put(PersistenceUnitProperties.COORDINATION_THREAD_POOL_SIZE, "PersistenceUnitProperties.COORDINATION_THREAD_POOL_SIZE"); + map.put("eclipselink.concurrency.manager.allow.concurrencyexception", "concurrency.manager.allow.concurrencyexception"); + map.put(PersistenceUnitProperties.LOGGING_EXCEPTIONS, "PersistenceUnitProperties.LOGGING_EXCEPTIONS"); + map.put(PersistenceUnitProperties.DATABASE_EVENT_LISTENER, "PersistenceUnitProperties.DATABASE_EVENT_LISTENER"); + map.put(PersistenceUnitProperties.WEAVING_EAGER, "PersistenceUnitProperties.WEAVING_EAGER"); + map.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, "PersistenceUnitProperties.CREATE_JDBC_DDL_FILE"); + map.put(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML"); + map.put(PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT, "PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT"); + map.put(PersistenceUnitProperties.LOGGING_FILE, "PersistenceUnitProperties.LOGGING_FILE"); + map.put(PersistenceUnitProperties.LOGGING_TIMESTAMP, "PersistenceUnitProperties.LOGGING_TIMESTAMP"); + map.put(PersistenceUnitProperties.COORDINATION_PROTOCOL, "PersistenceUnitProperties.COORDINATION_PROTOCOL"); + map.put(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, "PersistenceUnitProperties.WEAVING_CHANGE_TRACKING"); + map.put(PersistenceUnitProperties.SQL_CAST, "PersistenceUnitProperties.SQL_CAST"); + map.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, "PersistenceUnitProperties.SESSION_CUSTOMIZER"); + map.put(PersistenceUnitProperties.INCLUDE_DESCRIPTOR_QUERIES, "PersistenceUnitProperties.INCLUDE_DESCRIPTOR_QUERIES"); + map.put("eclipselink.concurrency.manager.maxfrequencytodumptinymessage", "concurrency.manager.maxfrequencytodumptinymessage"); + map.put(PersistenceUnitProperties.WEAVING_FETCHGROUPS, "PersistenceUnitProperties.WEAVING_FETCHGROUPS"); + map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT"); + map.put(PersistenceUnitProperties.COORDINATION_RMI_MULTICAST_GROUP, "PersistenceUnitProperties.COORDINATION_RMI_MULTICAST_GROUP"); + map.put("eclipselink.concurrency.manager.maxsleeptime", "concurrency.manager.maxsleeptime"); + map.put(PersistenceUnitProperties.DDL_GENERATION_MODE, "PersistenceUnitProperties.DDL_GENERATION_MODE"); + map.put("eclipselink.nosql.property", "nosql.property"); + map.put("eclipselink.concurrency.manager.allow.interruptedexception", "concurrency.manager.allow.interruptedexception"); + map.put("eclipselink.connection-pool.read", "connection-pool.read"); + map.put(PersistenceUnitProperties.METADATA_SOURCE, "PersistenceUnitProperties.METADATA_SOURCE"); + map.put(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_IS_LAZY, "PersistenceUnitProperties.EXCLUSIVE_CONNECTION_IS_LAZY"); + map.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, "PersistenceUnitProperties.DROP_JDBC_DDL_FILE"); + map.put(PersistenceUnitProperties.CACHE_SHARED_DEFAULT, "PersistenceUnitProperties.CACHE_SHARED_DEFAULT"); + map.put(PersistenceUnitProperties.ID_VALIDATION, "PersistenceUnitProperties.ID_VALIDATION"); + map.put(PersistenceUnitProperties.COORDINATION_RMI_PACKET_TIME_TO_LIVE, "PersistenceUnitProperties.COORDINATION_RMI_PACKET_TIME_TO_LIVE"); + map.put(PersistenceUnitProperties.WEAVING, "PersistenceUnitProperties.WEAVING"); + map.put(PersistenceUnitProperties.COORDINATION_ASYNCH, "PersistenceUnitProperties.COORDINATION_ASYNCH"); + map.put(PersistenceUnitProperties.ORM_SCHEMA_VALIDATION, "PersistenceUnitProperties.ORM_SCHEMA_VALIDATION"); + map.put(PersistenceUnitProperties.TARGET_SERVER, "PersistenceUnitProperties.TARGET_SERVER"); + map.put(PersistenceUnitProperties.COORDINATION_RMI_URL, "PersistenceUnitProperties.COORDINATION_RMI_URL"); + map.put(PersistenceUnitProperties.COORDINATION_JMS_REUSE_PUBLISHER, "PersistenceUnitProperties.COORDINATION_JMS_REUSE_PUBLISHER"); + map.put(PersistenceUnitProperties.PROFILER, "PersistenceUnitProperties.PROFILER"); + map.put("eclipselink.concurrency.manager.maxfrequencytodumpmassivemessage", "concurrency.manager.maxfrequencytodumpmassivemessage"); + map.put(PersistenceUnitProperties.DDL_GENERATION, "PersistenceUnitProperties.DDL_GENERATION"); + map.put(PersistenceUnitProperties.UPPERCASE_COLUMN_NAMES, "PersistenceUnitProperties.UPPERCASE_COLUMN_NAMES"); + map.put("eclipselink.concurrency.manager.allow.readlockstacktrace", "concurrency.manager.allow.readlockstacktrace"); + map.put("eclipselink.cache.type", "cache.type"); + map.put(PersistenceUnitProperties.PARTITIONING_CALLBACK, "PersistenceUnitProperties.PARTITIONING_CALLBACK"); + map.put("eclipselink.connection-pool", "connection-pool"); + map.put(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_MODE, "PersistenceUnitProperties.EXCLUSIVE_CONNECTION_MODE"); + map.put(PersistenceUnitProperties.NATIVE_QUERY_UPPERCASE_COLUMNS, "PersistenceUnitProperties.NATIVE_QUERY_UPPERCASE_COLUMNS"); + map.put(PersistenceUnitProperties.CLASSLOADER, "PersistenceUnitProperties.CLASSLOADER"); + map.put(PersistenceUnitProperties.TEMPORAL_MUTABLE, "PersistenceUnitProperties.TEMPORAL_MUTABLE"); + map.put(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_UNITS, "PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_UNITS"); + map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_COMMIT_WITHOUT_PERSIST_RULES, "PersistenceUnitProperties.PERSISTENCE_CONTEXT_COMMIT_WITHOUT_PERSIST_RULES"); + map.put(PersistenceUnitProperties.LOGGING_SESSION, "PersistenceUnitProperties.LOGGING_SESSION"); + map.put(PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS, "PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS"); + map.put("eclipselink.connection-pool.sequence", "connection-pool.sequence"); + map.put(PersistenceUnitProperties.ALLOW_NATIVE_SQL_QUERIES, "PersistenceUnitProperties.ALLOW_NATIVE_SQL_QUERIES"); + map.put(PersistenceUnitProperties.PARTITIONING, "PersistenceUnitProperties.PARTITIONING"); + map.put(PersistenceUnitProperties.TUNING, "PersistenceUnitProperties.TUNING"); + map.put(PersistenceUnitProperties.EXCLUDE_ECLIPSELINK_ORM_FILE, "PersistenceUnitProperties.EXCLUDE_ECLIPSELINK_ORM_FILE"); + map.put(PersistenceUnitProperties.APP_LOCATION, "PersistenceUnitProperties.APP_LOCATION"); + map.put(PersistenceUnitProperties.COORDINATION_JMS_TOPIC, "PersistenceUnitProperties.COORDINATION_JMS_TOPIC"); + map.put(PersistenceUnitProperties.NATIVE_SQL, "PersistenceUnitProperties.NATIVE_SQL"); + map.put(PersistenceUnitProperties.COORDINATION_RMI_MULTICAST_GROUP_PORT, "PersistenceUnitProperties.COORDINATION_RMI_MULTICAST_GROUP_PORT"); + map.put(PersistenceUnitProperties.DEPLOY_ON_STARTUP, "PersistenceUnitProperties.DEPLOY_ON_STARTUP"); + map.put(PersistenceUnitProperties.LOGGING_LEVEL, "PersistenceUnitProperties.LOGGING_LEVEL"); + map.put(PersistenceUnitProperties.NOSQL_CONNECTION_FACTORY, "PersistenceUnitProperties.NOSQL_CONNECTION_FACTORY"); + map.put(PersistenceUnitProperties.BATCH_WRITING_SIZE, "PersistenceUnitProperties.BATCH_WRITING_SIZE"); + map.put(PersistenceUnitProperties.LOGGING_THREAD, "PersistenceUnitProperties.LOGGING_THREAD"); + map.put(PersistenceUnitProperties.SESSIONS_XML, "PersistenceUnitProperties.SESSIONS_XML"); + map.put(PersistenceUnitProperties.COMPOSITE_UNIT_PROPERTIES, "PersistenceUnitProperties.COMPOSITE_UNIT_PROPERTIES"); + map.put(PersistenceUnitProperties.METADATA_SOURCE_PROPERTIES_FILE, "PersistenceUnitProperties.METADATA_SOURCE_PROPERTIES_FILE"); + map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_PERSIST_ON_COMMIT, "PersistenceUnitProperties.PERSISTENCE_CONTEXT_PERSIST_ON_COMMIT"); + map.put(PersistenceUnitProperties.COORDINATION_RMI_ANNOUNCEMENT_DELAY, "PersistenceUnitProperties.COORDINATION_RMI_ANNOUNCEMENT_DELAY"); + map.put(PersistenceUnitProperties.ORACLE_PROXY_TYPE, "PersistenceUnitProperties.ORACLE_PROXY_TYPE"); + map.put(PersistenceUnitProperties.COORDINATION_JMS_FACTORY, "PersistenceUnitProperties.COORDINATION_JMS_FACTORY"); + map.put(PersistenceUnitProperties.NOSQL_CONNECTION_SPEC, "PersistenceUnitProperties.NOSQL_CONNECTION_SPEC"); + map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_FLUSH_MODE, "PersistenceUnitProperties.PERSISTENCE_CONTEXT_FLUSH_MODE"); + map.put("eclipselink.cache.size", "cache.size"); + map.put(PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS, "PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS"); + map.put("eclipselink.descriptor.customizer", "descriptor.customizer"); + map.put(PersistenceUnitProperties.FLUSH_CLEAR_CACHE, "PersistenceUnitProperties.FLUSH_CLEAR_CACHE"); + map.put("eclipselink.jdbc.property", "jdbc.property"); + map.put(PersistenceUnitProperties.JOIN_EXISTING_TRANSACTION, "PersistenceUnitProperties.JOIN_EXISTING_TRANSACTION"); + map.put(PersistenceUnitProperties.COORDINATION_JMS_HOST, "PersistenceUnitProperties.COORDINATION_JMS_HOST"); + map.put(PersistenceUnitProperties.WEAVING_INTERNAL, "PersistenceUnitProperties.WEAVING_INTERNAL"); + map.put(PersistenceUnitProperties.VALIDATION_ONLY_PROPERTY, "PersistenceUnitProperties.VALIDATION_ONLY_PROPERTY"); + map.put("eclipselink.ddl.table-creation-suffix", "ddl.table-creation-suffix"); + map.put(PersistenceUnitProperties.COORDINATION_REMOVE_CONNECTION, "PersistenceUnitProperties.COORDINATION_REMOVE_CONNECTION"); + map.put(PersistenceUnitProperties.JDBC_CONNECTOR, "PersistenceUnitProperties.JDBC_CONNECTOR"); + map.put(PersistenceUnitProperties.METADATA_SOURCE_XML_URL, "PersistenceUnitProperties.METADATA_SOURCE_XML_URL"); + map.put(PersistenceUnitProperties.COORDINATION_CHANNEL, "PersistenceUnitProperties.COORDINATION_CHANNEL"); + map.put(PersistenceUnitProperties.CACHE_STATEMENTS_SIZE, "PersistenceUnitProperties.CACHE_STATEMENTS_SIZE"); + + return map; + } + + @Bean + public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable { + InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver(); + return loadTimeWeaver; + } + }"""; + assertThat(projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.vmware.example.EclipseLinkJpaConfiguration")).isNotEmpty(); - assertThat(projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.vmware.example.EclipseLinkJpaConfiguration").get().print()).isEqualTo( - "package com.vmware.example;\n" + - "\n" + - "import org.eclipse.persistence.config.PersistenceUnitProperties;\n" + - "import org.eclipse.persistence.logging.SessionLog;\n" + - "import org.springframework.beans.factory.ObjectProvider;\n" + - "import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;\n" + - "import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;\n" + - "import org.springframework.context.annotation.Bean;\n" + - "import org.springframework.context.annotation.Configuration;\n" + - "import org.springframework.context.annotation.EnableLoadTimeWeaving;\n" + - "import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;\n" + - "import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;\n" + - "import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;\n" + - "import org.springframework.transaction.jta.JtaTransactionManager;\n" + - "\n" + - "import javax.sql.DataSource;\n" + - "import java.util.HashMap;\n" + - "import java.util.Map;\n" + - "\n" + - "@Configuration\n" + - "@EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED)\n" + - "public class EclipseLinkJpaConfiguration extends JpaBaseConfiguration {\n" + - "\n" + - " protected EclipseLinkJpaConfiguration(DataSource dataSource, JpaProperties properties, ObjectProvider jtaTransactionManager) {\n" + - " super(dataSource, properties, jtaTransactionManager);\n" + - " }\n" + - "\n" + - " @Override\n" + - " protected AbstractJpaVendorAdapter createJpaVendorAdapter() {\n" + - " return new EclipseLinkJpaVendorAdapter();\n" + - " }\n" + - "\n" + - " @Override\n" + - " protected Map getVendorProperties() {\n" + - " Map map = new HashMap<>();\n" + - "\n" + - " map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, \"PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE\");\n" + - " map.put(PersistenceUnitProperties.VALIDATE_EXISTENCE, \"PersistenceUnitProperties.VALIDATE_EXISTENCE\");\n" + - " map.put(PersistenceUnitProperties.SESSION_NAME, \"PersistenceUnitProperties.SESSION_NAME\");\n" + - " map.put(\"eclipselink.concurrency.manager.waittime\", \"concurrency.manager.waittime\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_JNDI_CONTEXT, \"PersistenceUnitProperties.COORDINATION_JNDI_CONTEXT\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_JNDI_PASSWORD, \"PersistenceUnitProperties.COORDINATION_JNDI_PASSWORD\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_JNDI_USER, \"PersistenceUnitProperties.COORDINATION_JNDI_USER\");\n" + - " map.put(PersistenceUnitProperties.WEAVING_LAZY, \"PersistenceUnitProperties.WEAVING_LAZY\");\n" + - " map.put(PersistenceUnitProperties.JPQL_PARSER, \"PersistenceUnitProperties.JPQL_PARSER\");\n" + - " map.put(\"eclipselink.persisencexml.default\", \"persisencexml.default\");\n" + - " map.put(PersistenceUnitProperties.METADATA_SOURCE_RCM_COMMAND, \"PersistenceUnitProperties.METADATA_SOURCE_RCM_COMMAND\");\n" + - " map.put(PersistenceUnitProperties.BATCH_WRITING, \"PersistenceUnitProperties.BATCH_WRITING\");\n" + - " map.put(PersistenceUnitProperties.CACHE_STATEMENTS, \"PersistenceUnitProperties.CACHE_STATEMENTS\");\n" + - " map.put(PersistenceUnitProperties.COMPOSITE_UNIT, \"PersistenceUnitProperties.COMPOSITE_UNIT\");\n" + - " map.put(PersistenceUnitProperties.JPQL_VALIDATION, \"PersistenceUnitProperties.JPQL_VALIDATION\");\n" + - " map.put(PersistenceUnitProperties.TARGET_DATABASE, \"PersistenceUnitProperties.TARGET_DATABASE\");\n" + - " map.put(PersistenceUnitProperties.COMPOSITE_UNIT_MEMBER, \"PersistenceUnitProperties.COMPOSITE_UNIT_MEMBER\");\n" + - " map.put(PersistenceUnitProperties.THROW_EXCEPTIONS, \"PersistenceUnitProperties.THROW_EXCEPTIONS\");\n" + - " map.put(PersistenceUnitProperties.LOGGING_CONNECTION, \"PersistenceUnitProperties.LOGGING_CONNECTION\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_NAMING_SERVICE, \"PersistenceUnitProperties.COORDINATION_NAMING_SERVICE\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_THREAD_POOL_SIZE, \"PersistenceUnitProperties.COORDINATION_THREAD_POOL_SIZE\");\n" + - " map.put(\"eclipselink.concurrency.manager.allow.concurrencyexception\", \"concurrency.manager.allow.concurrencyexception\");\n" + - " map.put(PersistenceUnitProperties.LOGGING_EXCEPTIONS, \"PersistenceUnitProperties.LOGGING_EXCEPTIONS\");\n" + - " map.put(PersistenceUnitProperties.DATABASE_EVENT_LISTENER, \"PersistenceUnitProperties.DATABASE_EVENT_LISTENER\");\n" + - " map.put(PersistenceUnitProperties.WEAVING_EAGER, \"PersistenceUnitProperties.WEAVING_EAGER\");\n" + - " map.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, \"PersistenceUnitProperties.CREATE_JDBC_DDL_FILE\");\n" + - " map.put(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, \"PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML\");\n" + - " map.put(PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT, \"PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT\");\n" + - " map.put(PersistenceUnitProperties.LOGGING_FILE, \"PersistenceUnitProperties.LOGGING_FILE\");\n" + - " map.put(PersistenceUnitProperties.LOGGING_TIMESTAMP, \"PersistenceUnitProperties.LOGGING_TIMESTAMP\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_PROTOCOL, \"PersistenceUnitProperties.COORDINATION_PROTOCOL\");\n" + - " map.put(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, \"PersistenceUnitProperties.WEAVING_CHANGE_TRACKING\");\n" + - " map.put(PersistenceUnitProperties.SQL_CAST, \"PersistenceUnitProperties.SQL_CAST\");\n" + - " map.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, \"PersistenceUnitProperties.SESSION_CUSTOMIZER\");\n" + - " map.put(PersistenceUnitProperties.INCLUDE_DESCRIPTOR_QUERIES, \"PersistenceUnitProperties.INCLUDE_DESCRIPTOR_QUERIES\");\n" + - " map.put(\"eclipselink.concurrency.manager.maxfrequencytodumptinymessage\", \"concurrency.manager.maxfrequencytodumptinymessage\");\n" + - " map.put(PersistenceUnitProperties.WEAVING_FETCHGROUPS, \"PersistenceUnitProperties.WEAVING_FETCHGROUPS\");\n" + - " map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, \"PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_RMI_MULTICAST_GROUP, \"PersistenceUnitProperties.COORDINATION_RMI_MULTICAST_GROUP\");\n" + - " map.put(\"eclipselink.concurrency.manager.maxsleeptime\", \"concurrency.manager.maxsleeptime\");\n" + - " map.put(PersistenceUnitProperties.DDL_GENERATION_MODE, \"PersistenceUnitProperties.DDL_GENERATION_MODE\");\n" + - " map.put(\"eclipselink.nosql.property\", \"nosql.property\");\n" + - " map.put(\"eclipselink.concurrency.manager.allow.interruptedexception\", \"concurrency.manager.allow.interruptedexception\");\n" + - " map.put(\"eclipselink.connection-pool.read\", \"connection-pool.read\");\n" + - " map.put(PersistenceUnitProperties.METADATA_SOURCE, \"PersistenceUnitProperties.METADATA_SOURCE\");\n" + - " map.put(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_IS_LAZY, \"PersistenceUnitProperties.EXCLUSIVE_CONNECTION_IS_LAZY\");\n" + - " map.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, \"PersistenceUnitProperties.DROP_JDBC_DDL_FILE\");\n" + - " map.put(PersistenceUnitProperties.CACHE_SHARED_DEFAULT, \"PersistenceUnitProperties.CACHE_SHARED_DEFAULT\");\n" + - " map.put(PersistenceUnitProperties.ID_VALIDATION, \"PersistenceUnitProperties.ID_VALIDATION\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_RMI_PACKET_TIME_TO_LIVE, \"PersistenceUnitProperties.COORDINATION_RMI_PACKET_TIME_TO_LIVE\");\n" + - " map.put(PersistenceUnitProperties.WEAVING, \"PersistenceUnitProperties.WEAVING\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_ASYNCH, \"PersistenceUnitProperties.COORDINATION_ASYNCH\");\n" + - " map.put(PersistenceUnitProperties.ORM_SCHEMA_VALIDATION, \"PersistenceUnitProperties.ORM_SCHEMA_VALIDATION\");\n" + - " map.put(PersistenceUnitProperties.TARGET_SERVER, \"PersistenceUnitProperties.TARGET_SERVER\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_RMI_URL, \"PersistenceUnitProperties.COORDINATION_RMI_URL\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_JMS_REUSE_PUBLISHER, \"PersistenceUnitProperties.COORDINATION_JMS_REUSE_PUBLISHER\");\n" + - " map.put(PersistenceUnitProperties.PROFILER, \"PersistenceUnitProperties.PROFILER\");\n" + - " map.put(\"eclipselink.concurrency.manager.maxfrequencytodumpmassivemessage\", \"concurrency.manager.maxfrequencytodumpmassivemessage\");\n" + - " map.put(PersistenceUnitProperties.DDL_GENERATION, \"PersistenceUnitProperties.DDL_GENERATION\");\n" + - " map.put(PersistenceUnitProperties.UPPERCASE_COLUMN_NAMES, \"PersistenceUnitProperties.UPPERCASE_COLUMN_NAMES\");\n" + - " map.put(\"eclipselink.concurrency.manager.allow.readlockstacktrace\", \"concurrency.manager.allow.readlockstacktrace\");\n" + - " map.put(\"eclipselink.cache.type\", \"cache.type\");\n" + - " map.put(PersistenceUnitProperties.PARTITIONING_CALLBACK, \"PersistenceUnitProperties.PARTITIONING_CALLBACK\");\n" + - " map.put(\"eclipselink.connection-pool\", \"connection-pool\");\n" + - " map.put(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_MODE, \"PersistenceUnitProperties.EXCLUSIVE_CONNECTION_MODE\");\n" + - " map.put(PersistenceUnitProperties.NATIVE_QUERY_UPPERCASE_COLUMNS, \"PersistenceUnitProperties.NATIVE_QUERY_UPPERCASE_COLUMNS\");\n" + - " map.put(PersistenceUnitProperties.CLASSLOADER, \"PersistenceUnitProperties.CLASSLOADER\");\n" + - " map.put(PersistenceUnitProperties.TEMPORAL_MUTABLE, \"PersistenceUnitProperties.TEMPORAL_MUTABLE\");\n" + - " map.put(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_UNITS, \"PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_UNITS\");\n" + - " map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_COMMIT_WITHOUT_PERSIST_RULES, \"PersistenceUnitProperties.PERSISTENCE_CONTEXT_COMMIT_WITHOUT_PERSIST_RULES\");\n" + - " map.put(PersistenceUnitProperties.LOGGING_SESSION, \"PersistenceUnitProperties.LOGGING_SESSION\");\n" + - " map.put(PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS, \"PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS\");\n" + - " map.put(\"eclipselink.connection-pool.sequence\", \"connection-pool.sequence\");\n" + - " map.put(PersistenceUnitProperties.ALLOW_NATIVE_SQL_QUERIES, \"PersistenceUnitProperties.ALLOW_NATIVE_SQL_QUERIES\");\n" + - " map.put(PersistenceUnitProperties.PARTITIONING, \"PersistenceUnitProperties.PARTITIONING\");\n" + - " map.put(PersistenceUnitProperties.TUNING, \"PersistenceUnitProperties.TUNING\");\n" + - " map.put(PersistenceUnitProperties.EXCLUDE_ECLIPSELINK_ORM_FILE, \"PersistenceUnitProperties.EXCLUDE_ECLIPSELINK_ORM_FILE\");\n" + - " map.put(PersistenceUnitProperties.APP_LOCATION, \"PersistenceUnitProperties.APP_LOCATION\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_JMS_TOPIC, \"PersistenceUnitProperties.COORDINATION_JMS_TOPIC\");\n" + - " map.put(PersistenceUnitProperties.NATIVE_SQL, \"PersistenceUnitProperties.NATIVE_SQL\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_RMI_MULTICAST_GROUP_PORT, \"PersistenceUnitProperties.COORDINATION_RMI_MULTICAST_GROUP_PORT\");\n" + - " map.put(PersistenceUnitProperties.DEPLOY_ON_STARTUP, \"PersistenceUnitProperties.DEPLOY_ON_STARTUP\");\n" + - " map.put(PersistenceUnitProperties.LOGGING_LEVEL, \"PersistenceUnitProperties.LOGGING_LEVEL\");\n" + - " map.put(PersistenceUnitProperties.NOSQL_CONNECTION_FACTORY, \"PersistenceUnitProperties.NOSQL_CONNECTION_FACTORY\");\n" + - " map.put(PersistenceUnitProperties.BATCH_WRITING_SIZE, \"PersistenceUnitProperties.BATCH_WRITING_SIZE\");\n" + - " map.put(PersistenceUnitProperties.LOGGING_THREAD, \"PersistenceUnitProperties.LOGGING_THREAD\");\n" + - " map.put(PersistenceUnitProperties.SESSIONS_XML, \"PersistenceUnitProperties.SESSIONS_XML\");\n" + - " map.put(PersistenceUnitProperties.COMPOSITE_UNIT_PROPERTIES, \"PersistenceUnitProperties.COMPOSITE_UNIT_PROPERTIES\");\n" + - " map.put(PersistenceUnitProperties.METADATA_SOURCE_PROPERTIES_FILE, \"PersistenceUnitProperties.METADATA_SOURCE_PROPERTIES_FILE\");\n" + - " map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_PERSIST_ON_COMMIT, \"PersistenceUnitProperties.PERSISTENCE_CONTEXT_PERSIST_ON_COMMIT\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_RMI_ANNOUNCEMENT_DELAY, \"PersistenceUnitProperties.COORDINATION_RMI_ANNOUNCEMENT_DELAY\");\n" + - " map.put(PersistenceUnitProperties.ORACLE_PROXY_TYPE, \"PersistenceUnitProperties.ORACLE_PROXY_TYPE\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_JMS_FACTORY, \"PersistenceUnitProperties.COORDINATION_JMS_FACTORY\");\n" + - " map.put(PersistenceUnitProperties.NOSQL_CONNECTION_SPEC, \"PersistenceUnitProperties.NOSQL_CONNECTION_SPEC\");\n" + - " map.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_FLUSH_MODE, \"PersistenceUnitProperties.PERSISTENCE_CONTEXT_FLUSH_MODE\");\n" + - " map.put(\"eclipselink.cache.size\", \"cache.size\");\n" + - " map.put(PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS, \"PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS\");\n" + - " map.put(\"eclipselink.descriptor.customizer\", \"descriptor.customizer\");\n" + - " map.put(PersistenceUnitProperties.FLUSH_CLEAR_CACHE, \"PersistenceUnitProperties.FLUSH_CLEAR_CACHE\");\n" + - " map.put(\"eclipselink.jdbc.property\", \"jdbc.property\");\n" + - " map.put(PersistenceUnitProperties.JOIN_EXISTING_TRANSACTION, \"PersistenceUnitProperties.JOIN_EXISTING_TRANSACTION\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_JMS_HOST, \"PersistenceUnitProperties.COORDINATION_JMS_HOST\");\n" + - " map.put(PersistenceUnitProperties.WEAVING_INTERNAL, \"PersistenceUnitProperties.WEAVING_INTERNAL\");\n" + - " map.put(PersistenceUnitProperties.VALIDATION_ONLY_PROPERTY, \"PersistenceUnitProperties.VALIDATION_ONLY_PROPERTY\");\n" + - " map.put(\"eclipselink.ddl.table-creation-suffix\", \"ddl.table-creation-suffix\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_REMOVE_CONNECTION, \"PersistenceUnitProperties.COORDINATION_REMOVE_CONNECTION\");\n" + - " map.put(PersistenceUnitProperties.JDBC_CONNECTOR, \"PersistenceUnitProperties.JDBC_CONNECTOR\");\n" + - " map.put(PersistenceUnitProperties.METADATA_SOURCE_XML_URL, \"PersistenceUnitProperties.METADATA_SOURCE_XML_URL\");\n" + - " map.put(PersistenceUnitProperties.COORDINATION_CHANNEL, \"PersistenceUnitProperties.COORDINATION_CHANNEL\");\n" + - " map.put(PersistenceUnitProperties.CACHE_STATEMENTS_SIZE, \"PersistenceUnitProperties.CACHE_STATEMENTS_SIZE\");\n" + - "\n" + - " return map;\n" + - " }\n" + - "\n" + - " @Bean\n" + - " public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable {\n" + - " InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();\n" + - " return loadTimeWeaver;\n" + - " }\n" + - "}" - ); + assertThat(projectContext.getProjectJavaSources().findJavaSourceDeclaringType("com.vmware.example.EclipseLinkJpaConfiguration").get().print()).isEqualToNormalizingNewlines(expected); } } \ No newline at end of file diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jpa/actions/PersistenceXmlToSpringBootApplicationPropertiesActionTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jpa/actions/PersistenceXmlToSpringBootApplicationPropertiesActionTest.java index e8015ef19..74ee8a61e 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jpa/actions/PersistenceXmlToSpringBootApplicationPropertiesActionTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jpa/actions/PersistenceXmlToSpringBootApplicationPropertiesActionTest.java @@ -183,8 +183,8 @@ void migrateJpaToSpringBoot() { .verify(context -> { List applicationProperties = context.search(new SpringBootApplicationPropertiesResourceListFilter()); SpringBootApplicationProperties springBootApplicationProperties = applicationProperties.get(0); - assertThat(springBootApplicationProperties.getProperty("spring.jpa.hibernate.ddl-auto").get()).isEqualTo("create-drop"); - assertThat(springBootApplicationProperties.getProperty("spring.jpa.database-platform").get()).isEqualTo("org.hibernate.dialect.HSQLDialect"); + assertThat(springBootApplicationProperties.getProperty("spring.jpa.hibernate.ddl-auto")).hasValue("create-drop"); + assertThat(springBootApplicationProperties.getProperty("spring.jpa.database-platform")).hasValue("org.hibernate.dialect.HSQLDialect"); assertThat(context.search(new PersistenceXmlResourceFilter("**/src/main/resources/**"))).isNotEmpty(); }); } @@ -249,8 +249,8 @@ void migrateJpaToSpringBootWithPersistenceXmlOnlyMatchesPersistenceXmlInMain() { .verify(projectContext -> { List applicationProperties = projectContext.search(new SpringBootApplicationPropertiesResourceListFilter()); SpringBootApplicationProperties springBootApplicationProperties = applicationProperties.get(0); - assertThat(springBootApplicationProperties.getProperty("spring.jpa.hibernate.ddl-auto").get()).isEqualTo("create-drop"); - assertThat(springBootApplicationProperties.getProperty("spring.jpa.database-platform").get()).isEqualTo("org.hibernate.dialect.HSQLDialect"); + assertThat(springBootApplicationProperties.getProperty("spring.jpa.hibernate.ddl-auto")).hasValue("create-drop"); + assertThat(springBootApplicationProperties.getProperty("spring.jpa.database-platform")).hasValue("org.hibernate.dialect.HSQLDialect"); assertThat(projectContext.search(new PersistenceXmlResourceFilter("**/src/main/resources/**"))).isNotEmpty(); }); } 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..464ae59ae 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 @@ -19,7 +19,6 @@ import org.springframework.sbm.mule.resource.MuleXmlProjectResourceRegistrar; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.openrewrite.RewriteExecutionContext; -import org.springframework.sbm.project.resource.ProjectResource; import org.springframework.sbm.project.resource.TestProjectContext; import freemarker.cache.FileTemplateLoader; import freemarker.template.Configuration; @@ -94,7 +93,10 @@ void test() { sut.apply(projectContext); Path path = TestProjectContext.getDefaultProjectRoot().resolve("src/main/resources/spring-integration-flow.xml"); - ProjectResource springIntegration = projectContext.search(new AbsolutePathResourceFinder(path)).get(); - assertThat(springIntegration.print()).isEqualTo(expected); + assertThat(projectContext.search(new AbsolutePathResourceFinder(path))) + .isNotEmpty() + .hasValueSatisfying(v -> { + assertThat(v.print()).isEqualToNormalizingNewlines(expected); + }); } } \ No newline at end of file diff --git a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/MuleToJavaDSLDwlTransformTest.java b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/MuleToJavaDSLDwlTransformTest.java index 5409a4c2f..cb46de2e6 100644 --- a/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/MuleToJavaDSLDwlTransformTest.java +++ b/components/sbm-recipes-mule-to-boot/src/test/java/org/springframework/sbm/mule/actions/MuleToJavaDSLDwlTransformTest.java @@ -77,7 +77,7 @@ public void shouldTranslateDwlTransformationWithSetPayload() { runAction(projectContext1 -> { assertThat(projectContext.getProjectJavaSources().list()).hasSize(2); assertThat(getGeneratedJavaFile()) - .isEqualTo( + .isEqualToNormalizingNewlines( """ package com.example.javadsl; import org.springframework.context.annotation.Bean; @@ -99,7 +99,7 @@ IntegrationFlow dwlFlow() { } }"""); assertThat(projectContext.getProjectJavaSources().list().get(1).print()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; public class DwlFlowTransform_2 { @@ -131,7 +131,7 @@ public void shouldTranslateDwlTransformationWithMuleTriggerMeshTransformAndSetPa assertThat(projectContext.getProjectJavaSources().list()).hasSize(3); assertThat(getGeneratedJavaFile()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -164,7 +164,7 @@ IntegrationFlow dwlFlow() { } }"""); assertThat(projectContext.getProjectJavaSources().list().get(1).print()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; import org.springframework.context.annotation.Configuration; @@ -182,7 +182,7 @@ public class TmDwPayload { """ ); assertThat(projectContext.getProjectJavaSources().list().get(2).print()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; import com.fasterxml.jackson.databind.ObjectMapper; @@ -285,7 +285,7 @@ public void shouldTransformDWLWithFileWithSetPayload() { runAction(projectContext -> { assertThat(projectContext.getProjectJavaSources().list()).hasSize(2); assertThat(getGeneratedJavaFile()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -306,7 +306,7 @@ IntegrationFlow dwlFlow() { } }"""); assertThat(projectContext.getProjectJavaSources().list().get(1).print()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; public class MapClientRiskRatingResponseTransform { @@ -358,7 +358,7 @@ public void shouldTranslateDWLTransformationWithOnlyOneSetVariable() { runAction(projectContext -> { assertThat(projectContext.getProjectJavaSources().list()).hasSize(1); assertThat(getGeneratedJavaFile()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -415,7 +415,7 @@ public void shouldNotErrorWhenDWLFileHasDash() { runAction(projectContext -> { assertThat(projectContext.getProjectJavaSources().list()).hasSize(2); assertThat(getGeneratedJavaFile()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -436,7 +436,7 @@ IntegrationFlow dwlFlow() { } }"""); assertThat(projectContext.getProjectJavaSources().list().get(1).print()) - .isEqualTo(""" + .isEqualToNormalizingNewlines(""" package com.example.javadsl; public class MapclientriskratingresponseTransform { @@ -560,11 +560,14 @@ public void multipleDWLTransformInSameFlowShouldProduceMultipleClassesWithTrigge addXMLFileToResource(xml); runAction(projectContext -> { - assertThat(projectContext.getProjectJavaSources().list()).hasSize(4); - assertThat(projectContext.getProjectJavaSources().list().get(0).getTypes().get(0).toString()).isEqualTo("com.example.javadsl.FlowConfigurations"); - assertThat(projectContext.getProjectJavaSources().list().get(1).getTypes().get(0).toString()).isEqualTo("com.example.javadsl.TmDwPayload"); - assertThat(projectContext.getProjectJavaSources().list().get(2).getTypes().get(0).toString()).isEqualTo("com.example.javadsl.MultipleTransformsTransformTM_3"); - assertThat(projectContext.getProjectJavaSources().list().get(3).getTypes().get(0).toString()).isEqualTo("com.example.javadsl.MultipleTransformsTransformTM_1"); + assertThat(projectContext.getProjectJavaSources().list()) + .hasSize(4) + .satisfiesExactlyInAnyOrder( + s -> assertThat(s.getTypes().get(0).toString()).isEqualTo("com.example.javadsl.FlowConfigurations"), + s -> assertThat(s.getTypes().get(0).toString()).isEqualTo("com.example.javadsl.TmDwPayload"), + s -> assertThat(s.getTypes().get(0).toString()).isEqualTo("com.example.javadsl.MultipleTransformsTransformTM_3"), + s -> assertThat(s.getTypes().get(0).toString()).isEqualTo("com.example.javadsl.MultipleTransformsTransformTM_1") + ); }); } } diff --git a/components/sbm-recipes-spring-framework/src/test/java/org/springframework/sbm/actions/spring/xml/include/ImportSpringXmlConfigXmlToJavaConfigurationActionTest.java b/components/sbm-recipes-spring-framework/src/test/java/org/springframework/sbm/actions/spring/xml/include/ImportSpringXmlConfigXmlToJavaConfigurationActionTest.java index 5f878f792..76782c3cc 100644 --- a/components/sbm-recipes-spring-framework/src/test/java/org/springframework/sbm/actions/spring/xml/include/ImportSpringXmlConfigXmlToJavaConfigurationActionTest.java +++ b/components/sbm-recipes-spring-framework/src/test/java/org/springframework/sbm/actions/spring/xml/include/ImportSpringXmlConfigXmlToJavaConfigurationActionTest.java @@ -16,6 +16,7 @@ package org.springframework.sbm.actions.spring.xml.include; import freemarker.template.Configuration; +import org.intellij.lang.annotations.Language; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -45,32 +46,37 @@ void oneXmlBeansFile() { String pkgName = TestProjectContext.getDefaultPackageName(); Path projectRootDirectory = Path.of("./fake/projects/something").toAbsolutePath().normalize(); - String xmlSample = - "\n" + - "\n" + - ""; - - String buildFileSource = "\n" + - "\n" + - " org.springframework.sbm\n" + - " something\n" + - " 0.6.1-SNAPSHOT\n" + - " \n" + - " 4.0.0\n" + - " \n" + - " \n" + - " org.springframework\n" + - " spring-context" + - " 5.3.16\n" + - " \n" + - " \n" + - ""; + @Language("xml") + String xmlSample = """ + + + + """; + + @Language("xml") + String buildFileSource = """ + + + org.springframework.sbm + something + 0.6.1-SNAPSHOT + + 4.0.0 + + + org.springframework + spring-context + 5.3.16 + + + + """; ProjectContext ctx = TestProjectContext.buildProjectContext() .withProjectRoot(projectRootDirectory) @@ -87,65 +93,74 @@ void oneXmlBeansFile() { JavaSource r = resources.get(0); Path absolutePathToConfig = projectRootDirectory.resolve("src/main/java/").resolve(pkgName.replace('.', '/')).resolve("SpringContextImportConfig.java"); assertThat(r.getResource().getAbsolutePath()).isEqualTo(absolutePathToConfig); - assertThat(r.getResource().print()) - .isEqualTo( - "package "+pkgName+";\n" + - "\n" + - "import org.springframework.context.annotation.Configuration;\n" + - "import org.springframework.context.annotation.ImportResource;\n" + - "\n" + - "@Configuration\n" + - "@ImportResource({\"classpath:my-xml/nicebeans.xml\"})\n" + - "public class SpringContextImportConfig {\n" + - "}\n" - ); + + @Language("java") + String expected = """ + package %s; + + import org.springframework.context.annotation.Configuration; + import org.springframework.context.annotation.ImportResource; + + @Configuration + @ImportResource({"classpath:my-xml/nicebeans.xml"}) + public class SpringContextImportConfig { + } + """.formatted(pkgName); + + assertThat(r.getResource().print()).isEqualToNormalizingNewlines(expected); } @Test void twoXmlBeansFiles() { String pkgName = TestProjectContext.getDefaultPackageName(); - String xmlSample = - "\n" + - "\n" + - ""; - - String xmlSample2 = - "\n" + - "\n" + - ""; + @Language("xml") + String xmlSample = """ + + + + """; + + @Language("xml") + String xmlSample2 = """ + + + + """; + + @Language("xml") + String mavenRootBuildFileSource = """ + + + org.springframework.sbm + 0.6.1-SNAPSHOT + 4.0.0 + + something + + + + org.springframework + spring-context + 5.3.16 + + + + """; ProjectContext ctx = TestProjectContext.buildProjectContext() .withProjectRoot(Path.of(".")) - .withMavenRootBuildFileSource( - "\n" + - "\n" + - " org.springframework.sbm\n" + - " 0.6.1-SNAPSHOT\n" + - " 4.0.0\n" + - "\n" + - " something\n" + - "\n" + - " \n" + - " \n" + - " org.springframework\n" + - " spring-context\n" + - " 5.3.16\n" + - " \n" + - " \n" + - "\n" + - "" - ) + .withMavenRootBuildFileSource(mavenRootBuildFileSource) .withProjectResource(Path.of("src/main/resources/my-xml/nicebeans.xml"), xmlSample) .withProjectResource(Path.of("src/main/resources/my-xml/favabeans.xml"), xmlSample2) .build(); @@ -158,18 +173,21 @@ void twoXmlBeansFiles() { assertThat(resources).hasSize(1); JavaSource r = resources.get(0); assertThat(r.getResource().getAbsolutePath()).isEqualTo(Path.of(".").toAbsolutePath().resolve("src/main/java/").resolve(pkgName.replace(".", "/")).resolve("SpringContextImportConfig.java").normalize()); - assertThat(r.getResource().print()) - .isEqualTo( - "package "+pkgName+";\n" + - "\n" + - "import org.springframework.context.annotation.Configuration;\n" + - "import org.springframework.context.annotation.ImportResource;\n" + - "\n" + - "@Configuration\n" + - "@ImportResource({\"classpath:my-xml/favabeans.xml\", \"classpath:my-xml/nicebeans.xml\"})\n" + - "public class SpringContextImportConfig {\n" + - "}\n" - ); + + @Language("java") + String expected = """ + package %s; + + import org.springframework.context.annotation.Configuration; + import org.springframework.context.annotation.ImportResource; + + @Configuration + @ImportResource({"classpath:my-xml/favabeans.xml", "classpath:my-xml/nicebeans.xml"}) + public class SpringContextImportConfig { + } + """.formatted(pkgName); + + assertThat(r.getResource().print()).isEqualToNormalizingNewlines(expected); } // TODO: more xml files than one diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/cleanup/actions/RemoveRedundantMavenCompilerPluginPropertiesTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/cleanup/actions/RemoveRedundantMavenCompilerPluginPropertiesTest.java index 4edb01820..09ef225cd 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/cleanup/actions/RemoveRedundantMavenCompilerPluginPropertiesTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/cleanup/actions/RemoveRedundantMavenCompilerPluginPropertiesTest.java @@ -513,8 +513,8 @@ void multiModuleWithPluginDefinedInParentModuleAndPropertiesInChildModule() { assertThat(rootModule.getProperty("maven.compiler.source")).isNull(); assertThat(rootModule.getProperty("maven.compiler.target")).isNull(); assertThat(rootModule.getProperty("java.version")).isEqualTo("17"); - assertThat(rootModule.getPlugins().get(0).getConfiguration().getDeclaredStringValue("target").get()).isEqualTo("${java.version}"); - assertThat(rootModule.getPlugins().get(0).getConfiguration().getDeclaredStringValue("source").get()).isEqualTo("${java.version}"); + assertThat(rootModule.getPlugins().get(0).getConfiguration().getDeclaredStringValue("target")).hasValue("${java.version}"); + assertThat(rootModule.getPlugins().get(0).getConfiguration().getDeclaredStringValue("source")).hasValue("${java.version}"); BuildFile childModule = projectContext.getApplicationModules().getModule("module1").getBuildFile(); diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/actions/AddSpringBootContextTestClassTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/actions/AddSpringBootContextTestClassTest.java index 3b2ce0a7a..a835d7bf1 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/actions/AddSpringBootContextTestClassTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/actions/AddSpringBootContextTestClassTest.java @@ -15,6 +15,7 @@ */ package org.springframework.sbm.boot.common.actions; +import org.intellij.lang.annotations.Language; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.SbmApplicationProperties; import org.springframework.sbm.project.resource.TestProjectContext; @@ -32,8 +33,6 @@ public class AddSpringBootContextTestClassTest { - private Configuration configuration; - private AddSpringBootContextTestClassAction sut; // TODO: add missing tests: test adding test with no classes in src/test/java but in src/main/java -> root package must be taken from src/main/java then @@ -42,7 +41,7 @@ public class AddSpringBootContextTestClassTest { @BeforeEach void setUp() throws IOException { Version version = new Version("2.3.0"); - configuration = new Configuration(version); + Configuration configuration = new Configuration(version); configuration.setTemplateLoader(new FileTemplateLoader(new File("./src/main/resources/templates"))); sut = new AddSpringBootContextTestClassAction(); sut.setConfiguration(configuration); @@ -53,20 +52,22 @@ public class GivenSingleModuleProject { @Test void testApplyShouldAddNewSource() { - String expectedTestClassSource = - "package org.springframework.sbm.root.test;\n" + - "\n" + - "import org.junit.jupiter.api.Test;\n" + - "import org.springframework.boot.test.context.SpringBootTest;\n" + - "\n" + - "@SpringBootTest\n" + - "class SpringBootAppTest {\n" + - "\n" + - " @Test\n" + - " void contextLoads() {\n" + - " }\n" + - "\n" + - "}\n"; + @Language("java") + String expectedTestClassSource = """ + package org.springframework.sbm.root.test; + + import org.junit.jupiter.api.Test; + import org.springframework.boot.test.context.SpringBootTest; + + @SpringBootTest + class SpringBootAppTest { + + @Test + void contextLoads() { + } + + } + """; SbmApplicationProperties sbmApplicationProperties = new SbmApplicationProperties(); sbmApplicationProperties.setDefaultBasePackage("foo.bar"); @@ -91,69 +92,76 @@ void testApplyShouldAddNewSource() { assertThat(context.getProjectJavaSources().list()).hasSize(3); assertThat(context.getProjectJavaSources().list().get(2).getPackageName()).isEqualTo("org.springframework.sbm.root.test"); - assertThat(context.getProjectJavaSources().list().get(2).print()).isEqualTo(expectedTestClassSource); + assertThat(context.getProjectJavaSources().list().get(2).print()).isEqualToNormalizingNewlines(expectedTestClassSource); } } @Nested public class GivenMultiModuleProject { - private static final String parentPom = - "\n" + - "\n" + - " com.example.sbm\n" + - " parent\n" + - " 0.1.0-SNAPSHOT\n" + - " 4.0.0\n" + - " pom\n" + - " \n" + - " module1\n" + - " module2\n" + - " " + - "\n"; - - private static final String childPom1 = - "\n" + - "\n" + - " \n" + - " com.example.sbm\n" + - " parent\n" + - " 0.1.0-SNAPSHOT\n" + - " ../pom.xml\n" + - " \n" + - " module1\n" + - " 4.0.0\n" + - " \n" + - " \n" + - " com.example.sbm\n" + - " module2\n" + - " 0.1.0-SNAPSHOT\n" + - " \n" + - " \n" + - "\n"; - - private static final String childPom2 = - "\n" + - "\n" + - " \n" + - " com.example.sbm\n" + - " parent\n" + - " 0.1.0-SNAPSHOT\n" + - " ../pom.xml\n" + - " \n" + - " module2\n" + - " 4.0.0\n" + - "\n"; - - - private static final String javaClass1 = - "package com.example.sbm;\n" + - "public class SomeClass {}"; + @Language("xml") + private static final String parentPom = """ + + + com.example.sbm + parent + 0.1.0-SNAPSHOT + 4.0.0 + pom + + module1 + module2 + + + """; + + @Language("xml") + private static final String childPom1 = """ + + + + com.example.sbm + parent + 0.1.0-SNAPSHOT + ../pom.xml + + module1 + 4.0.0 + + + com.example.sbm + module2 + 0.1.0-SNAPSHOT + + + + """; + + @Language("xml") + private static final String childPom2 = """ + + + + com.example.sbm + parent + 0.1.0-SNAPSHOT + ../pom.xml + + module2 + 4.0.0 + + """; + + @Language("java") + private static final String javaClass1 = """ + package com.example.sbm; + public class SomeClass {} + """; @Test void test() { @@ -178,6 +186,4 @@ void test() { assertThat(projectContext.getApplicationModules().findModule("com.example.sbm:module2:0.1.0-SNAPSHOT").get().getTestJavaSourceSet().list()).isEmpty(); } } - - } diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/actions/AddSpringBootMainClassActionTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/actions/AddSpringBootMainClassActionTest.java index b4980b5c3..80e6cd50a 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/actions/AddSpringBootMainClassActionTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/actions/AddSpringBootMainClassActionTest.java @@ -15,6 +15,7 @@ */ package org.springframework.sbm.boot.common.actions; +import org.intellij.lang.annotations.Language; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.TestProjectContext; import freemarker.template.Configuration; @@ -52,20 +53,24 @@ void testApplyShouldAddNewSource() { sut.apply(context); assertThat(context.getProjectJavaSources().list()).hasSize(2); + + @Language("java") + String expected = """ + package org.springframework.sbm.root; + + import org.springframework.boot.SpringApplication; + import org.springframework.boot.autoconfigure.SpringBootApplication; + + @SpringBootApplication + public class SpringBootApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootApp.class, args); + } + } + """; + assertThat(context.getProjectJavaSources().list().get(1).print()) - .isEqualTo( - "package org.springframework.sbm.root;\n" + - "\n" + - "import org.springframework.boot.SpringApplication;\n" + - "import org.springframework.boot.autoconfigure.SpringBootApplication;\n" + - "\n" + - "@SpringBootApplication\n" + - "public class SpringBootApp {\n" + - "\n" + - " public static void main(String[] args) {\n" + - " SpringApplication.run(SpringBootApp.class, args);\n" + - " }\n" + - "}\n" - ); + .isEqualToNormalizingNewlines(expected); } } diff --git a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/finder/SpringBeanMethodDeclarationFinderTest.java b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/finder/SpringBeanMethodDeclarationFinderTest.java index 05e4485a7..828ab6ed5 100644 --- a/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/finder/SpringBeanMethodDeclarationFinderTest.java +++ b/components/sbm-support-boot/src/test/java/org/springframework/sbm/boot/common/finder/SpringBeanMethodDeclarationFinderTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.sbm.project.resource.TestProjectContext; +import org.springframework.sbm.utils.LinuxWindowsPathUnifier; import java.util.List; @@ -78,9 +79,9 @@ public class SomeBean {} void shouldReturnTheMatchingBeanDeclaration() { List matches = builder.build().search(sut); assertThat(matches).hasSize(1); - assertThat(matches.get(0).getJavaSource().getSourcePath().toString()).isEqualTo("src/main/java/MyConfiguration.java"); + assertThat(LinuxWindowsPathUnifier.unifyPath(matches.get(0).getJavaSource().getSourcePath())).isEqualTo("src/main/java/MyConfiguration.java"); assertThat(matches.get(0).getType().getFullyQualifiedName()).isEqualTo("MyConfiguration"); - assertThat(matches.get(0).getMethod().getReturnValue().get()).isEqualTo("a.b.c.SomeBean"); + assertThat(matches.get(0).getMethod().getReturnValue()).hasValue("a.b.c.SomeBean"); assertThat(matches.get(0).getMethod().getName()).isEqualTo("someBean"); } } @@ -143,25 +144,21 @@ public class AnotherBean {} .withBuildFileHavingDependencies("org.springframework:spring-context:5.3.22"); } - @Test void shouldReturnTheMatchingBeanDeclarations() { List matches = builder.build().search(sut); assertThat(matches).hasSize(2); - assertThat(matches.get(0).getJavaSource().getSourcePath().toString()).isEqualTo("src/main/java/MyConfiguration.java"); + assertThat(LinuxWindowsPathUnifier.unifyPath(matches.get(0).getJavaSource().getSourcePath())).isEqualTo("src/main/java/MyConfiguration.java"); assertThat(matches.get(0).getType().getFullyQualifiedName()).isEqualTo("MyConfiguration"); - assertThat(matches.get(0).getMethod().getReturnValue()).isPresent(); - assertThat(matches.get(0).getMethod().getReturnValue().get()).isEqualTo("a.b.c.SomeBean"); + assertThat(matches.get(0).getMethod().getReturnValue()).hasValue("a.b.c.SomeBean"); assertThat(matches.get(0).getMethod().getName()).isEqualTo("someBean"); - assertThat(matches.get(1).getJavaSource().getSourcePath().toString()).isEqualTo("src/main/java/MyConfiguration2.java"); + assertThat(LinuxWindowsPathUnifier.unifyPath(matches.get(1).getJavaSource().getSourcePath())).isEqualTo("src/main/java/MyConfiguration2.java"); assertThat(matches.get(1).getType().getFullyQualifiedName()).isEqualTo("MyConfiguration2"); assertThat(matches.get(1).getMethod().getName()).isEqualTo("someBean2"); - assertThat(matches.get(1).getMethod().getReturnValue()).isPresent(); - assertThat(matches.get(1).getMethod().getReturnValue().get()).isEqualTo("a.b.c.SomeBean"); + assertThat(matches.get(1).getMethod().getReturnValue()).hasValue("a.b.c.SomeBean"); } } - @Nested class WithVoidBeans { 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..13aba8fe9 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 @@ -43,8 +43,8 @@ void parseExistingPropertiesTest() { "foo=bar\n" + "bob=bill"); SpringBootApplicationProperties sut = new SpringBootApplicationProperties(Path.of("./projectDir").toAbsolutePath(), parse.get(0), new RewriteExecutionContext()); - assertThat(sut.getProperty("foo").get()).isEqualTo("bar"); - assertThat(sut.getProperty("bob").get()).isEqualTo("bill"); + assertThat(sut.getProperty("foo")).hasValue("bar"); + assertThat(sut.getProperty("bob")).hasValue("bill"); assertThat(sut.getProperty("jane")).isEmpty(); } 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..4b30659a5 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 @@ -38,7 +38,7 @@ void test() { List properties = context.search(new SpringBootApplicationPropertiesResourceListFilter()); assertThat(properties).hasSize(1); - assertThat(properties.get(0).getProperty("foo").get()).isEqualTo("bar"); + assertThat(properties.get(0).getProperty("foo")).hasValue("bar"); } } diff --git a/docs/boot-3.0.0-M3-upgrade.adoc b/docs/boot-3.0.0-M3-upgrade.adoc index 500200e68..4d9adac11 100644 --- a/docs/boot-3.0.0-M3-upgrade.adoc +++ b/docs/boot-3.0.0-M3-upgrade.adoc @@ -61,7 +61,7 @@ All variables used in the template must be provided by `getData`. The scan found properties with `spring.data` prefix but no dependency matching `org.springframework.data:.*`. <#list matches as match> <2> - * file://${match.absolutePath}[`${match.relativePath}`] + * ${match.absolutePath.toUri()}[`${match.relativePath}`] <#list match.propertiesFound as property> ** `${property}` @@ -232,7 +232,7 @@ https://github.com/Buzzardo/spring-style-guide/blob/master/spring-style-guide.ad The scan found properties with `spring.data` prefix but no dependency matching `org.springframework.data:.*`. <#list matches as match> - * file://${match.absolutePath}[`${match.relativePath}`] + * ${match.absolutePath.toUri()}[`${match.relativePath}`] <#list match.propertiesFound as property> ** `${property}` diff --git a/pom.xml b/pom.xml index 77bc3c912..4a471bd18 100644 --- a/pom.xml +++ b/pom.xml @@ -192,6 +192,11 @@ rewrite-properties ${openrewrite.version} + + org.openrewrite + rewrite-test + ${openrewrite.version} + org.openrewrite.recipe rewrite-spring @@ -382,7 +387,7 @@ com.mycila license-maven-plugin - 4.1 + 4.3 validate @@ -426,6 +431,8 @@ limitations under the License. **/testcode/** **/test-code/** **/pom.xml + **/*.gradle.kts + **/*.gradle **/*.properties **/*.yaml **/*.yml diff --git a/sbm-support-rewrite/pom.xml b/sbm-support-rewrite/pom.xml index 3e67fad3e..4c953ae58 100644 --- a/sbm-support-rewrite/pom.xml +++ b/sbm-support-rewrite/pom.xml @@ -283,7 +283,7 @@ com.mycila license-maven-plugin - 4.1 + 4.3 validate @@ -327,6 +327,8 @@ limitations under the License. **/testcode/** **/test-code/** **/pom.xml + **/*.gradle.kts + **/*.gradle **/*.properties **/*.yaml **/*.yml