From 79ee7f387897ee78c911312a546de41d28fe2ecb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabian=20Kr=C3=BCger?= <56278322+fabapp2@users.noreply.github.com> Date: Mon, 25 Sep 2023 00:24:21 +0200 Subject: [PATCH] 858 incorporate new parser into core (#868) * Fix parsing duplicate pom files Added target to default ignorePatterns Refactor method names for test Fix dependency download Fix test by ignoring poms when parsing resources Add logging Replace List with Set to avoid duplicates * Refactoring * Add test proving duplicate parsing of resources * Fix path calculcation to other modules * Back to use shrinkwrap in tests * Replace single-line with multi-line String * Bumped maven-resolver.version * Fix test allow SbmCoreConfig construct ExecutionContext * GH Action * Assert correct classpath * Fix testdata * Cleanup * Disabled test that must be reactivated later * Move JavaSourceUtil to sbm-support-rewrite * Move OpenRewriteTestSupport to test-helper * Back to use shrinkwrap in tests * Add missing test projects * Back to use shrinkwrap in tests * Revamp/move open rewrite test support to test helper (#939) * Revamp/make other modules compile (#943) * Update license header * Add sbm-support-boot module * Add sbm-support-boot module * Module sbm-support-boot compiles * Module sbm-support-jee compiles * Module sbm-support-weblogic compiles * WIP sbm-recipes-jee-to-boot * Make SwapResponseWithResponseEntity compile * Make SwapCacheControl compile * Make SwapStatusForHttpStatus compile * Make fieldsMapping a member * Remove unused member * Make ReplaceMediaType compile Also removes unused member * Make ReplaceResponseEntityBuilder compile * Make sbm-recipes-jee-to-boot compile * Make sbm-recipes-spring-cloud compile * Delete unused classes * Delete unused classes * Make sbm-recipes-boot-upgrade compile * Using shrinkwrap depchain dependency * Replace single line with multi line string * Cleanup properties order --- .../sbm/java/api/JavaSource.java | 2 +- .../springframework/sbm/java/api/Type.java | 2 +- .../sbm/java/impl/CompiledType.java | 4 +- .../sbm/java/impl/OpenRewriteJavaSource.java | 3 +- .../sbm/java/impl/OpenRewriteType.java | 2 +- .../java/RetrieveAnnotationTypeTest.java | 9 +- .../openrewrite/api/GetImplementsTest.java | 43 +- components/sbm-recipes-boot-upgrade/pom.xml | 5 +- .../CassandraApplicationPropertiesMove.java | 2 +- .../CrudRepositoryExtension.java | 110 --- ...CrudRepositoryExtensionWithReferences.java | 201 ------ .../ImplementTypedInterface.java | 158 ----- .../DatabaseDriverGaeSectionBuilder.java | 2 +- .../checks/RedeclaredDependenciesBuilder.java | 2 +- .../SecurityManagerUsagesFinder.java | 7 +- .../SpringBootUpgradeReportDataProvider.java | 2 +- .../helper/ConstructorBindingHelper.java | 2 +- .../helper/JohnzonDependencyHelper.java | 8 +- ...MVCAndWebFluxUrlMatchingChangesHelper.java | 2 +- ...edInstantiationOfExecutionContextTest.java | 2 +- .../upgrade_27_30/ConfigRecipeTestHelper.java | 6 +- .../CrudRepositoryExtensionTest.java | 410 ----------- ...RepositoryExtensionWithReferencesTest.java | 587 ---------------- .../boot/upgrade_27_30/JavaTestHelper.java | 71 -- .../upgrade_27_30/UpgradeBomTo30Test.java | 19 +- .../JerseyTemporarilyRemovedFinderTest.java | 4 +- .../RedeclaredDependenciesFinderTest.java | 12 +- .../config/ConfigRecipeTestHelper.java | 10 +- .../SpringBootUpgradeReportActionTest.java | 2 +- .../UpgradeDepenenciesMigrationTest.java | 5 +- components/sbm-recipes-jee-to-boot/pom.xml | 21 +- .../jee/ejb/actions/MigrateJndiLookup.java | 21 +- .../sbm/jee/jaxrs/MigrateJaxRsRecipe.java | 4 +- .../recipes/CopyAnnotationAttribute.java | 9 +- .../RemoveAnnotationIfAccompanied.java | 5 +- .../jee/jaxrs/recipes/ReplaceMediaType.java | 179 ++--- .../ReplaceRequestParameterProperties.java | 19 +- .../recipes/ReplaceResponseEntityBuilder.java | 77 +- .../jee/jaxrs/recipes/SwapCacheControl.java | 94 +-- .../jaxrs/recipes/SwapFamilyForSeries.java | 13 +- .../sbm/jee/jaxrs/recipes/SwapHttHeaders.java | 25 +- .../SwapResponseWithResponseEntity.java | 665 +++++++++--------- .../recipes/SwapStatusForHttpStatus.java | 65 +- .../CopyAnnotationAttributeVisitor.java | 3 +- .../sbm/jee/jaxws/GenerateWebServices.java | 5 +- .../sbm/jee/jaxws/WebServiceDescriptor.java | 20 +- ...edInstantiationOfExecutionContextTest.java | 2 +- .../jaxrs/recipes/ReplaceMediaTypeTest.java | 9 +- .../jaxrs/recipes/ResponseBuilderTest.java | 4 +- .../ResponseEntityReplacementTest.java | 6 +- .../jee/jaxrs/recipes/ResponseStatusTest.java | 3 +- .../MigrateEclipseLinkToSpringBootTest.java | 5 +- ...ngBootApplicationPropertiesActionTest.java | 4 +- components/sbm-recipes-spring-cloud/pom.xml | 1 + ...edInstantiationOfExecutionContextTest.java | 2 +- components/sbm-support-boot/pom.xml | 5 +- .../spring/SpringBeanDeclarationFinder.java | 7 +- .../HasSpringBootDependencyImport.java | 2 +- ...asSpringBootDependencyManuallyManaged.java | 2 +- .../SpringBootApplicationPropertiesTest.java | 16 +- components/sbm-support-jee/pom.xml | 4 +- ...ersistenceXmlProjectResourceRegistrar.java | 5 +- .../JeeWebXmlProjectResourceRegistrar.java | 18 +- ...edInstantiationOfExecutionContextTest.java | 2 +- .../sbm/jee/ejb/api/EjbJarXmlTest.java | 2 +- .../sbm/jee/web/api/WebXmlTest.java | 4 +- ...edInstantiationOfExecutionContextTest.java | 2 +- components/test-helper/pom.xml | 45 +- pom.xml | 20 +- .../sbm/parsers/JavaParserBuilder.java | 3 - 70 files changed, 832 insertions(+), 2260 deletions(-) delete mode 100644 components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtension.java delete mode 100644 components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionWithReferences.java delete mode 100644 components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/ImplementTypedInterface.java delete mode 100644 components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionTest.java delete mode 100644 components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionWithReferencesTest.java delete mode 100644 components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/JavaTestHelper.java diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/java/api/JavaSource.java b/components/sbm-core/src/main/java/org/springframework/sbm/java/api/JavaSource.java index 43c7f0194..3b0313755 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/java/api/JavaSource.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/java/api/JavaSource.java @@ -59,7 +59,7 @@ public interface JavaSource extends ProjectResource { *

* Be careful if the given {@code Recipe} affects more than the wrapped compilation unit YOU MUST CALL {@link JavaSourceSet.apply(..)} */ - void apply(Recipe recipe); + void apply(Recipe... recipe); /** * Retrieve the {@code Type} declared in this {@code JavaSource}. diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/java/api/Type.java b/components/sbm-core/src/main/java/org/springframework/sbm/java/api/Type.java index f4cf48307..6c9e4101a 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/java/api/Type.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/java/api/Type.java @@ -59,7 +59,7 @@ public interface Type { Annotation getAnnotation(String fqName); - void apply(Recipe r); + void apply(Recipe... r); boolean hasMethod(String methodPattern); diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/CompiledType.java b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/CompiledType.java index 6c35817a5..461143446 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/CompiledType.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/CompiledType.java @@ -123,8 +123,8 @@ public Annotation getAnnotation(String fqName) { } @Override - public void apply(Recipe r) { - + public void apply(Recipe... r) { + throw new UnsupportedOperationException(); } @Override diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteJavaSource.java b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteJavaSource.java index a93a5c2ef..07443da61 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteJavaSource.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteJavaSource.java @@ -171,7 +171,6 @@ public void replaceLiteral(Class klass, LiteralTransformer t) { refactoring.refactor(getResource(), new ReplaceLiteralVisitor<>(klass, t)); } - @Override public String toString() { return "OpenRewriteJavaSource(" + getAbsolutePath() + ")"; @@ -181,7 +180,7 @@ public String toString() { * {@inheritDoc} */ @Override - public void apply(Recipe recipe) { + public void apply(Recipe... recipe) { refactoring.refactor(getResource(), recipe); } diff --git a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteType.java b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteType.java index 82d2729df..6ef4c00b4 100644 --- a/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteType.java +++ b/components/sbm-core/src/main/java/org/springframework/sbm/java/impl/OpenRewriteType.java @@ -295,7 +295,7 @@ public String toString() { } @Override - public void apply(Recipe r) { + public void apply(Recipe... r) { refactoring.refactor(rewriteSourceFileHolder, r); } diff --git a/components/sbm-openrewrite/src/test/java/org/springframework/sbm/openrewrite/java/RetrieveAnnotationTypeTest.java b/components/sbm-openrewrite/src/test/java/org/springframework/sbm/openrewrite/java/RetrieveAnnotationTypeTest.java index 85eaee32d..0ed8c46b8 100644 --- a/components/sbm-openrewrite/src/test/java/org/springframework/sbm/openrewrite/java/RetrieveAnnotationTypeTest.java +++ b/components/sbm-openrewrite/src/test/java/org/springframework/sbm/openrewrite/java/RetrieveAnnotationTypeTest.java @@ -33,10 +33,11 @@ public class RetrieveAnnotationTypeTest { @Test void retrieveAnnotation() { String javaSource = - "import javax.ejb.Stateless;\n" + - "@Stateless\n" + - "public class MyClass {" + - "}"; + """ + import javax.ejb.Stateless; + @Stateless + public class MyClass { } + """; // String mavenRepo = System.getProperty("user.home") + "/.m2/repository"; // List paths = JavaParser.dependenciesFromClasspath("ejb-api"); diff --git a/components/sbm-openrewrite/src/test/java/org/springframework/sbm/support/openrewrite/api/GetImplementsTest.java b/components/sbm-openrewrite/src/test/java/org/springframework/sbm/support/openrewrite/api/GetImplementsTest.java index 80c855cd9..f4874c8cb 100644 --- a/components/sbm-openrewrite/src/test/java/org/springframework/sbm/support/openrewrite/api/GetImplementsTest.java +++ b/components/sbm-openrewrite/src/test/java/org/springframework/sbm/support/openrewrite/api/GetImplementsTest.java @@ -27,28 +27,31 @@ public class GetImplementsTest { @Test void test() { String businessInterface = - "package com.example.jee.app.ejb.local;\n" + - "\n" + - "import javax.ejb.Local;\n" + - "\n" + - "@Local\n" + - "public interface ABusinessInterface {\n" + - " String businessMethod();\n" + - "}"; + """ + package com.example.jee.app.ejb.local; + + import javax.ejb.Local; + + @Local + public interface ABusinessInterface { + String businessMethod(); + } + """; String ejb = - "package com.example.jee.app.ejb.local;\n" + - "\n" + - "import javax.ejb.Stateless;\n" + - "\n" + - "@Stateless\n" + - "public class ABean implements ABusinessInterface {\n" + - "\n" + - " @Override\n" + - " public String businessMethod() {\n" + - " return \"A\";\n" + - " }\n" + - "}"; + """ + package com.example.jee.app.ejb.local; + + import javax.ejb.Stateless; + + @Stateless + public class ABean implements ABusinessInterface { + @Override + public String businessMethod() { + return "A"; + } + } + """; List compilationUnitsFromStrings = OpenRewriteTestSupport.createCompilationUnitsFromStrings(List.of("javax.ejb:javax.ejb-api:3.2"), businessInterface, ejb); diff --git a/components/sbm-recipes-boot-upgrade/pom.xml b/components/sbm-recipes-boot-upgrade/pom.xml index 855e94a01..0aab2b812 100644 --- a/components/sbm-recipes-boot-upgrade/pom.xml +++ b/components/sbm-recipes-boot-upgrade/pom.xml @@ -29,8 +29,8 @@ UTF-8 UTF-8 - 11 - 11 + 17 + 17 @@ -73,6 +73,7 @@ org.springframework.sbm recipe-test-support + ${project.version} test diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CassandraApplicationPropertiesMove.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CassandraApplicationPropertiesMove.java index 6cb8ecc8a..1ef3633ed 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CassandraApplicationPropertiesMove.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CassandraApplicationPropertiesMove.java @@ -36,7 +36,7 @@ public String getDescription() { } @Override - protected TreeVisitor getVisitor() { + public TreeVisitor getVisitor() { return new PropertiesVisitor() { diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtension.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtension.java deleted file mode 100644 index 682ab5c67..000000000 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtension.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2021 - 2023 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.sbm.boot.upgrade_27_30; - - -import lombok.Setter; -import org.jetbrains.annotations.NotNull; -import org.openrewrite.ExecutionContext; -import org.openrewrite.Recipe; -import org.openrewrite.TreeVisitor; -import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.JavaType; - -import java.util.List; -import java.util.Optional; - - -@Setter -public class CrudRepositoryExtension extends Recipe { - - @Override - @NotNull - public String getDisplayName() { - return "Extends CrudRepository for Interfaces that extends PagingAndSortingRepository"; - } - - public CrudRepositoryExtension() { - - } - - public CrudRepositoryExtension(String pagingAndSortingRepository, String targetCrudRepository) { - this.pagingAndSortingRepository = pagingAndSortingRepository; - this.targetCrudRepository = targetCrudRepository; - } - - private String pagingAndSortingRepository; - private String targetCrudRepository; - - @Override - protected @Nullable TreeVisitor getApplicableTest() { - return new JavaIsoVisitor<>() { - @Override - @NotNull - public J.ClassDeclaration visitClassDeclaration(@NotNull J.ClassDeclaration classDecl, @NotNull ExecutionContext executionContext) { - return doesItExtendPagingAndSorting(classDecl) ? applyThisRecipe(classDecl) : ceaseVisit(classDecl); - } - - private boolean doesItExtendPagingAndSorting(J.ClassDeclaration classDecl) { - if (classDecl.getImplements() == null) { - return false; - } - return classDecl.getType().getInterfaces().stream() - .anyMatch(impl -> impl.getFullyQualifiedName().equals(pagingAndSortingRepository)); - } - - private J.ClassDeclaration ceaseVisit(J.ClassDeclaration classDecl) { - return classDecl; - } - - @NotNull - private J.ClassDeclaration applyThisRecipe(J.ClassDeclaration classDecl) { - return classDecl.withMarkers(classDecl.getMarkers().searchResult()); - } - }; - } - - @Override - @NotNull - protected JavaIsoVisitor getVisitor() { - return new JavaIsoVisitor<>() { - @Override - @NotNull - public J.ClassDeclaration visitClassDeclaration(@NotNull J.ClassDeclaration classDecl, @NotNull ExecutionContext executionContext) { - - Optional pagingInterface = getExtendPagingAndSorting(classDecl); - if (pagingInterface.isEmpty()) { - return classDecl; - } - List typeParameters = pagingInterface.get().getTypeParameters(); - doAfterVisit(new ImplementTypedInterface<>(classDecl, targetCrudRepository, typeParameters)); - return classDecl; - } - - private Optional getExtendPagingAndSorting(J.ClassDeclaration classDecl) { - if (classDecl.getType() == null) { - return Optional.empty(); - } - return classDecl.getType().getInterfaces().stream() - .filter(impl -> impl.getFullyQualifiedName().equals(pagingAndSortingRepository)) - .findAny(); - } - }; - - } -} diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionWithReferences.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionWithReferences.java deleted file mode 100644 index 401bee824..000000000 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionWithReferences.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright 2021 - 2023 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.sbm.boot.upgrade_27_30; - - -import lombok.Setter; -import org.jetbrains.annotations.NotNull; -import org.openrewrite.ExecutionContext; -import org.openrewrite.Recipe; -import org.openrewrite.SourceFile; -import org.openrewrite.internal.ListUtils; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.JavaType; -import org.openrewrite.java.tree.MethodCall; -import org.openrewrite.java.tree.TypeUtils; - -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - - -@Setter -public class CrudRepositoryExtensionWithReferences extends Recipe { - - @Override - @NotNull - public String getDisplayName() { - return "Extends CrudRepository for Interfaces that extends PagingAndSortingRepository"; - } - - public CrudRepositoryExtensionWithReferences() { - - } - - public CrudRepositoryExtensionWithReferences(String pagingAndSortingRepository, String targetCrudRepository) { - this.pagingAndSortingRepository = pagingAndSortingRepository; - this.targetCrudRepository = targetCrudRepository; - } - - private String pagingAndSortingRepository; - private String targetCrudRepository; - - @Override - protected List visit(List allSourceFiles, ExecutionContext ctx) { - - Set classesToAddCrudRepository = new HashSet<>(); - for (SourceFile source : allSourceFiles) { - - if (source instanceof J) { - J cu = (J) source; - - new JavaIsoVisitor() { - - @Override - public J.MemberReference visitMemberReference(J.MemberReference memberRef, Integer integer) { - - JavaType callingClassType = memberRef.getContaining().getType(); - JavaType.FullyQualified fullyQualified = TypeUtils.asFullyQualified(callingClassType); - - if ((fullyQualified != null) - && shouldApplyCrudExtension(callingClassType, memberRef)) { - classesToAddCrudRepository.add(fullyQualified.getFullyQualifiedName()); - } - - return super.visitMemberReference(memberRef, integer); - } - - @Override - public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Integer integer) { - if (method.getSelect() == null) { - return super.visitMethodInvocation(method, integer); - } - - JavaType callingClassType = method.getSelect().getType(); - - if (shouldApplyCrudExtension(callingClassType, method)) { - JavaType.FullyQualified fullyQualified = TypeUtils.asFullyQualified(callingClassType); - if (fullyQualified != null) { - classesToAddCrudRepository.add(fullyQualified.getFullyQualifiedName()); - } - } - - return super.visitMethodInvocation(method, integer); - } - - private boolean shouldApplyCrudExtension(JavaType callingClassType, MethodCall method) { - return TypeUtils.isAssignableTo(pagingAndSortingRepository, callingClassType) - && (method.getMethodType() == null || - TypeUtils.isAssignableTo(targetCrudRepository, method.getMethodType().getDeclaringType())) - ; - } - }.visit(cu, 0); - } - } - - return ListUtils.map(allSourceFiles, sourceFile -> (SourceFile) new JavaIsoVisitor() { - - @Override - public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Integer p) { - JavaType.FullyQualified fullyQualified = TypeUtils.asFullyQualified(classDecl.getType()); - if ( - TypeUtils.isAssignableTo(pagingAndSortingRepository, classDecl.getType()) - && fullyQualified != null - && classesToAddCrudRepository.contains(fullyQualified.getFullyQualifiedName()) - ) { - Optional pagingInterface = getExtendPagingAndSorting(classDecl); - if (pagingInterface.isEmpty()) { - return classDecl; - } - List typeParameters = pagingInterface.get().getTypeParameters(); - doAfterVisit(new ImplementTypedInterface<>(classDecl, targetCrudRepository, typeParameters)); - - return classDecl; - } - - return super.visitClassDeclaration(classDecl, p); - } - }.visit(sourceFile, 0)); - } - - private Optional getExtendPagingAndSorting(J.ClassDeclaration classDecl) { - if (classDecl.getType() == null) { - return Optional.empty(); - } - return classDecl.getType().getInterfaces().stream() - .filter(impl -> impl.getFullyQualifiedName().equals(pagingAndSortingRepository)) - .findAny(); - } - - // @Override -// protected @Nullable TreeVisitor getApplicableTest() { -// return new JavaIsoVisitor<>() { -// @Override -// @NotNull -// public J.ClassDeclaration visitClassDeclaration(@NotNull J.ClassDeclaration classDecl, @NotNull ExecutionContext executionContext) { -// return doesItExtendPagingAndSorting(classDecl) ? applyThisRecipe(classDecl) : ceaseVisit(classDecl); -// } -// -// private boolean doesItExtendPagingAndSorting(J.ClassDeclaration classDecl) { -// if (classDecl.getImplements() == null) { -// return false; -// } -// return classDecl.getType().getInterfaces().stream() -// .anyMatch(impl -> impl.getFullyQualifiedName().equals(pagingAndSortingRepository)); -// } -// -// private J.ClassDeclaration ceaseVisit(J.ClassDeclaration classDecl) { -// return classDecl; -// } -// -// @NotNull -// private J.ClassDeclaration applyThisRecipe(J.ClassDeclaration classDecl) { -// return classDecl.withMarkers(classDecl.getMarkers().searchResult()); -// } -// }; -// } - -// @Override -// @NotNull -// protected JavaIsoVisitor getVisitor() { -// return new JavaIsoVisitor<>() { -// @Override -// @NotNull -// public J.ClassDeclaration visitClassDeclaration(@NotNull J.ClassDeclaration classDecl, @NotNull ExecutionContext executionContext) { -// -// Optional pagingInterface = getExtendPagingAndSorting(classDecl); -// if (pagingInterface.isEmpty()) { -// return classDecl; -// } -// List typeParameters = pagingInterface.get().getTypeParameters(); -// doAfterVisit(new ImplementTypedInterface<>(classDecl, targetCrudRepository, typeParameters)); -// return classDecl; -// } -// -// private Optional getExtendPagingAndSorting(J.ClassDeclaration classDecl) { -// if (classDecl.getType() == null) { -// return Optional.empty(); -// } -// return classDecl.getType().getInterfaces().stream() -// .filter(impl -> impl.getFullyQualifiedName().equals(pagingAndSortingRepository)) -// .findAny(); -// } -// }; -// -// } -} diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/ImplementTypedInterface.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/ImplementTypedInterface.java deleted file mode 100644 index 65bbe715e..000000000 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/ImplementTypedInterface.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 2021 - 2023 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.sbm.boot.upgrade_27_30; - -import org.jetbrains.annotations.NotNull; -import org.openrewrite.Tree; -import org.openrewrite.internal.ListUtils; -import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.tree.*; -import org.openrewrite.marker.Markers; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class ImplementTypedInterface

extends JavaIsoVisitor

{ - private final J.ClassDeclaration scope; - private final JavaType.FullyQualified interfaceType; - private final List typeParameters; - - public ImplementTypedInterface(J.ClassDeclaration scope, JavaType.FullyQualified interfaceType, List typeParameters) { - this.scope = scope; - this.interfaceType = interfaceType; - this.typeParameters = typeParameters; - } - - public ImplementTypedInterface(J.ClassDeclaration scope, String interfaze, List typeParameters) { - this(scope, JavaType.ShallowClass.build(interfaze), typeParameters); - } - - @NotNull - public J.ClassDeclaration visitClassDeclaration(@NotNull J.ClassDeclaration classDecl, @NotNull P p) { - J.ClassDeclaration c = super.visitClassDeclaration(classDecl, p); - if (c.isScope(this.scope) && (c.getImplements() == null || c.getImplements().stream().noneMatch((f) -> TypeUtils.isAssignableTo(f.getType(), this.interfaceType)))) { - if (!classDecl.getSimpleName().equals(this.interfaceType.getClassName())) { - this.maybeAddImport(this.interfaceType); - } - - TypeTree type = TypeTree.build(classDecl.getSimpleName().equals(this.interfaceType.getClassName()) ? this.interfaceType.getFullyQualifiedName() : this.interfaceType.getClassName()).withType(this.interfaceType).withPrefix(Space.format(" ")); - if (typeParameters != null && !typeParameters.isEmpty() && typeParameters.stream().noneMatch(tp -> tp instanceof JavaType.GenericTypeVariable)) { - type = new J.ParameterizedType(UUID.randomUUID(), Space.EMPTY, Markers.EMPTY, type, buildTypeParameters(typeParameters)); - } - c = c.withImplements(ListUtils.concat(c.getImplements(), type)); - JContainer anImplements = c.getPadding().getImplements(); - - assert anImplements != null; - - if (anImplements.getBefore().getWhitespace().isEmpty()) { - c = c.getPadding().withImplements(anImplements.withBefore(Space.format(" "))); - } - } - - return c; - } - - @Nullable - private JContainer buildTypeParameters(List typeParameters) { - List> typeExpressions = new ArrayList<>(); - - int index = 0; - for (JavaType type : typeParameters) { - Expression typeParameterExpression = (Expression) buildTypeTree(type, (index++ == 0) ? Space.EMPTY : Space.format(" ")); - if (typeParameterExpression == null) { - return null; - } - typeExpressions.add(new JRightPadded<>( - typeParameterExpression, - Space.EMPTY, - Markers.EMPTY - )); - } - return JContainer.build(Space.EMPTY, typeExpressions, Markers.EMPTY); - } - - private TypeTree buildTypeTree(@Nullable JavaType type, Space space) { - if (type == null || type instanceof JavaType.Unknown) { - return null; - } else if (type instanceof JavaType.FullyQualified fq) { - - J.Identifier identifier = new J.Identifier(Tree.randomId(), - space, - Markers.EMPTY, - fq.getClassName(), - type, - null - ); - - if (!fq.getTypeParameters().isEmpty()) { - JContainer typeParameters = buildTypeParameters(fq.getTypeParameters()); - if (typeParameters == null) { - //If there is a problem resolving one of the type parameters, then do not return a type - //expression for the fully-qualified type. - return null; - } - return new J.ParameterizedType( - Tree.randomId(), - space, - Markers.EMPTY, - identifier, - typeParameters - ); - - } else { - maybeAddImport(fq); - return identifier; - } - } else if (type instanceof JavaType.GenericTypeVariable genericType) { - if (!genericType.getName().equals("?")) { - return new J.Identifier(Tree.randomId(), - space, - Markers.EMPTY, - genericType.getName(), - type, - null - ); - } - JLeftPadded bound = null; - NameTree boundedType = null; - if (genericType.getVariance() == JavaType.GenericTypeVariable.Variance.COVARIANT) { - bound = new JLeftPadded<>(Space.format(" "), J.Wildcard.Bound.Extends, Markers.EMPTY); - } else if (genericType.getVariance() == JavaType.GenericTypeVariable.Variance.CONTRAVARIANT) { - bound = new JLeftPadded<>(Space.format(" "), J.Wildcard.Bound.Super, Markers.EMPTY); - } - - if (!genericType.getBounds().isEmpty()) { - boundedType = buildTypeTree(genericType.getBounds().get(0), Space.format(" ")); - if (boundedType == null) { - return null; - } - } - - return new J.Wildcard( - Tree.randomId(), - space, - Markers.EMPTY, - bound, - boundedType - ); - } - return null; - - } -} - diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/checks/DatabaseDriverGaeSectionBuilder.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/checks/DatabaseDriverGaeSectionBuilder.java index 564ada81b..335032452 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/checks/DatabaseDriverGaeSectionBuilder.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/checks/DatabaseDriverGaeSectionBuilder.java @@ -44,7 +44,7 @@ public Sbu30_PreconditionCheckResult run(ProjectContext context) { if(collect.isEmpty()) { return new Sbu30_PreconditionCheckResult(PreconditionCheck.ResultState.PASSED, "No dependency to Google AppEngine's AppEngineDriver found."); } else { - String message = "Dependencies containing 'com.google.appengine.api.rdbms.AppEngineDriver' were found in these modules: '" + collect.stream().map(m -> m.getBuildFile().getCoordinates()).collect(Collectors.joining("', '")) + "'"; + String message = "Dependencies containing 'com.google.appengine.api.rdbms.AppEngineDriver' were found in these modules: '" + collect.stream().map(m -> m.getBuildFile().getGav()).collect(Collectors.joining("', '")) + "'"; return new Sbu30_PreconditionCheckResult(PreconditionCheck.ResultState.FAILED, message); } } diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/checks/RedeclaredDependenciesBuilder.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/checks/RedeclaredDependenciesBuilder.java index 82b7b75ed..9a14f7f12 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/checks/RedeclaredDependenciesBuilder.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/checks/RedeclaredDependenciesBuilder.java @@ -46,7 +46,7 @@ public Section build(ProjectContext projectContext) { Set matches = finder.findMatches(projectContext); List todos = matches.stream() .map(m -> TodoList.Todo.builder() - .text(String.format("Remove explicit declaration of version for artifact: %s, its already declared with version %s", m.getRedeclaredDependency().getCoordinates(), m.originalVersion())) + .text(String.format("Remove explicit declaration of version for artifact: %s, its already declared with version %s", m.getRedeclaredDependency().getGav(), m.originalVersion())) .build()).toList(); return ChangeSection.RelevantChangeSection.builder() diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/openrewrite/SecurityManagerUsagesFinder.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/openrewrite/SecurityManagerUsagesFinder.java index b4d430006..6e36ac3d6 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/openrewrite/SecurityManagerUsagesFinder.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/openrewrite/SecurityManagerUsagesFinder.java @@ -36,7 +36,12 @@ public String getDisplayName() { } @Override - protected TreeVisitor getVisitor() { + public String getDescription() { + return getDisplayName(); + } + + @Override + public TreeVisitor getVisitor() { return new JavaIsoVisitor<>() { @Override public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) { diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportDataProvider.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportDataProvider.java index a5965ac97..8bae8b9d3 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportDataProvider.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportDataProvider.java @@ -42,7 +42,7 @@ public Map getData(ProjectContext context, @Valid List> recipe = - new GenericOpenRewriteRecipe<>(() -> new UsesType("org.springframework.boot.context.properties.ConstructorBinding")); + new GenericOpenRewriteRecipe<>(() -> new UsesType("org.springframework.boot.context.properties.ConstructorBinding", false)); List> rewriteSourceFileHolders = context.getProjectJavaSources().find(recipe); diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/JohnzonDependencyHelper.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/JohnzonDependencyHelper.java index 54c22247c..8f8c2f578 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/JohnzonDependencyHelper.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/JohnzonDependencyHelper.java @@ -35,10 +35,10 @@ public String getDescription() { @Override public boolean evaluate(ProjectContext context) { - - Optional d = context.getBuildFile().getDeclaredDependencies().stream() - .filter(x -> x.getCoordinates().contains("org.apache.johnzon:johnzon-core")).findFirst(); - return d.isPresent(); + return context.getApplicationModules().getRootModule().getBuildFile() + .getDeclaredDependencies() + .stream() + .anyMatch(x -> x.getGav().contains("org.apache.johnzon:johnzon-core")); } @Override diff --git a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesHelper.java b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesHelper.java index 707ba7efe..1f1c2988a 100644 --- a/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesHelper.java +++ b/components/sbm-recipes-boot-upgrade/src/main/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/SpringMVCAndWebFluxUrlMatchingChangesHelper.java @@ -51,7 +51,7 @@ public boolean evaluate(ProjectContext context) { return false; } - GenericOpenRewriteRecipe> usesTypeRecipe = new GenericOpenRewriteRecipe<>(() -> new UsesType<>(SPRING_REST_CONTROLLER_FQN)); + GenericOpenRewriteRecipe> usesTypeRecipe = new GenericOpenRewriteRecipe<>(() -> new UsesType<>(SPRING_REST_CONTROLLER_FQN, false)); matches = context.getProjectJavaSources().find(usesTypeRecipe).stream() .filter(m -> OpenRewriteJavaSource.class.isInstance(m)) diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java index 4ca962036..70e08f74f 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java @@ -24,7 +24,7 @@ import com.tngtech.archunit.lang.ArchRule; import org.openrewrite.ExecutionContext; import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/ConfigRecipeTestHelper.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/ConfigRecipeTestHelper.java index 66f4ecabb..fd674e3d7 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/ConfigRecipeTestHelper.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/ConfigRecipeTestHelper.java @@ -21,6 +21,8 @@ import org.junit.jupiter.params.provider.Arguments; import org.openrewrite.InMemoryExecutionContext; import org.openrewrite.Result; +import org.openrewrite.SourceFile; +import org.openrewrite.internal.InMemoryLargeSourceSet; import org.openrewrite.properties.PropertiesParser; import org.openrewrite.properties.tree.Properties; import org.openrewrite.test.RewriteTest; @@ -42,10 +44,10 @@ public class ConfigRecipeTestHelper { public static List runRecipeOnYaml(@Language("yml") String source, String recipeName) { InMemoryExecutionContext ctx = new InMemoryExecutionContext(Throwable::printStackTrace); - List document = new YamlParser().parse(source); + List document = new YamlParser().parse(source).toList(); return RewriteTest .fromRuntimeClasspath(recipeName) - .run(document, ctx).getResults(); + .run(new InMemoryLargeSourceSet(document), ctx).getChangeset().getAllResults(); } // public static List runRecipeOnProperties(@Language("properties") String source, String recipeName) { diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionTest.java deleted file mode 100644 index 925015c18..000000000 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionTest.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright 2021 - 2023 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.sbm.boot.upgrade_27_30; - -import org.jetbrains.annotations.NotNull; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.openrewrite.Recipe; -import org.openrewrite.Result; -import org.openrewrite.test.RewriteTest; - -import java.util.List; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; - - -public class CrudRepositoryExtensionTest implements RewriteTest { - - private final JavaTestHelper javaTestHelper = new JavaTestHelper(); - private static final Recipe crudRepoExtensionRecipe = new CrudRepositoryExtensionWithReferences( - "org.springframework.data.repository.PagingAndSortingRepository", - "org.springframework.data.repository.CrudRepository" - ); - - private static final Recipe reactiveCrudExtensionRecipe = new CrudRepositoryExtensionWithReferences( - "org.springframework.data.repository.reactive.ReactiveSortingRepository", - "org.springframework.data.repository.reactive.ReactiveCrudRepository" - ); - - private static final Recipe rxJavaCrudExtensionRecipe = new CrudRepositoryExtensionWithReferences( - "org.springframework.data.repository.reactive.RxJava3SortingRepository", - "org.springframework.data.repository.reactive.RxJava3CrudRepository" - ); - - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - public void shouldAddCrudRepository(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - void save(T entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - public interface A extends -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(result, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - public interface A extends -pagingRepository-, -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage - )); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - public void canDoQuestionMark(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - - @NotNull List result = javaTestHelper.runRecipe(recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - void save(T); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public interface Payment { - T hello(); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - public interface A extends -pagingRepository-, Long> { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(result, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - public interface A extends -pagingRepository-, Long>, -crudRepository-, Long> { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)); - } - - @MethodSource("repositoryTestArguments") - @ParameterizedTest - public void whenThereAreNoParametersWhilstExtending(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - - @NotNull List results = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - public interface A extends -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(results, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - public interface A extends -pagingRepository-, -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)); - } - - @MethodSource("repositoryTestArguments") - @ParameterizedTest - public void multipleExtends(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - @NotNull List results = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package temp; - public interface Hello { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - import temp.Hello; - public interface A extends Hello, -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(results, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - import temp.Hello; - - public interface A extends Hello, -pagingRepository-, -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)); - } - - @MethodSource("repositoryTestArguments") - @ParameterizedTest - public void classImplementsPagingRepository(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - """ - package temp; - public interface Hello { - } - """, - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - import temp.Hello; - public class A implements Hello, -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(result, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - import temp.Hello; - - public class A implements Hello, -pagingRepository-, -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - void shouldExtendCrudRepositoryInInnerInterface(Recipe recipe, String pagingAndSortingRepository, - String crudRepository, - String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - void save(String entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - class Hello { - public interface A extends -pagingRepository- { - } - - public void myCall(A a) { - a.save(""); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - assertThat(result).hasSize(1); - assertThat(result.get(0).getAfter().printAll()) - .isEqualTo( - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - class Hello { - public interface A extends -pagingRepository-, -crudRepository- { - } - - public void myCall(A a) { - a.save(""); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - void shouldExtendCrudRepositoryForCrudMethodReference(Recipe recipe, String pagingAndSortingRepository, - String crudRepository, - String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - void save(String entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ), - replacePagingRepoAndCrudRepo(""" - package test; - import java.util.List; - - import -repositoryPackage-.-pagingRepository-; - - class Hello { - public interface A extends -pagingRepository- { - } - - public void myCall(A a) { - List.of("1", "2", "3").stream() - .forEach(a::save); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - assertThat(result).hasSize(1); - assertThat(result.get(0).getAfter().printAll()) - .isEqualTo( - replacePagingRepoAndCrudRepo(""" - package test; - import java.util.List; - - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - class Hello { - public interface A extends -pagingRepository-, -crudRepository- { - } - - public void myCall(A a) { - List.of("1", "2", "3").stream() - .forEach(a::save); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - } - - private String replacePagingRepoAndCrudRepo(String template, String pagingRepo, String crudRepo, String repositoryPackage) { - - return template - .replaceAll("-pagingRepository-", pagingRepo) - .replaceAll("-crudRepository-", crudRepo) - .replaceAll("-repositoryPackage-", repositoryPackage); - } - - private static Stream repositoryTestArguments() { - return Stream.of( - Arguments.of(crudRepoExtensionRecipe, "PagingAndSortingRepository", "CrudRepository", "org.springframework.data.repository"), - Arguments.of(reactiveCrudExtensionRecipe, "ReactiveSortingRepository", "ReactiveCrudRepository", "org.springframework.data.repository.reactive"), - Arguments.of(rxJavaCrudExtensionRecipe, "RxJava3SortingRepository", "RxJava3CrudRepository", "org.springframework.data.repository.reactive") - ); - } -} diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionWithReferencesTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionWithReferencesTest.java deleted file mode 100644 index 54dae5fb6..000000000 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/CrudRepositoryExtensionWithReferencesTest.java +++ /dev/null @@ -1,587 +0,0 @@ -/* - * Copyright 2021 - 2023 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.sbm.boot.upgrade_27_30; - -import org.jetbrains.annotations.NotNull; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.openrewrite.Recipe; -import org.openrewrite.Result; -import org.openrewrite.test.RewriteTest; - -import java.util.List; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; - - -public class CrudRepositoryExtensionWithReferencesTest implements RewriteTest { - - private final JavaTestHelper javaTestHelper = new JavaTestHelper(); - private static final Recipe crudRepoExtensionRecipe = new CrudRepositoryExtensionWithReferences( - "org.springframework.data.repository.PagingAndSortingRepository", - "org.springframework.data.repository.CrudRepository" - ); - - private static final Recipe reactiveCrudExtensionRecipe = new CrudRepositoryExtensionWithReferences( - "org.springframework.data.repository.reactive.ReactiveSortingRepository", - "org.springframework.data.repository.reactive.ReactiveCrudRepository" - ); - - private static final Recipe rxJavaCrudExtensionRecipe = new CrudRepositoryExtensionWithReferences( - "org.springframework.data.repository.reactive.RxJava3SortingRepository", - "org.springframework.data.repository.reactive.RxJava3CrudRepository" - ); - - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - public void shouldAddCrudRepository(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - void save(T entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - public interface A extends -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(result, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - public interface A extends -pagingRepository-, -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage - )); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - public void canDoQuestionMark(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - - @NotNull List result = javaTestHelper.runRecipe(recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - void save(T); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public interface Payment { - T hello(); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - public interface A extends -pagingRepository-, Long> { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(result, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - public interface A extends -pagingRepository-, Long>, -crudRepository-, Long> { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)); - } - - @MethodSource("repositoryTestArguments") - @ParameterizedTest - public void onlyExtendCrudRepoIfInterfaceHasPagingAndSortingRepository(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe(recipe, - List.of(""" - package -repositoryPackage-; - public interface HelloWorld { - } - """, - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - """ - package test; - public interface Payment { - T hello(); - } - """, - """ - package test; - import org.springframework.data.repository.HelloWorld; - public interface A extends HelloWorld, Long> { - } - """ - ) - ); - - assertThat(result).hasSize(0); - } - - - @MethodSource("repositoryTestArguments") - @ParameterizedTest - public void whenThereAreNoParametersWhilstExtending(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - - @NotNull List results = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - public interface A extends -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(results, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - public interface A extends -pagingRepository-, -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)); - } - - @MethodSource("repositoryTestArguments") - @ParameterizedTest - public void multipleExtends(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - @NotNull List results = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package temp; - public interface Hello { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - import temp.Hello; - public interface A extends Hello, -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(results, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - import temp.Hello; - - public interface A extends Hello, -pagingRepository-, -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)); - } - - @MethodSource("repositoryTestArguments") - @ParameterizedTest - public void classImplementsPagingRepository(Recipe recipe, String pagingAndSortingRepository, String crudRepository, String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - """ - package temp; - public interface Hello { - } - """, - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - import temp.Hello; - public class A implements Hello, -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - public class Hello { - public void test(A a) { - a.save("Hello"); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - javaTestHelper.assertResult(result, replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - import temp.Hello; - - public class A implements Hello, -pagingRepository-, -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage)); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - void shouldExtendCrudRepositoryInInnerInterface(Recipe recipe, String pagingAndSortingRepository, - String crudRepository, - String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - void save(String entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - class Hello { - public interface A extends -pagingRepository- { - } - - public void myCall(A a) { - a.save(""); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - assertThat(result).hasSize(1); - assertThat(result.get(0).getAfter().printAll()) - .isEqualTo( - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - class Hello { - public interface A extends -pagingRepository-, -crudRepository- { - } - - public void myCall(A a) { - a.save(""); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - void shouldNotExtendCrudRepositoryIfMethodIsNotCrud(Recipe recipe, String pagingAndSortingRepository, - String crudRepository, - String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - void findAll(String entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - - public interface A extends -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - import -repositoryPackage-.-pagingRepository-; - - public interface B extends -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package test; - class Hello { - - public void myCall(A a, B b) { - a.findAll(""); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - assertThat(result).hasSize(0); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - void shouldExtendCrudRepositoryForCrudMethodReference(Recipe recipe, String pagingAndSortingRepository, - String crudRepository, - String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - void save(String entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ), - replacePagingRepoAndCrudRepo(""" - package test; - import java.util.List; - - import -repositoryPackage-.-pagingRepository-; - - class Hello { - public interface A extends -pagingRepository- { - } - - public void myCall(A a) { - List.of("1", "2", "3").stream() - .forEach(a::save); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - assertThat(result).hasSize(1); - assertThat(result.get(0).getAfter().printAll()) - .isEqualTo( - replacePagingRepoAndCrudRepo(""" - package test; - import java.util.List; - - import -repositoryPackage-.-crudRepository-; - import -repositoryPackage-.-pagingRepository-; - - class Hello { - public interface A extends -pagingRepository-, -crudRepository- { - } - - public void myCall(A a) { - List.of("1", "2", "3").stream() - .forEach(a::save); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - void shouldNotExtendCrudRepositoryForNonPagingMethodReference(Recipe recipe, String pagingAndSortingRepository, - String crudRepository, - String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - void save(String entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ), - replacePagingRepoAndCrudRepo(""" - package test; - import java.util.List; - - import -repositoryPackage-.-pagingRepository-; - - class Hello { - public interface A extends -pagingRepository- { - } - - public void myCall(A a) { - List.of("1", "2", "3").stream() - .forEach(a::save); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - assertThat(result).hasSize(0); - } - - @ParameterizedTest - @MethodSource("repositoryTestArguments") - public void worksWithStaticImports(Recipe recipe, String pagingAndSortingRepository, - String crudRepository, - String repositoryPackage) { - @NotNull List result = javaTestHelper.runRecipe( - recipe, - List.of(replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -crudRepository- { - - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - replacePagingRepoAndCrudRepo(""" - package -repositoryPackage-; - public interface -pagingRepository- { - void save(String entity); - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage), - """ - package test; - - public class StaticClass { - public static int ret() { - return 0; - } - } - """ - ), - - replacePagingRepoAndCrudRepo(""" - package test; - import java.util.List; - import static StaticClass.*; - import -repositoryPackage-.-pagingRepository-; - - class Hello { - public static int temp() { - return 10; - } - public interface A extends -pagingRepository- { - } - - public void myCall(A a) { - int x = ret(); - List.of("1", "2", "3").stream() - .forEach(a::save); - } - } - """, pagingAndSortingRepository, crudRepository, repositoryPackage) - ); - - assertThat(result).hasSize(0); - } - - - private String replacePagingRepoAndCrudRepo(String template, String pagingRepo, String crudRepo, String repositoryPackage) { - - return template - .replaceAll("-pagingRepository-", pagingRepo) - .replaceAll("-crudRepository-", crudRepo) - .replaceAll("-repositoryPackage-", repositoryPackage); - } - - private static Stream repositoryTestArguments() { - return Stream.of( - Arguments.of(crudRepoExtensionRecipe, "PagingAndSortingRepository", "CrudRepository", "org.springframework.data.repository"), - Arguments.of(reactiveCrudExtensionRecipe, "ReactiveSortingRepository", "ReactiveCrudRepository", "org.springframework.data.repository.reactive"), - Arguments.of(rxJavaCrudExtensionRecipe, "RxJava3SortingRepository", "RxJava3CrudRepository", "org.springframework.data.repository.reactive") - ); - } -} diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/JavaTestHelper.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/JavaTestHelper.java deleted file mode 100644 index 3002afa28..000000000 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/JavaTestHelper.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2021 - 2023 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.sbm.boot.upgrade_27_30; - -import org.intellij.lang.annotations.Language; -import org.jetbrains.annotations.NotNull; -import org.openrewrite.InMemoryExecutionContext; -import org.openrewrite.Recipe; -import org.openrewrite.Result; -import org.openrewrite.java.JavaParser; -import org.openrewrite.java.tree.J; -import org.openrewrite.test.RewriteTest; - -import java.util.ArrayList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -public class JavaTestHelper { - - public void runAndVerifyNoChanges( - Recipe recipe, - List dependsOn, - @Language("java") String before - ) { - List result = runRecipe(recipe, dependsOn, before); - assertThat(result).hasSize(0); - } - - - @NotNull - public List runRecipe(Recipe recipe, List dependsOn, @Language("java") String... before) { - - List errors = new ArrayList<>(); - InMemoryExecutionContext ctx = new InMemoryExecutionContext((ex) -> { - ex.printStackTrace(); - errors.add(ex); - }); - - JavaParser parser = JavaParser - .fromJavaVersion() - .dependsOn(dependsOn.toArray(new String[0])) - .build(); - - List cu = parser.parse(before); - - List result = recipe.run(cu, ctx).getResults(); - - assertThat(errors).hasSize(0); - return result; - } - - public void assertResult(List result, String after) { - - assertThat(result).hasSize(1); - assertThat(result.get(0).getAfter().printAll()).isEqualTo(after); - } -} diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/UpgradeBomTo30Test.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/UpgradeBomTo30Test.java index b77c5ca48..e262811fb 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/UpgradeBomTo30Test.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/UpgradeBomTo30Test.java @@ -15,10 +15,13 @@ */ package org.springframework.sbm.boot.upgrade_27_30; +import jnr.ffi.annotations.In; import org.junit.jupiter.api.Test; import org.openrewrite.InMemoryExecutionContext; import org.openrewrite.Recipe; import org.openrewrite.Result; +import org.openrewrite.SourceFile; +import org.openrewrite.internal.InMemoryLargeSourceSet; import org.openrewrite.maven.MavenParser; import org.openrewrite.maven.UpgradeDependencyVersion; import org.openrewrite.xml.tree.Xml; @@ -37,6 +40,7 @@ void shouldUpdateBomVersionTo30() { "spring-boot-dependencies", "3.0.0-M3", null, + null, null ); @@ -47,7 +51,7 @@ void shouldUpdateBomVersionTo30() { }); MavenParser parser = MavenParser.builder().build(); - List documentList = parser.parse(""" + List documentList = parser.parse(""" @@ -93,9 +97,10 @@ void shouldUpdateBomVersionTo30() { - """); + """) + .toList(); - List result = recipe.run(documentList, ctx).getResults(); + List result = recipe.run(new InMemoryLargeSourceSet(documentList), ctx).getChangeset().getAllResults(); assertThat(result).hasSize(1); @@ -156,6 +161,7 @@ public void whenThereIsNoBomNoChanges() { "spring-boot-dependencies", "3.0.0-M3", null, + null, null ); @@ -166,7 +172,7 @@ public void whenThereIsNoBomNoChanges() { }); MavenParser parser = MavenParser.builder().build(); - List documentList = parser.parse(""" + List documentList = parser.parse(""" @@ -206,9 +212,10 @@ public void whenThereIsNoBomNoChanges() { - """); + """) + .toList(); - List result = recipe.run(documentList, ctx).getResults(); + List result = recipe.run(new InMemoryLargeSourceSet(documentList), ctx).getChangeset().getAllResults(); assertThat(result).hasSize(0); } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/JerseyTemporarilyRemovedFinderTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/JerseyTemporarilyRemovedFinderTest.java index 9f640d6ec..47482f8dd 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/JerseyTemporarilyRemovedFinderTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/JerseyTemporarilyRemovedFinderTest.java @@ -39,7 +39,7 @@ void finderShouldFindAnyJerseyDependency() { Set matches = sut.findMatches(context); assertThat(matches).isNotEmpty(); assertThat(matches).hasSize(1); - assertThat(matches.iterator().next().getBuildFile().getDeclaredDependencies(Scope.Compile).get(0).getCoordinates()).isEqualTo(dependencyCoordinates); + assertThat(matches.iterator().next().getBuildFile().getDeclaredDependencies(Scope.Compile).get(0).getGav()).isEqualTo(dependencyCoordinates); } @Test @@ -122,7 +122,7 @@ void finderShouldFindOnlyJerseyDependency() { assertThat(context.getApplicationModules().list()).hasSize(3); assertThat(matches).isNotEmpty(); assertThat(matches).hasSize(1); - assertThat(matches.iterator().next().getBuildFile().getDeclaredDependencies(Scope.Compile).get(0).getCoordinates()).isEqualTo(jerseyDependencyCoordinates); + assertThat(matches.iterator().next().getBuildFile().getDeclaredDependencies(Scope.Compile).get(0).getGav()).isEqualTo(jerseyDependencyCoordinates); } } diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/RedeclaredDependenciesFinderTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/RedeclaredDependenciesFinderTest.java index 5dfcc111d..743ecb73d 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/RedeclaredDependenciesFinderTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/checks/RedeclaredDependenciesFinderTest.java @@ -90,7 +90,7 @@ void shouldFindDependencyRedefinedParentVersion() { assertThat(matches).hasSize(1); RedeclaredDependency explicitDependency = matches.iterator().next(); String explicitVersionDependencyCoordinates = "javax.validation:validation-api:1.1.0.Final"; - assertThat(explicitDependency.getRedeclaredDependency().getCoordinates()).isEqualTo(explicitVersionDependencyCoordinates); + assertThat(explicitDependency.getRedeclaredDependency().getGav()).isEqualTo(explicitVersionDependencyCoordinates); assertThat(explicitDependency.getOriginalVersion()).isEqualTo("2.0.0.Final"); } @@ -152,7 +152,7 @@ void shouldReportSameVersion() { assertThat(matches).hasSize(1); RedeclaredDependency explicitDependency = matches.iterator().next(); String explicitVersionDependencyCoordinates = "javax.validation:validation-api:2.0.0.Final"; - assertThat(explicitDependency.getRedeclaredDependency().getCoordinates()).isEqualTo(explicitVersionDependencyCoordinates); + assertThat(explicitDependency.getRedeclaredDependency().getGav()).isEqualTo(explicitVersionDependencyCoordinates); assertThat(explicitDependency.getOriginalVersion()).isEqualTo("2.0.0.Final"); } @@ -231,7 +231,7 @@ void shouldFindDependencyRedefinedBomVersion() { assertThat(context.getApplicationModules().list()).hasSize(2); assertThat(matches).isNotEmpty(); assertThat(matches).hasSize(1); - assertThat(matches.iterator().next().getRedeclaredDependency().getCoordinates()).isEqualTo(explicitVersionDependencyCoordinates); + assertThat(matches.iterator().next().getRedeclaredDependency().getGav()).isEqualTo(explicitVersionDependencyCoordinates); } @Test @@ -350,8 +350,8 @@ void shouldFindAllRedefinedDependencies() { ProjectContext context = TestProjectContext.buildProjectContext() .withMavenRootBuildFileSource(parentPomXml) .withMavenBuildFileSource("module1", module1PomXml) - .serializeProjectContext(Path.of("./target/test")); -// .build(); +// .serializeProjectContext(Path.of("./target/test")); + .build(); RedeclaredDependenciesFinder finder = new RedeclaredDependenciesFinder(Set.of()); Set matches = finder.findMatches(context); @@ -445,7 +445,7 @@ void shouldFindRedeclaredDependenciesOnlyFromList() { assertThat(matches).hasSize(1); RedeclaredDependency explicitDependency = matches.iterator().next(); String explicitVersionDependencyCoordinates = "javax.validation:validation-api:1.1.0.Final"; - assertThat(explicitDependency.getRedeclaredDependency().getCoordinates()).isEqualTo(explicitVersionDependencyCoordinates); + assertThat(explicitDependency.getRedeclaredDependency().getGav()).isEqualTo(explicitVersionDependencyCoordinates); assertThat(explicitDependency.getOriginalVersion()).isEqualTo("2.0.1.Final"); } 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..e1110fcec 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 @@ -21,6 +21,8 @@ import org.junit.jupiter.params.provider.Arguments; import org.openrewrite.InMemoryExecutionContext; import org.openrewrite.Result; +import org.openrewrite.SourceFile; +import org.openrewrite.internal.InMemoryLargeSourceSet; import org.openrewrite.properties.PropertiesParser; import org.openrewrite.properties.tree.Properties; import org.openrewrite.test.RewriteTest; @@ -42,18 +44,18 @@ public class ConfigRecipeTestHelper { public static List runRecipeOnYaml(@Language("yml") String source, String recipeName) { InMemoryExecutionContext ctx = new InMemoryExecutionContext(Throwable::printStackTrace); - List document = new YamlParser().parse(source); + Stream document = new YamlParser().parse(source); return RewriteTest .fromRuntimeClasspath(recipeName) - .run(document, ctx).getResults(); + .run(new InMemoryLargeSourceSet(document.toList()), ctx).getChangeset().getAllResults(); } public static List runRecipeOnProperties(@Language("properties") String source, String recipeName) { InMemoryExecutionContext ctx = new InMemoryExecutionContext(Throwable::printStackTrace); - List document = new PropertiesParser().parse(source); + List document = new PropertiesParser().parse(source).toList(); return RewriteTest .fromRuntimeClasspath(recipeName) - .run(document, ctx).getResults(); + .run(new InMemoryLargeSourceSet(document), ctx).getChangeset().getAllResults(); } public static Pair provideIO(String inputFilePath) throws IOException { diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportActionTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportActionTest.java index a2f1411ab..f4b50e72d 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportActionTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/SpringBootUpgradeReportActionTest.java @@ -201,7 +201,7 @@ void verifyRenderedHtml(@TempDir Path tempDir) throws IOException { .withMavenRootBuildFileSource(pomSource) .withProjectResource("src/main/resources/application.properties", "spring.data.foo=bar") .withProjectResource("src/main/resources/application-another.properties", "spring.data.here=there") - .serializeProjectContext(tempDir); + .buildAndSerializeProjectContext(tempDir); RecipeIntegrationTestSupport.initializeProject(tempDir, "spring-upgrade-report") .andApplyRecipe("sbu30-report"); diff --git a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/UpgradeDepenenciesMigrationTest.java b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/UpgradeDepenenciesMigrationTest.java index e37062b4e..e90d62077 100644 --- a/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/UpgradeDepenenciesMigrationTest.java +++ b/components/sbm-recipes-boot-upgrade/src/test/java/org/springframework/sbm/boot/upgrade_27_30/report/helper/UpgradeDepenenciesMigrationTest.java @@ -17,6 +17,7 @@ import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; +import org.openrewrite.SourceFile; import org.openrewrite.maven.MavenParser; import org.openrewrite.xml.tree.Xml; import org.springframework.sbm.engine.context.ProjectContext; @@ -41,7 +42,7 @@ void migrateEhCacheToSpringBoot3() { .withBuildFileHavingDependencies("org.ehcache:ehcache") .build(); - System.out.println(context.getBuildFile().print()); + System.out.println(context.getApplicationModules().getRootModule().getBuildFile().print()); RecipeTestSupport.testRecipe(Path.of("recipes/27_30/migration/sbu30-upgrade-dependencies.yaml"), recipes -> { Recipe recipe = recipes.getRecipeByName("sbu30-upgrade-dependencies").get(); @@ -75,7 +76,7 @@ void migrateEhCacheToSpringBoot3() { """ ); - Xml.Document document = MavenParser.builder().build().parse(modifiedPom).get(0); + SourceFile document = MavenParser.builder().build().parse(modifiedPom).toList().get(0); assertThat(document).isNotNull(); }); } diff --git a/components/sbm-recipes-jee-to-boot/pom.xml b/components/sbm-recipes-jee-to-boot/pom.xml index fdd967f28..2ce02fa4b 100644 --- a/components/sbm-recipes-jee-to-boot/pom.xml +++ b/components/sbm-recipes-jee-to-boot/pom.xml @@ -88,16 +88,20 @@ aspectjweaver - + + + + + + + + + - javax.xml.bind - jaxb-api + org.openrewrite.recipe + rewrite-static-analysis + 1.0.7 - - org.glassfish.jaxb - jaxb-runtime - - org.springframework.sbm test-helper @@ -119,6 +123,7 @@ org.springframework.sbm recipe-test-support + ${project.version} test diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/ejb/actions/MigrateJndiLookup.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/ejb/actions/MigrateJndiLookup.java index 75a4ff501..bda37d7c3 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/ejb/actions/MigrateJndiLookup.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/ejb/actions/MigrateJndiLookup.java @@ -15,6 +15,7 @@ */ package org.springframework.sbm.jee.ejb.actions; +import org.openrewrite.staticanalysis.RemoveUnusedLocalVariables; import org.springframework.sbm.engine.recipe.AbstractAction; import org.springframework.sbm.java.api.JavaSource; import org.springframework.sbm.engine.context.ProjectContext; @@ -27,7 +28,7 @@ import org.openrewrite.java.JavaIsoVisitor; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.RemoveUnusedImports; -import org.openrewrite.java.cleanup.RemoveUnusedLocalVariables; +import org.openrewrite.staticanalysis.RemoveUnusedLocalVariables; import org.openrewrite.java.format.AutoFormat; import org.openrewrite.java.tree.*; @@ -47,13 +48,13 @@ public void apply(ProjectContext context) { } private void migrateJndiLookup(JavaSource sourceWithLookup) { - Recipe recipe = new GenericOpenRewriteRecipe<>(() -> new MigrateJndiLookupVisitor()) - .doNext(new RemoveUnusedLocalVariables(null)) - .doNext(new RemoveUnusedImports()) - .doNext(new GenericOpenRewriteRecipe<>(() -> new AddImport<>("org.springframework.beans.factory.annotation.Autowired", null, false))) - .doNext(new AutoFormat()); - - sourceWithLookup.apply(recipe); + sourceWithLookup.apply( + new GenericOpenRewriteRecipe<>(() -> new MigrateJndiLookupVisitor()), + new RemoveUnusedLocalVariables(null), + new RemoveUnusedImports(), + new GenericOpenRewriteRecipe<>(() -> new AddImport<>("org.springframework.beans.factory.annotation.Autowired", null, false)), + new AutoFormat() + ); } class MigrateJndiLookupVisitor extends JavaIsoVisitor { @@ -140,8 +141,8 @@ private J.ClassDeclaration addInstanceAsAutowiredMember(J.ClassDeclaration class J.VariableDeclarations variable = matchFound.getMultiVariable(); JavaType.Class type = (JavaType.Class) variable.getTypeExpression().getType(); String variableName = variable.getVariables().get(0).getSimpleName(); - JavaTemplate javaTemplate = JavaTemplate.builder(() -> getCursor(), "@Autowired\nprivate " + type.getClassName() + " " + variableName).build(); - J.Block result = body.withTemplate(javaTemplate, body.getCoordinates().lastStatement()); + JavaTemplate javaTemplate = JavaTemplate.builder("@Autowired\nprivate " + type.getClassName() + " " + variableName).build(); + J.Block result = javaTemplate.apply(getCursor(), body.getCoordinates().lastStatement()); List statements1 = result.getStatements(); Statement statement = statements1.get(statements1.size() - 1); statements1.remove(statement); diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/MigrateJaxRsRecipe.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/MigrateJaxRsRecipe.java index 724ebbe17..f8177fc9c 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/MigrateJaxRsRecipe.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/MigrateJaxRsRecipe.java @@ -99,7 +99,7 @@ public Recipe jaxRs(RewriteRecipeLoader rewriteRecipeLoader) { JavaRecipeAction.builder() .condition(HasImportStartingWith.builder().value("javax.ws.rs.core.MediaType").build()) .description("Replace JaxRs MediaType with it's Spring equivalent.") - .recipe(new ReplaceMediaType(javaParserSupplier)) + .recipe(new ReplaceMediaType()) .build(), JavaRecipeAction.builder() @@ -123,7 +123,7 @@ public Recipe jaxRs(RewriteRecipeLoader rewriteRecipeLoader) { JavaRecipeAction.builder() .condition(HasImportStartingWith.builder().value("javax.ws.rs.core.Response").build()) .description("Replace JaxRs Response and ResponseBuilder with it's Spring equivalent.") - .recipe(new SwapResponseWithResponseEntity(javaParserSupplier)) + .recipe(new SwapResponseWithResponseEntity()) .build(), JavaRecipeAction.builder() diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/CopyAnnotationAttribute.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/CopyAnnotationAttribute.java index 06dae3513..3d8226bad 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/CopyAnnotationAttribute.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/CopyAnnotationAttribute.java @@ -52,9 +52,10 @@ public class CopyAnnotationAttribute extends Recipe { example = "timeout") String targetAttributeName; - @Override - protected TreeVisitor getSingleSourceApplicableTest() { - return new UsesType<>(sourceAnnotationType); + // FIXME: removed with 8.x +// @Override + public TreeVisitor getSingleSourceApplicableTest() { + return new UsesType<>(sourceAnnotationType, null); } @Override @@ -68,7 +69,7 @@ protected TreeVisitor getSingleSourceApplicableTest() { } @Override - protected @NotNull JavaIsoVisitor getVisitor() { + public @NotNull JavaIsoVisitor getVisitor() { return new CopyAnnotationAttributeVisitor( sourceAnnotationType, sourceAttributeName, diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/RemoveAnnotationIfAccompanied.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/RemoveAnnotationIfAccompanied.java index 0ec2b9586..935901d1b 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/RemoveAnnotationIfAccompanied.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/RemoveAnnotationIfAccompanied.java @@ -51,9 +51,10 @@ public class RemoveAnnotationIfAccompanied extends Recipe { return "Remove matching annotation if the other annotation is also present."; } - @Override + // FIXME: removed with 8.x +// @Override protected TreeVisitor getSingleSourceApplicableTest() { - return new UsesType<>(annotationTypeToRemove); + return new UsesType<>(annotationTypeToRemove, null); } @Override diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceMediaType.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceMediaType.java index 410ee56d1..379d39e64 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceMediaType.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceMediaType.java @@ -27,6 +27,7 @@ import org.springframework.sbm.java.migration.recipes.RewriteMethodInvocation; import org.springframework.sbm.java.migration.recipes.openrewrite.ReplaceConstantWithAnotherConstant; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -36,7 +37,9 @@ public class ReplaceMediaType extends Recipe { - public ReplaceMediaType(Supplier javaParserSupplier) { + private final List recipes; + + public ReplaceMediaType() { // Constants Map mappings = new HashMap<>(); @@ -82,90 +85,97 @@ public ReplaceMediaType(Supplier javaParserSupplier) { mappings.put("WILDCARD", "ALL_VALUE"); mappings.put("WILDCARD_TYPE", "ALL"); + recipes = new ArrayList<>(); mappings.forEach( - (key, value) -> doNext(new ReplaceConstantWithAnotherConstant("javax.ws.rs.core.MediaType." + key,"org.springframework.http.MediaType." + value)) + (key, value) -> recipes.add(new ReplaceConstantWithAnotherConstant("javax.ws.rs.core.MediaType." + key, "org.springframework.http.MediaType." + value)) ); + } - doNext(new ReplaceConstantWithAnotherConstant("javax.ws.rs.core.MediaType.CHARSET_PARAMETER","org.springframework.util.MimeType.PARAM_CHARSET")); - doNext(new ReplaceConstantWithAnotherConstant("javax.ws.rs.core.MediaType.MEDIA_TYPE_WILDCARD","org.springframework.util.MimeType.WILDCARD_TYPE")); - - // instance methods - // #isCompatible(MediaType) - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.MediaType isCompatible(javax.ws.rs.core.MediaType)"), (v, m, addImport) -> { - JavaType type = JavaType.buildType("org.springframework.http.MediaType"); - - J.Identifier newMethodName = m.getName().withSimpleName("isCompatibleWith"); - Expression newSelect = m.getSelect().withType(type); - JavaType.Method newMethodType = m.getMethodType().withReturnType(type).withDeclaringType(TypeUtils.asFullyQualified(type)); - List newMethodArguments = List.of(m.getArguments().get(0).withType(type)); - - return m - .withName(newMethodName) - .withSelect(newSelect) - .withMethodType(newMethodType) - .withArguments(newMethodArguments); - })); - - // #withCharset(String) - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.MediaType withCharset(java.lang.String)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "new MediaType(#{any(org.springframework.http.MediaType)}, Charset.forName(#{any(java.lang.String)}))") - .imports("org.springframework.http.MediaType", "java.nio.charset.Charset") - .build(); - addImport.accept("java.nio.charset.Charset"); - addImport.accept("org.springframework.http.MediaType"); - - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); - })); - - // #getParameters() - comes with org.springframework.util.MimeType#getParameters() - // #getSubtype() - comes with org.springframework.util.MimeType#getSubtype() - // #getType() - comes with org.springframework.util.MimeType#getType() - // #isWildcardSubtype() - comes with org.springframework.util.MimeType#isWildcardSubtype() - // #isWildcardType() - comes with org.springframework.util.MimeType#isWildcardType() - - // static methods - - // #valueOf(String) present on Spring MediaType - - // constructors - - // MediaType() -> new MediaType(MimeType.WILDCARD_TYPE, MimeType.WILDCARD_TYPE) - doNext(new RewriteConstructorInvocation(constructorMatcher("javax.ws.rs.core.MediaType"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "new MediaType(MimeType.WILDCARD_TYPE, MimeType.WILDCARD_TYPE)") - .imports("org.springframework.http.MediaType", "org.springframework.util.MimeType") - .build(); - addImport.accept("org.springframework.util.MimeType"); - addImport.accept("org.springframework.http.MediaType"); - - return m.withTemplate(template, m.getCoordinates().replace()); - })); - - // MediaType(String, String) - present on Spring MediaType - doNext(new RewriteConstructorInvocation(constructorMatcher("javax.ws.rs.core.MediaType", "java.lang.String", "java.lang.String"), (v, m, addImport) -> { - JavaType type = JavaType.buildType("org.springframework.http.MediaType"); - return m.withConstructorType(m.getConstructorType().withDeclaringType(TypeUtils.asFullyQualified(type))); - })); - - // MediaType(String, String, String) -> MediaType(String, String, Charset) - doNext(new RewriteConstructorInvocation(constructorMatcher("javax.ws.rs.core.MediaType", "java.lang.String", "java.lang.String", "java.lang.String"), (v, m, addImport) -> { - List arguments = m.getArguments(); - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "new MediaType(#{any(java.lang.String)}, #{any(java.lang.String)}, Charset.forName(#{any(java.lang.String)}))") - .imports("org.springframework.http.MediaType", "java.nio.charset.Charset") - .build(); - addImport.accept("java.nio.charset.Charset"); - addImport.accept("org.springframework.http.MediaType"); - - return m.withTemplate(template, m.getCoordinates().replace(), arguments.get(0), arguments.get(1), arguments.get(2)); - })); - - // MediaType(String, String, Map) - present on Spring MediaType - doNext(new RewriteConstructorInvocation(constructorMatcher("javax.ws.rs.core.MediaType", "java.lang.String", "java.lang.String", "java.util.Map"), (v, m, addImport) -> { - JavaType type = JavaType.buildType("org.springframework.http.MediaType"); - return m.withConstructorType(m.getConstructorType().withDeclaringType(TypeUtils.asFullyQualified(type))); - })); - - // Type references - doNext(new ChangeType("javax.ws.rs.core.MediaType", "org.springframework.http.MediaType", false)); + @Override + public List getRecipeList() { + return List.of( + + new ReplaceConstantWithAnotherConstant("javax.ws.rs.core.MediaType.CHARSET_PARAMETER", "org.springframework.util.MimeType.PARAM_CHARSET"), + new ReplaceConstantWithAnotherConstant("javax.ws.rs.core.MediaType.MEDIA_TYPE_WILDCARD", "org.springframework.util.MimeType.WILDCARD_TYPE"), + + // instance methods + // #isCompatible(MediaType) + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.MediaType isCompatible(javax.ws.rs.core.MediaType)"), (v, m, addImport) -> { + JavaType type = JavaType.buildType("org.springframework.http.MediaType"); + + J.Identifier newMethodName = m.getName().withSimpleName("isCompatibleWith"); + Expression newSelect = m.getSelect().withType(type); + JavaType.Method newMethodType = m.getMethodType().withReturnType(type).withDeclaringType(TypeUtils.asFullyQualified(type)); + List newMethodArguments = List.of(m.getArguments().get(0).withType(type)); + + return m + .withName(newMethodName) + .withSelect(newSelect) + .withMethodType(newMethodType) + .withArguments(newMethodArguments); + }), + + // #withCharset(String) + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.MediaType withCharset(java.lang.String)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("new MediaType(#{any(org.springframework.http.MediaType)}, Charset.forName(#{any(java.lang.String)}))") + .imports("org.springframework.http.MediaType", "java.nio.charset.Charset") + .build(); + addImport.accept("java.nio.charset.Charset"); + addImport.accept("org.springframework.http.MediaType"); + + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + }), + + // #getParameters() - comes with org.springframework.util.MimeType#getParameters() + // #getSubtype() - comes with org.springframework.util.MimeType#getSubtype() + // #getType() - comes with org.springframework.util.MimeType#getType() + // #isWildcardSubtype() - comes with org.springframework.util.MimeType#isWildcardSubtype() + // #isWildcardType() - comes with org.springframework.util.MimeType#isWildcardType() + + // static methods + + // #valueOf(String) present on Spring MediaType + + // constructors + + // MediaType() -> new MediaType(MimeType.WILDCARD_TYPE, MimeType.WILDCARD_TYPE) + new RewriteConstructorInvocation(constructorMatcher("javax.ws.rs.core.MediaType"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("new MediaType(MimeType.WILDCARD_TYPE, MimeType.WILDCARD_TYPE)") + .imports("org.springframework.http.MediaType", "org.springframework.util.MimeType") + .build(); + addImport.accept("org.springframework.util.MimeType"); + addImport.accept("org.springframework.http.MediaType"); + + return template.apply(v.getCursor(), m.getCoordinates().replace()); + }), + + // MediaType(String, String) - present on Spring MediaType + new RewriteConstructorInvocation(constructorMatcher("javax.ws.rs.core.MediaType", "java.lang.String", "java.lang.String"), (v, m, addImport) -> { + JavaType type = JavaType.buildType("org.springframework.http.MediaType"); + return m.withConstructorType(m.getConstructorType().withDeclaringType(TypeUtils.asFullyQualified(type))); + }), + + // MediaType(String, String, String) -> MediaType(String, String, Charset) + new RewriteConstructorInvocation(constructorMatcher("javax.ws.rs.core.MediaType", "java.lang.String", "java.lang.String", "java.lang.String"), (v, m, addImport) -> { + List arguments = m.getArguments(); + JavaTemplate template = JavaTemplate.builder("new MediaType(#{any(java.lang.String)}, #{any(java.lang.String)}, Charset.forName(#{any(java.lang.String)}))") + .imports("org.springframework.http.MediaType", "java.nio.charset.Charset") + .build(); + addImport.accept("java.nio.charset.Charset"); + addImport.accept("org.springframework.http.MediaType"); + + return template.apply(v.getCursor(), m.getCoordinates().replace(), arguments.get(0), arguments.get(1), arguments.get(2)); + }), + + // MediaType(String, String, Map) - present on Spring MediaType + new RewriteConstructorInvocation(constructorMatcher("javax.ws.rs.core.MediaType", "java.lang.String", "java.lang.String", "java.util.Map"), (v, m, addImport) -> { + JavaType type = JavaType.buildType("org.springframework.http.MediaType"); + return m.withConstructorType(m.getConstructorType().withDeclaringType(TypeUtils.asFullyQualified(type))); + }), + + // Type references + new ChangeType("javax.ws.rs.core.MediaType", "org.springframework.http.MediaType", false) + ); } @Override @@ -173,4 +183,9 @@ public String getDisplayName() { return "Replace JAX-RS MediaType with Spring MediaType"; } + @Override + public String getDescription() { + return getDisplayName(); + } + } diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceRequestParameterProperties.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceRequestParameterProperties.java index 4441adb67..d58e44696 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceRequestParameterProperties.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceRequestParameterProperties.java @@ -18,21 +18,30 @@ import org.jetbrains.annotations.NotNull; import org.openrewrite.Recipe; +import java.util.List; + /** * @author Vincent Botteman */ public class ReplaceRequestParameterProperties extends Recipe { public ReplaceRequestParameterProperties() { - doNext(new CopyAnnotationAttribute( - "javax.ws.rs.DefaultValue", "value", "org.springframework.web.bind.annotation.RequestParam", "defaultValue") + } + + @Override + public List getRecipeList() { + return List.of( + new CopyAnnotationAttribute("javax.ws.rs.DefaultValue", "value", "org.springframework.web.bind.annotation.RequestParam", "defaultValue"), + new RemoveAnnotationIfAccompanied("javax.ws.rs.DefaultValue", "org.springframework.web.bind.annotation.RequestParam") ); - doNext(new RemoveAnnotationIfAccompanied( - "javax.ws.rs.DefaultValue", "org.springframework.web.bind.annotation.RequestParam" - )); } @Override public @NotNull String getDisplayName() { return "Migrate the properties of a request parameter: default value, ..."; } + + @Override + public String getDescription() { + return getDisplayName(); + } } \ No newline at end of file diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceResponseEntityBuilder.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceResponseEntityBuilder.java index 1a04aec6a..c81de5a27 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceResponseEntityBuilder.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/ReplaceResponseEntityBuilder.java @@ -42,13 +42,13 @@ public ReplaceResponseEntityBuilder() { RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder allow(java.lang.String...)"), (v, m, addImport) -> { String transformedArgs = m.getArguments().stream().map(arg -> "HttpMethod.resolve(#{any()})").collect(Collectors.joining(", ")); - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.allow(" + transformedArgs + ")").imports("org.springframework.http.HttpMethod", "org.springframework.http.ResponseEntity.HeadersBuilder").build(); + JavaTemplate t = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.allow(" + transformedArgs + ")").imports("org.springframework.http.HttpMethod", "org.springframework.http.ResponseEntity.HeadersBuilder").build(); // v.maybeAddImport("org.springframework.http.HttpMethod"); addImport.accept("org.springframework.http.HttpMethod"); List parameters = new ArrayList(); parameters.add(m.getSelect()); parameters.addAll(m.getArguments()); - return m.withTemplate(t, m.getCoordinates().replace(), parameters.toArray()); + return t.apply(v.getCursor(), m.getCoordinates().replace(), parameters.toArray()); } ) ); @@ -57,14 +57,13 @@ public ReplaceResponseEntityBuilder() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder allow(java.util.Set)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder( - () -> v.getCursor(), - "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.allow(#{any()}.stream().map(HttpMethod::resolve).toArray(String[]::new))").imports("org.springframework.http.HttpMethod", "org.springframework.http.ResponseEntity.HeadersBuilder" - ) + JavaTemplate t = JavaTemplate + .builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.allow(#{any()}.stream().map(HttpMethod::resolve).toArray(String[]::new))") + .imports("org.springframework.http.HttpMethod", "org.springframework.http.ResponseEntity.HeadersBuilder") .build(); -// v.maybeAddImport("org.springframework.http.HttpMethod"); + addImport.accept("org.springframework.http.HttpMethod"); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -75,14 +74,12 @@ public ReplaceResponseEntityBuilder() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder encoding(java.lang.String)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder( - () -> v.getCursor(), - "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.header(HttpHeaders.CONTENT_ENCODING, #{any()})" - ) + JavaTemplate t = JavaTemplate + .builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.header(HttpHeaders.CONTENT_ENCODING, #{any()})") .imports("org.springframework.http.HttpHeaders", "org.springframework.http.ResponseEntity.HeadersBuilder") .build(); addImport.accept("org.springframework.http.HttpHeaders"); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments()); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments()); } ) ); @@ -99,7 +96,8 @@ public ReplaceResponseEntityBuilder() { RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder entity(java.lang.Object, ..)"), (v, m, addImport) -> { VisitorUtils.markWrappingInvocationWithTemplate(v, m, new MethodMatcher("javax.ws.rs.core.Response.ResponseBuilder build()"), m.getArguments().get(0).print(), this); - return m.withTemplate(JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}").build(), m.getCoordinates().replace(), m.getSelect()); + JavaTemplate javaTemplate = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}").build(); + return javaTemplate.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); } ) ); @@ -108,9 +106,10 @@ public ReplaceResponseEntityBuilder() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder expires(java.util.Date)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> h.setExpires(#{any()}.toInstant()))") + JavaTemplate t = JavaTemplate + .builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> h.setExpires(#{any()}.toInstant()))") .build(); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -119,11 +118,11 @@ public ReplaceResponseEntityBuilder() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder language(java.lang.String)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> h.set(HttpHeaders.CONTENT_LANGUAGE, #{any()}))") + JavaTemplate t = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> h.set(HttpHeaders.CONTENT_LANGUAGE, #{any()}))") .imports("org.springframework.http.HttpHeaders") .build(); addImport.accept("org.springframework.http.HttpHeaders"); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -132,9 +131,9 @@ public ReplaceResponseEntityBuilder() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder language(java.util.Locale)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> h.setContentLanguage(#{any()}))") + JavaTemplate t = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> h.setContentLanguage(#{any()}))") .build(); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -143,9 +142,9 @@ public ReplaceResponseEntityBuilder() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder lastModified(java.util.Date)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.lastModified(#{any()}.toInstant())") + JavaTemplate t = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.lastModified(#{any()}.toInstant())") .build(); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -156,13 +155,15 @@ public ReplaceResponseEntityBuilder() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder replaceAll(javax.ws.rs.core.MultivaluedMap)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> {\n" - + "h.clear();\n" - + "h.addAll(#{any()});\n" - + "})") + JavaTemplate t = JavaTemplate.builder(""" + #{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> { + h.clear(); + h.addAll(#{any()}); + }) + """) .imports("org.springframework.util.MultiValueMap", "org.springframework.http.ResponseEntity.HeadersBuilder") .build(); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -171,10 +172,10 @@ public ReplaceResponseEntityBuilder() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.ResponseBuilder type(java.lang.String)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> h.set(HttpHeaders.CONTENT_TYPE, #{any()}))") + JavaTemplate t = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.headers(h -> h.set(HttpHeaders.CONTENT_TYPE, #{any()}))") .imports("org.springframework.http.HttpHeaders", "org.springframework.http.ResponseEntity.HeadersBuilder") .build(); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -190,8 +191,8 @@ public ReplaceResponseEntityBuilder() { MarkWithTemplate marker = m.getMarkers().findFirst(MarkWithTemplate.class).orElse(null); if (marker != null) { m = VisitorUtils.removeMarker(m, marker); - Builder t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.body(#{})"); - m = m.withTemplate(t.build(), m.getCoordinates().replace(), m.getSelect(), marker.getTemplate()); + JavaTemplate t = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.body(#{})").build(); + m = t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), marker.getTemplate()); } return m.withMarkers(m.getMarkers().computeByType(new MarkReturnType(Tree.randomId(), this, "ResponseEntity", "org.springframework.http.ResponseEntity"), (o1, o2) -> o2)); } @@ -222,9 +223,8 @@ public ReplaceResponseEntityBuilder() { (v, m, addImport) -> { MarkWithTemplate marker = m.getMarkers().findFirst(MarkWithTemplate.class).orElse(null); m = VisitorUtils.removeMarker(m, marker); - return m - .withTemplate( - JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.body(#{}").build(), + JavaTemplate javaTemplate = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity.HeadersBuilder)}.body(#{}").build(); + return javaTemplate.apply(v.getCursor(), m.getCoordinates().replace(), m, marker.getTemplate()) @@ -240,9 +240,18 @@ public ReplaceResponseEntityBuilder() { } + private void doNext(Recipe recipe) { + getRecipeList().add(recipe); + } + @Override public String getDisplayName() { return "Replace references to JAX-RS ReplaceResponseEntityBuilder"; } + @Override + public String getDescription() { + return getDisplayName(); + } + } diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapCacheControl.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapCacheControl.java index e4eb8116e..1f92cff6c 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapCacheControl.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapCacheControl.java @@ -21,53 +21,62 @@ import org.springframework.sbm.java.migration.recipes.RewriteConstructorInvocation; import org.springframework.sbm.java.migration.recipes.RewriteMethodInvocation; +import java.util.List; + public class SwapCacheControl extends Recipe { public SwapCacheControl() { - /* - * NOT SUPPORTED: - * - valueOf(String) - * - getCacheExtension() - * - getMaxAge() - * - getNoCacheFields() - * - getPrivateFields() - * - getSMaxAge() - * - isMustRevalidate() - * - isNoCache() - * - isNoStore() - * - isNoTransform() - * - isPrivate() - * - isProxyRevalidate() - * - setMaxAge(int) - * - setMustRevalidate(boolean) - * - setNoCache(boolean) - * - setNoStore(boolean) - * - setNoTransform(boolean) - * - setPrivate(boolean) - * - setProxyRevalidate(boolean) - */ + } + + @Override + public List getRecipeList() { + return List.of( + + /* + * NOT SUPPORTED: + * - valueOf(String) + * - getCacheExtension() + * - getMaxAge() + * - getNoCacheFields() + * - getPrivateFields() + * - getSMaxAge() + * - isMustRevalidate() + * - isNoCache() + * - isNoStore() + * - isNoTransform() + * - isPrivate() + * - isProxyRevalidate() + * - setMaxAge(int) + * - setMustRevalidate(boolean) + * - setNoCache(boolean) + * - setNoStore(boolean) + * - setNoTransform(boolean) + * - setPrivate(boolean) + * - setProxyRevalidate(boolean) + */ - // setSMaxAge(int) - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.CacheControl setSMaxAge(int)"), (v, m, addImport) -> { - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.CacheControl)}.sMaxAge(#{any(int)}, TimeUnit.SECONDS)") - .imports("java.util.concurrent.TimeUnit", "org.springframework.http.CacheControl") - .build(); - addImport.accept("java.util.concurrent.TimeUnit"); - return m.withTemplate(t, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); - })); + // setSMaxAge(int) + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.CacheControl setSMaxAge(int)"), (v, m, addImport) -> { + JavaTemplate t = JavaTemplate.builder("#{any(org.springframework.http.CacheControl)}.sMaxAge(#{any(int)}, TimeUnit.SECONDS)") + .imports("java.util.concurrent.TimeUnit", "org.springframework.http.CacheControl") + .build(); + addImport.accept("java.util.concurrent.TimeUnit"); + return t.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + }), - // constructor - doNext(new RewriteConstructorInvocation(RewriteConstructorInvocation.constructorMatcher("javax.ws.rs.core.CacheControl"), (v, c, addImport) -> { - JavaTemplate t = JavaTemplate.builder(() -> v.getCursor(), "CacheControl.empty()") - .imports("org.springframework.http.CacheControl") - .build(); - addImport.accept("org.springframework.http.CacheControl"); - v.maybeRemoveImport("javax.ws.rs.core.CacheControl"); - return c.withTemplate(t, c.getCoordinates().replace()); - })); + // constructor + new RewriteConstructorInvocation(RewriteConstructorInvocation.constructorMatcher("javax.ws.rs.core.CacheControl"), (v, c, addImport) -> { + JavaTemplate t = JavaTemplate.builder("CacheControl.empty()") + .imports("org.springframework.http.CacheControl") + .build(); + addImport.accept("org.springframework.http.CacheControl"); + v.maybeRemoveImport("javax.ws.rs.core.CacheControl"); + return t.apply(v.getCursor(), c.getCoordinates().replace()); + }), - doNext(new ChangeType("javax.ws.rs.core.CacheControl", "org.springframework.http.CacheControl", false)); + new ChangeType("javax.ws.rs.core.CacheControl", "org.springframework.http.CacheControl", false) + ); } @Override @@ -75,4 +84,9 @@ public String getDisplayName() { return "Swap JAX-RS CacheControl with Spring CacheControl"; } + @Override + public String getDescription() { + return getDisplayName(); + } + } diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapFamilyForSeries.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapFamilyForSeries.java index fab2b8309..da2be9c03 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapFamilyForSeries.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapFamilyForSeries.java @@ -41,10 +41,10 @@ public SwapFamilyForSeries() { doNext(new RewriteMethodInvocation( RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response.Status.Family familyOf(int)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "HttpStatus.Series.resolve(#{any(int)})").build(); + JavaTemplate template = JavaTemplate.builder("HttpStatus.Series.resolve(#{any(int)})").build(); v.maybeAddImport("org.springframework.http.HttpStatus.Series"); addImport.accept("org.springframework.http.HttpStatus"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().get(0)); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().get(0)); } ) ); @@ -53,9 +53,18 @@ public SwapFamilyForSeries() { } + private void doNext(Recipe recipe) { + getRecipeList().add(recipe); + } + @Override public String getDisplayName() { return "Swap JAX-RS Family with Spring HttpStatus.Series"; } + @Override + public String getDescription() { + return getDisplayName(); + } + } diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapHttHeaders.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapHttHeaders.java index 9e0f2b94b..6b2d7d7df 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapHttHeaders.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapHttHeaders.java @@ -56,11 +56,11 @@ public SwapHttHeaders() { doNext(new RewriteMethodInvocation( methodInvocationMatcher("javax.ws.rs.core.HttpHeaders getDate()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "new Date()") + JavaTemplate template = JavaTemplate.builder("new Date()") .imports("java.util.Date") .build(); addImport.accept("java.util.Date"); - NewClass newMethod = (NewClass) m.withTemplate(template, m.getCoordinates().replace()); + NewClass newMethod = (NewClass) template.apply(v.getCursor(), m.getCoordinates().replace()); JavaType javaType = JavaType.buildType("org.springframework.http.HttpHeaders"); return newMethod.withArguments(List.of( m.withSelect(m.getSelect().withType(javaType)) @@ -75,9 +75,9 @@ public SwapHttHeaders() { doNext(new RewriteMethodInvocation( methodInvocationMatcher("javax.ws.rs.core.HttpHeaders getHeaderString(java.lang.String)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "String.join(\", \", #{any(org.springframework.http.HttpHeaders)}.get(#{any(java.lang.String)})") + JavaTemplate template = JavaTemplate.builder("String.join(\", \", #{any(org.springframework.http.HttpHeaders)}.get(#{any(java.lang.String)})") .build(); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -114,9 +114,9 @@ public SwapHttHeaders() { // #getRequestHeader(String) doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.HttpHeaders getRequestHeader(java.lang.String)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.HttpHeaders)}.get(#{any(java.lang.String)})") + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.HttpHeaders)}.get(#{any(java.lang.String)})") .build(); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); } ) ); @@ -125,7 +125,8 @@ public SwapHttHeaders() { doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.HttpHeaders getRequestHeaders()"), (v, m, addImport) -> { // Spring HttpHeaders is a MultiValueMap, hence just leave the expression and remove the call - return m.withTemplate(JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.HttpHeaders)}").build(), m.getCoordinates().replace(), m.getSelect()); + JavaTemplate javaTemplate = JavaTemplate.builder("#{any(org.springframework.http.HttpHeaders)}").build(); + return javaTemplate.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); } ) ); @@ -133,9 +134,19 @@ public SwapHttHeaders() { doNext(new ChangeType("javax.ws.rs.core.HttpHeaders", "org.springframework.http.HttpHeaders", false)); } + private void doNext(Recipe getAcceptLanguageAsLocales) { + // This might not work + getRecipeList().add(getAcceptLanguageAsLocales); + } + @Override public String getDisplayName() { return "Swap JAX-RS HttpHeaders with Spring HttpHeaders"; } + @Override + public String getDescription() { + return getDisplayName(); + } + } diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapResponseWithResponseEntity.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapResponseWithResponseEntity.java index 33ade0d0b..23a029719 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapResponseWithResponseEntity.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapResponseWithResponseEntity.java @@ -35,333 +35,339 @@ public class SwapResponseWithResponseEntity extends Recipe { - public SwapResponseWithResponseEntity(Supplier javaParserSupplier) { - - doNext(new SwapStatusForHttpStatus(javaParserSupplier)); - // #status(int) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response status(int)"), (v, m, addImport) -> { - String args = m.getArguments().stream().map(a -> "#{any()}").collect(Collectors.joining(", ")); - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(" + args + ")") - .imports("org.springframework.http.ResponseEntity") - .build(); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - addImport.accept("org.springframework.http.ResponseEntity"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().toArray()); - })); - - // #status(int, String) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response status(int, java.lang.String)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(#{any()})") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().get(0)).withMarkers(m.getMarkers().add(new CommentJavaSearchResult(Tree.randomId(), "SBM FIXME: Couldn't find exact replacement for status(int, java.lang.String) - dropped java.lang.String argument"))); - })); - - // #status(Status) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response status(javax.ws.rs.core.Response.Status)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(#{any()})") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().get(0)).withMarkers(m.getMarkers().add(new CommentJavaSearchResult(Tree.randomId(), "SBM FIXME: Couldn't find exact replacement for status(javax.ws.rs.core.Response.StatusType) - replaced with status(int)"))); - })); - - // #status(StatusType) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response status(javax.ws.rs.core.Response.StatusType)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(#{()})") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().get(0)).withMarkers(m.getMarkers().add(new CommentJavaSearchResult(Tree.randomId(), "SBM FIXME: Couldn't find exact replacement for status(javax.ws.rs.core.Response.StatusType) - replaced with status(int)"))); - })); - - // #ok() - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response ok()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.ok()") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace()); - })); - - // #ok(Object) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response ok(java.lang.Object)"), (v, m, addImport) -> { - List args = m.getArguments(); - if(J.Literal.class.isInstance(m.getArguments().get(0))) { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.ok()") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - m = m.withTemplate(template, m.getCoordinates().replace()); - markTopLevelInvocationWithTemplate(v, m, args.get(0).print()); - } - return m; - })); - - // #ok(Object, MediaType) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response ok(java.lang.Object, javax.ws.rs.core.MediaType)"), (v, m, addImport) -> { - List args = m.getArguments(); - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.ok().contentType(#{any()})") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - markTopLevelInvocationWithTemplate(v, m, args.get(0).print()); - return m.withTemplate(template, m.getCoordinates().replace(), args.get(1)); - })); - - // #ok(Object, String) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response ok(java.lang.Object, java.lang.String)"), (v, m, addImport) -> { - List args = m.getArguments(); - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.ok().contentType(MediaType.parseMediaType(#{any()}))") - .imports("org.springframework.http.ResponseEntity", "org.springframework.http.MediaType") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - addImport.accept("org.springframework.http.MediaType"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - markTopLevelInvocationWithTemplate(v, m, args.get(0).print()); - return m.withTemplate(template, m.getCoordinates().replace(), args.get(1)); - })); - - // #accepted() - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response accepted()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.accepted()") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace()); - })); - - // #accepted(Object) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response accepted(java.lang.Object)"), (v, m, addImport) -> { - List args = m.getArguments(); - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.accepted()") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - m = m.withTemplate(template, m.getCoordinates().replace()); - markTopLevelInvocationWithTemplate(v, m, args.get(0).print()); - return m; - })); - - // #created(URI) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response created(java.net.URI)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.created(#{any()})") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().get(0)); - })); - - // #fromResponse(Response) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response fromResponse(javax.ws.rs.core.Response)"), (v, m, addImport) -> { - Expression e = m.getArguments().get(0); - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(#{any()}.getStatusCode()).headers(#{any()}.getHeaders())") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - markTopLevelInvocationWithTemplate(v, m, e.print() + ".getBody()"); - return m.withTemplate(template, m.getCoordinates().replace(), e, e); - })); - - // #noContent() - // TODO: returns HeadersBuilder - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response noContent()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.noContent()") - .imports("org.springframework.http.ResponseEntity") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace()); - })); - - // #notAcceptable(List { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(HttpStatus.NOT_MODIFIED)") - .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace()); - })); - - // notModified(String) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response notModified(java.lang.String)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(HttpStatus.NOT_MODIFIED).eTag(#{any()})") - .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - addImport.accept("org.springframework.http.HttpStatus"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().get(0)); - })); - - // notModified(EntityTag) - migration not supported - - // #seeOther(URI) - // TODO: Returns BodyBuilder - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response seeOther(java.net.URI)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(HttpStatus.SEE_OTHER).location(#{any()})") - .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - addImport.accept("org.springframework.http.HttpStatus"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().get(0)); - })); - - // #serverError() - // Returns BodyBuilder - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response serverError()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(HttpStatus.SERVER_ERROR)") - .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - addImport.accept("org.springframework.http.HttpStatus"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace()); - })); - - // #temporaryRedirect(URI) - // TODO: Returns BodyBuilder - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response temporaryRedirect(java.net.URI)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "ResponseEntity.status(HttpStatus.TEMPORARY_REDIRECT).location(#{any()})") - .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") - .build(); - addImport.accept("org.springframework.http.ResponseEntity"); - addImport.accept("org.springframework.http.HttpStatus"); - v.maybeRemoveImport("javax.ws.rs.core.Response"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getArguments().get(0)); - })); - - // INSTANCE METHODS - - // #getAllowedMethods() - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getAllowedMethods()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity)}.getHeaders().getAllow().stream().map(m -> m.toString()).collect(Collectors.toList())") - .imports("java.util.stream.Collectors", "org.springframework.http.ResponseEntity") - .build(); - addImport.accept("java.util.stream.Collectors"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getDate() - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getDate()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "new Date(#{any(org.springframework.http.ResponseEntity)}.getHeaders().getDate())") - .imports("java.util.Date", "org.springframework.http.ResponseEntity") - .build(); - addImport.accept("java.util.Date"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getEntity() - doNext(renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getEntity()"), "getBody", "org.springframework.http.ResponseEntity")); - - // #getEntityTag() - // TODO: return type not EntityTag but String after migration - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getEntityTag()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity)}.getHeaders().getETag()") - .build(); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getHeaderString(String) - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getHeaderString(java.lang.String)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity)}.getHeaders().get(#{any()}).stream().collect(Collectors.joining(\", \"))") - .imports("java.util.stream.Collectors") - .build(); - v.maybeAddImport("java.util.stream.Collectors"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); - })); - - // #getMetadata() - doNext(renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getMetadata()"), "getHeaders", "org.springframework.http.ResponseEntity")); - - // #getLanguage() - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getLanguage()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity)}.getHeaders().getContentLanguage()") - .build(); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getLastModified() - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getLastModified()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "new Date(#{any(org.springframework.http.ResponseEntity)}.getHeaders().getLastModified())") - .imports("java.util.Date") - .build(); - addImport.accept("java.util.Date"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getLength() - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getLength()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity)}.getHeaders().getContentLength()") - .build(); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getLocation() - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getLocation()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity)}.getHeaders().getLocation()") - .build(); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getMediaType() - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getMediaType()"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity)}.getHeaders().getContentType()") - .build(); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getStatus() - doNext(renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getStatus()"), "getStatusCodeValue", "org.springframework.http.ResponseEntity")); - - // #getStatusInfo() - doNext(renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getStatusInfo()"), "getStatusCode", "org.springframework.http.ResponseEntity")); - - // #getStringHeaders() - // TODO: different return type - doNext(renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getStringHeaders()"), "getHeaders", "org.springframework.http.ResponseEntity")); - - // #hasEntity() - doNext(renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response hasEntity()"), "hasBody", "org.springframework.http.ResponseEntity")); - - // #readEntity(..) - doNext(new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response readEntity(..)"), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.ResponseEntity)}.getBody())") - .build(); - v.maybeRemoveImport("java.lang.annotation.Annotation"); - v.maybeRemoveImport("javax.ws.rs.core.GenericType"); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); - - // #getHeaders() - present on ResponseEntity but different return type. Nothing can be done about it for now... - - // #getCookies() - not implemented - // #bufferEntity() - not implemented - // #close() - not implemented - // #getLink(String) - not implemented - // #getLinkBuilder(String) - not implemented - // #getLinks() - not implemented - // #hasLink() - not implemented - - - doNext(new ReplaceResponseEntityBuilder()); - - doNext(new ChangeType("javax.ws.rs.core.Response", "org.springframework.http.ResponseEntity", false)); + public SwapResponseWithResponseEntity() { + } + + @Override + public List getRecipeList() { + return List.of( + new SwapStatusForHttpStatus(), + // #status(int) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response status(int)"), (v, m, addImport) -> { + String args = m.getArguments().stream().map(a -> "#{any()}").collect(Collectors.joining(", ")); + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(" + args + ")") + .imports("org.springframework.http.ResponseEntity") + .build(); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + addImport.accept("org.springframework.http.ResponseEntity"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().toArray()); + }), + + + // #status(int, String) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response status(int, java.lang.String)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(#{any()})") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().get(0)).withMarkers(m.getMarkers().add(new CommentJavaSearchResult(Tree.randomId(), "SBM FIXME: Couldn't find exact replacement for status(int, java.lang.String) - dropped java.lang.String argument"))); + }), + + // #status(Status) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response status(javax.ws.rs.core.Response.Status)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(#{any()})") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().get(0)).withMarkers(m.getMarkers().add(new CommentJavaSearchResult(Tree.randomId(), "SBM FIXME: Couldn't find exact replacement for status(javax.ws.rs.core.Response.StatusType) - replaced with status(int)"))); + }), + + // #status(StatusType) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response status(javax.ws.rs.core.Response.StatusType)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(#{()})") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().get(0)).withMarkers(m.getMarkers().add(new CommentJavaSearchResult(Tree.randomId(), "SBM FIXME: Couldn't find exact replacement for status(javax.ws.rs.core.Response.StatusType) - replaced with status(int)"))); + }), + + // #ok() + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response ok()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.ok()") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace()); + }), + + // #ok(Object) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response ok(java.lang.Object)"), (v, m, addImport) -> { + List args = m.getArguments(); + if (J.Literal.class.isInstance(m.getArguments().get(0))) { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.ok()") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + m = template.apply(v.getCursor(), m.getCoordinates().replace()); + markTopLevelInvocationWithTemplate(v, m, args.get(0).print()); + } + return m; + }), + + // #ok(Object, MediaType) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response ok(java.lang.Object, javax.ws.rs.core.MediaType)"), (v, m, addImport) -> { + List args = m.getArguments(); + JavaTemplate template = JavaTemplate.builder("ResponseEntity.ok().contentType(#{any()})") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + markTopLevelInvocationWithTemplate(v, m, args.get(0).print()); + return template.apply(v.getCursor(), m.getCoordinates().replace(), args.get(1)); + }), + + // #ok(Object, String) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response ok(java.lang.Object, java.lang.String)"), (v, m, addImport) -> { + List args = m.getArguments(); + JavaTemplate template = JavaTemplate.builder("ResponseEntity.ok().contentType(MediaType.parseMediaType(#{any()}))") + .imports("org.springframework.http.ResponseEntity", "org.springframework.http.MediaType") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + addImport.accept("org.springframework.http.MediaType"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + markTopLevelInvocationWithTemplate(v, m, args.get(0).print()); + return template.apply(v.getCursor(), m.getCoordinates().replace(), args.get(1)); + }), + + // #accepted() + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response accepted()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.accepted()") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace()); + }), + + // #accepted(Object) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response accepted(java.lang.Object)"), (v, m, addImport) -> { + List args = m.getArguments(); + JavaTemplate template = JavaTemplate.builder("ResponseEntity.accepted()") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + m = template.apply(v.getCursor(), m.getCoordinates().replace()); + markTopLevelInvocationWithTemplate(v, m, args.get(0).print()); + return m; + }), + + // #created(URI) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response created(java.net.URI)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.created(#{any()})") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().get(0)); + }), + + // #fromResponse(Response) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response fromResponse(javax.ws.rs.core.Response)"), (v, m, addImport) -> { + Expression e = m.getArguments().get(0); + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(#{any()}.getStatusCode()).headers(#{any()}.getHeaders())") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + markTopLevelInvocationWithTemplate(v, m, e.print() + ".getBody()"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), e, e); + }), + + // #noContent() + // TODO: returns HeadersBuilder + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response noContent()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.noContent()") + .imports("org.springframework.http.ResponseEntity") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace()); + }), + + // #notAcceptable(List { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(HttpStatus.NOT_MODIFIED)") + .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace()); + }), + + // notModified(String) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response notModified(java.lang.String)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(HttpStatus.NOT_MODIFIED).eTag(#{any()})") + .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + addImport.accept("org.springframework.http.HttpStatus"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().get(0)); + }), + + // notModified(EntityTag) - migration not supported + + // #seeOther(URI) + // TODO: Returns BodyBuilder + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response seeOther(java.net.URI)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(HttpStatus.SEE_OTHER).location(#{any()})") + .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + addImport.accept("org.springframework.http.HttpStatus"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().get(0)); + }), + + // #serverError() + // Returns BodyBuilder + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response serverError()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(HttpStatus.SERVER_ERROR)") + .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + addImport.accept("org.springframework.http.HttpStatus"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace()); + }), + + // #temporaryRedirect(URI) + // TODO: Returns BodyBuilder + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response temporaryRedirect(java.net.URI)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("ResponseEntity.status(HttpStatus.TEMPORARY_REDIRECT).location(#{any()})") + .imports("org.springframework.http.ResponseEntity", "org.springframework.http.HttpStatus") + .build(); + addImport.accept("org.springframework.http.ResponseEntity"); + addImport.accept("org.springframework.http.HttpStatus"); + v.maybeRemoveImport("javax.ws.rs.core.Response"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getArguments().get(0)); + }), + + // INSTANCE METHODS + + // #getAllowedMethods() + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getAllowedMethods()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity)}.getHeaders().getAllow().stream().map(m -> m.toString()).collect(Collectors.toList())") + .imports("java.util.stream.Collectors", "org.springframework.http.ResponseEntity") + .build(); + addImport.accept("java.util.stream.Collectors"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getDate() + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getDate()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("new Date(#{any(org.springframework.http.ResponseEntity)}.getHeaders().getDate())") + .imports("java.util.Date", "org.springframework.http.ResponseEntity") + .build(); + addImport.accept("java.util.Date"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getEntity() + renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getEntity()"), "getBody", "org.springframework.http.ResponseEntity"), + + // #getEntityTag() + // TODO: return type not EntityTag but String after migration + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getEntityTag()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity)}.getHeaders().getETag()") + .build(); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getHeaderString(String) + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getHeaderString(java.lang.String)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity)}.getHeaders().get(#{any()}).stream().collect(Collectors.joining(\", \"))") + .imports("java.util.stream.Collectors") + .build(); + v.maybeAddImport("java.util.stream.Collectors"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)); + }), + + // #getMetadata() + renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getMetadata()"), "getHeaders", "org.springframework.http.ResponseEntity"), + + // #getLanguage() + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getLanguage()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity)}.getHeaders().getContentLanguage()") + .build(); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getLastModified() + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getLastModified()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("new Date(#{any(org.springframework.http.ResponseEntity)}.getHeaders().getLastModified())") + .imports("java.util.Date") + .build(); + addImport.accept("java.util.Date"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getLength() + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getLength()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity)}.getHeaders().getContentLength()") + .build(); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getLocation() + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getLocation()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity)}.getHeaders().getLocation()") + .build(); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getMediaType() + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response getMediaType()"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity)}.getHeaders().getContentType()") + .build(); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getStatus() + renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getStatus()"), "getStatusCodeValue", "org.springframework.http.ResponseEntity"), + + // #getStatusInfo() + renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getStatusInfo()"), "getStatusCode", "org.springframework.http.ResponseEntity"), + + // #getStringHeaders() + // TODO: different return type + renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response getStringHeaders()"), "getHeaders", "org.springframework.http.ResponseEntity"), + + // #hasEntity() + renameMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response hasEntity()"), "hasBody", "org.springframework.http.ResponseEntity"), + + // #readEntity(..) + new RewriteMethodInvocation(RewriteMethodInvocation.methodInvocationMatcher("javax.ws.rs.core.Response readEntity(..)"), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.ResponseEntity)}.getBody())") + .build(); + v.maybeRemoveImport("java.lang.annotation.Annotation"); + v.maybeRemoveImport("javax.ws.rs.core.GenericType"); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), + + // #getHeaders() - present on ResponseEntity but different return type. Nothing can be done about it for now... + + // #getCookies() - not implemented + // #bufferEntity() - not implemented + // #close() - not implemented + // #getLink(String) - not implemented + // #getLinkBuilder(String) - not implemented + // #getLinks() - not implemented + // #hasLink() - not implemented + + + new ReplaceResponseEntityBuilder(), + + new ChangeType("javax.ws.rs.core.Response", "org.springframework.http.ResponseEntity", false) + ); } private void markTopLevelInvocationWithTemplate(JavaVisitor v, MethodInvocation m, String template) { @@ -373,4 +379,9 @@ public String getDisplayName() { return "Replace JAX-RS Response with Spring ResponseEntity"; } + @Override + public String getDescription() { + return getDisplayName(); + } + } diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapStatusForHttpStatus.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapStatusForHttpStatus.java index 3de007445..4b03a2a42 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapStatusForHttpStatus.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/SwapStatusForHttpStatus.java @@ -23,6 +23,7 @@ import org.springframework.sbm.java.migration.recipes.openrewrite.ReplaceConstantWithAnotherConstant; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.function.Supplier; @@ -30,11 +31,10 @@ public class SwapStatusForHttpStatus extends Recipe { - public SwapStatusForHttpStatus(Supplier javaParserSupplier) { - // Switch JAX-RS Family to Spring HttpStatus.Series - doNext(new SwapFamilyForSeries()); + private final Map fieldsMapping; - Map fieldsMapping = new HashMap<>(); + public SwapStatusForHttpStatus() { + fieldsMapping = new HashMap<>(); fieldsMapping.put("OK", "OK"); fieldsMapping.put("ACCEPTED", "ACCEPTED"); fieldsMapping.put("BAD_GATEWAY", "BAD_GATEWAY"); @@ -79,34 +79,42 @@ public SwapStatusForHttpStatus(Supplier javaParserSupplier) { fieldsMapping.put("UNSUPPORTED_MEDIA_TYPE", "UNSUPPORTED_MEDIA_TYPE"); fieldsMapping.put("USE_PROXY", "USE_PROXY"); - fieldsMapping.forEach( - (key, value) -> doNext(new ReplaceConstantWithAnotherConstant("javax.ws.rs.core.Response$Status." + key,"org.springframework.http.HttpStatus." + value)) - ); + fieldsMapping.forEach((key, value) -> new ReplaceConstantWithAnotherConstant("javax.ws.rs.core.Response$Status." + key, "org.springframework.http.HttpStatus." + value)); + } + + @Override + public List getRecipeList() { + + return List.of( + // Switch JAX-RS Family to Spring HttpStatus.Series + new SwapFamilyForSeries(), - // Instance methods - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response.StatusType getStatusCode()") - .or(methodInvocationMatcher("javax.ws.rs.core.Response.Status getStatusCode()")), - (v, m, addImport) -> { - return m.withName(m.getName().withSimpleName("getValue")); - })); - // Remove #toEnum() method calls - these shouldn't appear as we migrate both Jax-Rs Status and StatusType to the same HttpStatus - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response.StatusType toEnum()").or(methodInvocationMatcher("javax.ws.rs.core.Response.Status toEnum()")), (v, m, addImport) -> { - JavaTemplate template = JavaTemplate.builder(() -> v.getCursor(), "#{any(org.springframework.http.HttpStatus)}").build(); - return m.withTemplate(template, m.getCoordinates().replace(), m.getSelect()); - })); + // Instance methods + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response.StatusType getStatusCode()") + .or(methodInvocationMatcher("javax.ws.rs.core.Response.Status getStatusCode()")), + (v, m, addImport) -> { + return m.withName(m.getName().withSimpleName("getValue")); + }), - // Switch Family to Series - doNext(new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response.StatusType getFamily()").or(methodInvocationMatcher("javax.ws.rs.core.Response.Status getFamily()")), (v, m, addImport) -> { - return m.withName(m.getName().withSimpleName("series")); - })); + // Remove #toEnum() method calls - these shouldn't appear as we migrate both Jax-Rs Status and StatusType to the same HttpStatus + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response.StatusType toEnum()").or(methodInvocationMatcher("javax.ws.rs.core.Response.Status toEnum()")), (v, m, addImport) -> { + JavaTemplate template = JavaTemplate.builder("#{any(org.springframework.http.HttpStatus)}").build(); + return template.apply(v.getCursor(), m.getCoordinates().replace(), m.getSelect()); + }), - // getReasonPhrase() doesn't need to be migrated - same named method returning the same type + // Switch Family to Series + new RewriteMethodInvocation(methodInvocationMatcher("javax.ws.rs.core.Response.StatusType getFamily()").or(methodInvocationMatcher("javax.ws.rs.core.Response.Status getFamily()")), (v, m, addImport) -> { + return m.withName(m.getName().withSimpleName("series")); + }), - // Type reference replacement + // getReasonPhrase() doesn't need to be migrated - same named method returning the same type - doNext(new ChangeType("javax.ws.rs.core.Response$StatusType", "org.springframework.http.HttpStatus", false)); - doNext(new ChangeType("javax.ws.rs.core.Response$Status", "org.springframework.http.HttpStatus", false)); + // Type reference replacement + + new ChangeType("javax.ws.rs.core.Response$StatusType", "org.springframework.http.HttpStatus", false), + new ChangeType("javax.ws.rs.core.Response$Status", "org.springframework.http.HttpStatus", false) + ); } @Override @@ -114,4 +122,9 @@ public String getDisplayName() { return "Swap Jax-RS Status with Spring HttpStatus"; } + @Override + public String getDescription() { + return getDisplayName(); + } + } diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/visitors/CopyAnnotationAttributeVisitor.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/visitors/CopyAnnotationAttributeVisitor.java index c171cbacd..050d1e502 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/visitors/CopyAnnotationAttributeVisitor.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxrs/recipes/visitors/CopyAnnotationAttributeVisitor.java @@ -20,6 +20,7 @@ import org.jetbrains.annotations.NotNull; import org.openrewrite.Cursor; import org.openrewrite.ExecutionContext; +import org.openrewrite.TreeVisitor; import org.openrewrite.java.AddOrUpdateAnnotationAttribute; import org.openrewrite.java.JavaIsoVisitor; import org.openrewrite.java.tree.J; @@ -62,7 +63,7 @@ public J.Annotation visitAnnotation(@NotNull J.Annotation annotation, @NotNull E if (sourceAnnotationAttributeValue.getValue() != null) { // If the annotation type is a shallow class then JavaType.getMethods is empty and AddOrUpdateAnnotationAttribute can't determine if the datatype of the attribute is String or not String targetAttributeValue = annotation.getType() instanceof JavaType.ShallowClass ? sourceAnnotationAttributeValue.getValueSource() : sourceAnnotationAttributeValue.getValue().toString(); - JavaIsoVisitor addOrUpdateAnnotationAttributeVisitor = new AddOrUpdateAnnotationAttribute(targetAnnotationType, targetAttributeName, targetAttributeValue, false) + TreeVisitor addOrUpdateAnnotationAttributeVisitor = new AddOrUpdateAnnotationAttribute(targetAnnotationType, targetAttributeName, targetAttributeValue, false) .getVisitor(); if (targetAnnotationOnlyHasOneLiteralArgument(a)) { a = (J.Annotation) addOrUpdateAnnotationAttributeVisitor.visit(a, ctx, getCursor()); diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxws/GenerateWebServices.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxws/GenerateWebServices.java index 5c01f85bb..b3800fd8b 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxws/GenerateWebServices.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxws/GenerateWebServices.java @@ -222,7 +222,10 @@ public boolean accept(Path path) { } catch (IOException e) { return new ByteArrayInputStream(new byte[0]); } - })), null, executionContext); + })), null, executionContext) + .map(Xml.Document.class::cast) + .toList(); + if (docs.isEmpty()) { throw new RuntimeException("Failed to parse XML file '" + p + "'"); } else { diff --git a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxws/WebServiceDescriptor.java b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxws/WebServiceDescriptor.java index f238063c4..8d98bbfab 100644 --- a/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxws/WebServiceDescriptor.java +++ b/components/sbm-recipes-jee-to-boot/src/main/java/org/springframework/sbm/jee/jaxws/WebServiceDescriptor.java @@ -133,7 +133,7 @@ public JavaSource generateEndpoint(Module module) { JavaSource javaSource = generateEndpointSource(module, ops); - javaSource.apply(new OrderImports(false).doNext(new AutoFormat())); + javaSource.apply(new OrderImports(false), new AutoFormat()); return javaSource; } @@ -232,15 +232,17 @@ private JavaSource generateEndpointSource(Module module, List javaParserSupplier = () -> new RewriteJavaParser(new SbmApplicationProperties(), - new RewriteExecutionContext()); - final private AbstractAction action = new AbstractAction() { @Override public void apply(ProjectContext context) { - ReplaceMediaType r = new ReplaceMediaType(javaParserSupplier); + ReplaceMediaType r = new ReplaceMediaType(); context.getProjectJavaSources().apply(r); } }; @@ -75,7 +72,7 @@ public String getHelloWorldJSON(String name) { ) .build(); - ReplaceMediaType sut = new ReplaceMediaType(javaParserSupplier); + ReplaceMediaType sut = new ReplaceMediaType(); JavaSource javaSource = projectContext.getProjectJavaSources().list().get(0); javaSource.apply(sut); @@ -561,7 +558,7 @@ public String getHelloWorldJSON(@PathParam("name") String name) { ) .build(); - ReplaceMediaType r = new ReplaceMediaType(javaParserSupplier); + ReplaceMediaType r = new ReplaceMediaType(); JavaSource javaSource = projectContext.getProjectJavaSources().list().get(0); javaSource.apply(r); diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseBuilderTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseBuilderTest.java index 30cd81332..482372eb5 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseBuilderTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseBuilderTest.java @@ -15,6 +15,7 @@ */ package org.springframework.sbm.jee.jaxrs.recipes; +import org.openrewrite.SourceFile; import org.openrewrite.java.tree.J; import org.springframework.sbm.engine.recipe.AbstractAction; import org.springframework.sbm.engine.context.ProjectContext; @@ -26,6 +27,7 @@ import org.junit.jupiter.api.Test; import java.util.List; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @@ -375,7 +377,7 @@ void type() { String actual = projectContext.getProjectJavaSources().list().get(0).print(); // verify it compiles - List parse = new RewriteJavaParser(new SbmApplicationProperties(), + Stream parse = new RewriteJavaParser(new SbmApplicationProperties(), new RewriteExecutionContext()).parse(actual); assertThat(actual) diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseEntityReplacementTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseEntityReplacementTest.java index de811c342..74b430101 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseEntityReplacementTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseEntityReplacementTest.java @@ -38,10 +38,8 @@ public class ResponseEntityReplacementTest { new AbstractAction() { @Override public void apply(ProjectContext context) { - Supplier javaParserSupplier = () -> new RewriteJavaParser(new SbmApplicationProperties(), - new RewriteExecutionContext()); - Recipe r = new SwapResponseWithResponseEntity(javaParserSupplier).doNext(new ReplaceMediaType(javaParserSupplier)); - context.getProjectJavaSources().apply(r); + context.getProjectJavaSources().apply(new SwapResponseWithResponseEntity()); + context.getProjectJavaSources().apply(new ReplaceMediaType()); } }; diff --git a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseStatusTest.java b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseStatusTest.java index eddf52bcc..a195c80a0 100644 --- a/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseStatusTest.java +++ b/components/sbm-recipes-jee-to-boot/src/test/java/org/springframework/sbm/jee/jaxrs/recipes/ResponseStatusTest.java @@ -34,8 +34,7 @@ public class ResponseStatusTest { new AbstractAction() { @Override public void apply(ProjectContext context) { - SwapStatusForHttpStatus r = new SwapStatusForHttpStatus(() -> new RewriteJavaParser(new SbmApplicationProperties(), - new RewriteExecutionContext())); + SwapStatusForHttpStatus r = new SwapStatusForHttpStatus(); context.getProjectJavaSources().apply(r); } }; 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..2c0da3627 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 @@ -82,7 +82,7 @@ void shouldAddDependencyToSpringBootStarterDataJpaIfNoneExists() { sut.apply(projectContext); - assertThat(projectContext.getBuildFile().print()).isEqualTo( + assertThat(projectContext.getApplicationModules().getRootModule().getBuildFile().print()).isEqualTo( "\n" + "\n" + " """) - .addRegistrar(new PersistenceXmlProjectResourceRegistrar())) + ) .actionUnderTest(new MigratePersistenceXmlToApplicationPropertiesAction()) .verify(context -> { List applicationProperties = context.search(new SpringBootApplicationPropertiesResourceListFilter()); diff --git a/components/sbm-recipes-spring-cloud/pom.xml b/components/sbm-recipes-spring-cloud/pom.xml index 18e2b0b41..b6afab87a 100644 --- a/components/sbm-recipes-spring-cloud/pom.xml +++ b/components/sbm-recipes-spring-cloud/pom.xml @@ -57,6 +57,7 @@ org.springframework.sbm recipe-test-support + ${project.version} test diff --git a/components/sbm-recipes-spring-cloud/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java b/components/sbm-recipes-spring-cloud/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java index 4ca962036..70e08f74f 100644 --- a/components/sbm-recipes-spring-cloud/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java +++ b/components/sbm-recipes-spring-cloud/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java @@ -24,7 +24,7 @@ import com.tngtech.archunit.lang.ArchRule; import org.openrewrite.ExecutionContext; import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; diff --git a/components/sbm-support-boot/pom.xml b/components/sbm-support-boot/pom.xml index 0d0b4dc71..bad82b587 100644 --- a/components/sbm-support-boot/pom.xml +++ b/components/sbm-support-boot/pom.xml @@ -27,8 +27,8 @@ sbm-support-boot - 11 - 11 + 17 + 17 @@ -76,6 +76,7 @@ org.springframework.sbm recipe-test-support + ${project.version} com.tngtech.archunit diff --git a/components/sbm-support-boot/src/main/java/org/openrewrite/java/spring/SpringBeanDeclarationFinder.java b/components/sbm-support-boot/src/main/java/org/openrewrite/java/spring/SpringBeanDeclarationFinder.java index 185da5cc8..468441286 100644 --- a/components/sbm-support-boot/src/main/java/org/openrewrite/java/spring/SpringBeanDeclarationFinder.java +++ b/components/sbm-support-boot/src/main/java/org/openrewrite/java/spring/SpringBeanDeclarationFinder.java @@ -37,7 +37,12 @@ public String getDisplayName() { } @Override - protected TreeVisitor getVisitor() { + public String getDescription() { + return getDisplayName(); + } + + @Override + public TreeVisitor getVisitor() { return new JavaIsoVisitor<>() { @Override public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext executionContext) { diff --git a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/common/conditions/HasSpringBootDependencyImport.java b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/common/conditions/HasSpringBootDependencyImport.java index 0f0b8eea1..51d10fdeb 100644 --- a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/common/conditions/HasSpringBootDependencyImport.java +++ b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/common/conditions/HasSpringBootDependencyImport.java @@ -52,7 +52,7 @@ private boolean hasBuildFileDependencyImport(BuildFile buildFile) { } private String resolveCoordinates(BuildFile buildFile, Dependency md) { - String coordinates = md.getCoordinates(); + String coordinates = md.getGav(); if (md.getVersion().startsWith("${")) { String version = buildFile.getProperty(md.getVersion().substring(2, md.getVersion().length() - 1)); if (version != null) { diff --git a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/common/conditions/HasSpringBootDependencyManuallyManaged.java b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/common/conditions/HasSpringBootDependencyManuallyManaged.java index b67d69a12..93a27b6c2 100644 --- a/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/common/conditions/HasSpringBootDependencyManuallyManaged.java +++ b/components/sbm-support-boot/src/main/java/org/springframework/sbm/boot/common/conditions/HasSpringBootDependencyManuallyManaged.java @@ -56,6 +56,6 @@ public boolean evaluate(ProjectContext context) { @NotNull private Predicate matchesSpringBootPattern() { - return k -> k.getCoordinates().matches("org\\.springframework\\.boot:.*:" + versionPattern); + return k -> k.getGav().matches("org\\.springframework\\.boot:.*:" + versionPattern); } } 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 94e21497a..c3ad24bf6 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 @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; +import org.openrewrite.SourceFile; import org.openrewrite.properties.PropertiesParser; import org.openrewrite.properties.tree.Properties; import org.springframework.sbm.parsers.RewriteExecutionContext; @@ -39,10 +40,17 @@ void createNewProperties_Add_Print() { @Test void parseExistingPropertiesTest() { - List parse = new PropertiesParser().parse( - "foo=bar\n" + - "bob=bill"); - SpringBootApplicationProperties sut = new SpringBootApplicationProperties(Path.of("./projectDir").toAbsolutePath(), parse.get(0), new RewriteExecutionContext()); + List parse = new PropertiesParser() + .parse( + """ + foo=bar + bob=bill + """ + ) + .toList(); + Path absolutePath = Path.of("./projectDir").toAbsolutePath(); + Properties.File propertiesFile = (Properties.File) parse.get(0); + SpringBootApplicationProperties sut = new SpringBootApplicationProperties(absolutePath, propertiesFile, new RewriteExecutionContext()); assertThat(sut.getProperty("foo").get()).isEqualTo("bar"); assertThat(sut.getProperty("bob").get()).isEqualTo("bill"); assertThat(sut.getProperty("jane")).isEmpty(); diff --git a/components/sbm-support-jee/pom.xml b/components/sbm-support-jee/pom.xml index e9bad7e8d..0675c4141 100644 --- a/components/sbm-support-jee/pom.xml +++ b/components/sbm-support-jee/pom.xml @@ -27,8 +27,8 @@ sbm-support-jee - 11 - 11 + 17 + 17 diff --git a/components/sbm-support-jee/src/main/java/org/springframework/sbm/jee/jpa/resource/PersistenceXmlProjectResourceRegistrar.java b/components/sbm-support-jee/src/main/java/org/springframework/sbm/jee/jpa/resource/PersistenceXmlProjectResourceRegistrar.java index b0a0e4a62..09851296c 100644 --- a/components/sbm-support-jee/src/main/java/org/springframework/sbm/jee/jpa/resource/PersistenceXmlProjectResourceRegistrar.java +++ b/components/sbm-support-jee/src/main/java/org/springframework/sbm/jee/jpa/resource/PersistenceXmlProjectResourceRegistrar.java @@ -15,6 +15,8 @@ */ package org.springframework.sbm.jee.jpa.resource; +import org.openrewrite.ExecutionContext; +import org.openrewrite.internal.InMemoryLargeSourceSet; import org.springframework.sbm.jee.jpa.api.PersistenceXml; import org.springframework.sbm.project.resource.ProjectResourceWrapper; import org.springframework.sbm.project.resource.RewriteSourceFileHolder; @@ -32,6 +34,7 @@ public class PersistenceXmlProjectResourceRegistrar implements ProjectResourceWrapper> { public static final String PERSISTENCE_XML_PATH = "META-INF/persistence.xml"; + private final ExecutionContext executionContext; @Override public boolean shouldHandle(RewriteSourceFileHolder rewriteSourceFileHolder) { @@ -45,7 +48,7 @@ public boolean shouldHandle(RewriteSourceFileHolder rewrit } private boolean hasPersistenceRootTag(Xml.Document xml) { - List results = new FindTags("/persistence").run(List.of(xml)).getResults(); + List results = new FindTags("/persistence").run(new InMemoryLargeSourceSet(List.of(xml)), executionContext).getChangeset().getAllResults(); return ! results.isEmpty(); } diff --git a/components/sbm-support-jee/src/main/java/org/springframework/sbm/jee/web/api/JeeWebXmlProjectResourceRegistrar.java b/components/sbm-support-jee/src/main/java/org/springframework/sbm/jee/web/api/JeeWebXmlProjectResourceRegistrar.java index edba1cf73..a1254b6eb 100644 --- a/components/sbm-support-jee/src/main/java/org/springframework/sbm/jee/web/api/JeeWebXmlProjectResourceRegistrar.java +++ b/components/sbm-support-jee/src/main/java/org/springframework/sbm/jee/web/api/JeeWebXmlProjectResourceRegistrar.java @@ -15,6 +15,9 @@ */ package org.springframework.sbm.jee.web.api; +import org.openrewrite.ExecutionContext; +import org.openrewrite.internal.InMemoryLargeSourceSet; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.sbm.project.resource.ProjectResourceWrapper; import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.sbm.project.web.api.WebAppType; @@ -33,6 +36,9 @@ @Configuration public class JeeWebXmlProjectResourceRegistrar implements ProjectResourceWrapper> { + @Autowired + private ExecutionContext executionContext; + // @EventListener(ProjectContextBuiltEvent.class) // public void onProjectContextBuiltEvent(ProjectContextBuiltEvent projectContextBuiltEvent) { // ProjectContext projectContext = projectContextBuiltEvent.getProjectContext(); @@ -65,10 +71,16 @@ private WebAppType parseXml(String xml) { @Override public boolean shouldHandle(RewriteSourceFileHolder rewriteSourceFileHolder) { + boolean sourceFileIsXmlDocument = Xml.Document.class.isAssignableFrom(rewriteSourceFileHolder.getSourceFile().getClass()); + boolean fileNameEndsWithWebXml = rewriteSourceFileHolder.getAbsolutePath().getFileName().endsWith("web.xml"); + List sourceFiles = List.of(rewriteSourceFileHolder.getSourceFile()); + InMemoryLargeSourceSet inMemoryLargeSourceSet = new InMemoryLargeSourceSet(sourceFiles); + boolean hasWebAppTag = !new FindTags("/web-app").run(inMemoryLargeSourceSet, executionContext).getChangeset().getAllResults().isEmpty(); return ( - Xml.Document.class.isAssignableFrom(rewriteSourceFileHolder.getSourceFile().getClass()) && - rewriteSourceFileHolder.getAbsolutePath().getFileName().endsWith("web.xml") && - ! new FindTags("/web-app").run(List.of(rewriteSourceFileHolder.getSourceFile())).getResults().isEmpty()); + sourceFileIsXmlDocument && + fileNameEndsWithWebXml && + hasWebAppTag + ); } @Override diff --git a/components/sbm-support-jee/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java b/components/sbm-support-jee/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java index 4ca962036..70e08f74f 100644 --- a/components/sbm-support-jee/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java +++ b/components/sbm-support-jee/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java @@ -24,7 +24,7 @@ import com.tngtech.archunit.lang.ArchRule; import org.openrewrite.ExecutionContext; import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; diff --git a/components/sbm-support-jee/src/test/java/org/springframework/sbm/jee/ejb/api/EjbJarXmlTest.java b/components/sbm-support-jee/src/test/java/org/springframework/sbm/jee/ejb/api/EjbJarXmlTest.java index 749858668..94b529a2b 100644 --- a/components/sbm-support-jee/src/test/java/org/springframework/sbm/jee/ejb/api/EjbJarXmlTest.java +++ b/components/sbm-support-jee/src/test/java/org/springframework/sbm/jee/ejb/api/EjbJarXmlTest.java @@ -153,7 +153,7 @@ void unmarshal_no_schema() throws JAXBException { ""; Path sourcePath = Path.of("some/path/ejb-jar.xml"); - Xml.Document xml = new XmlParser().parse(ejbJarXmlContent).get(0); + Xml.Document xml = (Xml.Document) new XmlParser().parse(ejbJarXmlContent).toList().get(0); EjbJarXml jeeEjbJarXmlProjectResourceRegistrar = new EjbJarXml(sourcePath, xml); EjbJarType ejbJarType = jeeEjbJarXmlProjectResourceRegistrar.unmarshal(ejbJarXmlContent); Assertions.assertThat(ejbJarType).isNotNull(); diff --git a/components/sbm-support-jee/src/test/java/org/springframework/sbm/jee/web/api/WebXmlTest.java b/components/sbm-support-jee/src/test/java/org/springframework/sbm/jee/web/api/WebXmlTest.java index b598a5371..fd54c0cab 100644 --- a/components/sbm-support-jee/src/test/java/org/springframework/sbm/jee/web/api/WebXmlTest.java +++ b/components/sbm-support-jee/src/test/java/org/springframework/sbm/jee/web/api/WebXmlTest.java @@ -82,7 +82,7 @@ void deserializeMovieFunExampleWebXml() { """; - Xml.Document document = new XmlParser().parse(webXmlSource).get(0).withSourcePath(Path.of("src/main/webapp/WEB-INF/web.xml")); + Xml.Document document = new XmlParser().parse(webXmlSource).toList().get(0).withSourcePath(Path.of("src/main/webapp/WEB-INF/web.xml")); WebXml webXml = new WebXml(Path.of("test-path").toAbsolutePath(), document); List servletDefinitions = webXml.getServletDefinitions(); @@ -141,7 +141,7 @@ void deleteServletDefinition() throws JAXBException { } private WebXml createWebXml(Path absoluteProjectDir) throws JAXBException { - Xml.Document document = new XmlParser().parse(CONTENT).get(0).withSourcePath(Path.of("src/main/webapp/WEB-INF/web.xml")); + Xml.Document document = new XmlParser().parse(CONTENT).toList().get(0).withSourcePath(Path.of("src/main/webapp/WEB-INF/web.xml")); return new WebXml(absoluteProjectDir, document); } diff --git a/components/sbm-support-weblogic/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java b/components/sbm-support-weblogic/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java index 4ca962036..70e08f74f 100644 --- a/components/sbm-support-weblogic/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java +++ b/components/sbm-support-weblogic/src/test/java/org/springframework/sbm/architecture/ControlledInstantiationOfExecutionContextTest.java @@ -24,7 +24,7 @@ import com.tngtech.archunit.lang.ArchRule; import org.openrewrite.ExecutionContext; import org.springframework.sbm.boot.autoconfigure.ScopeConfiguration; -import org.springframework.sbm.openrewrite.RewriteExecutionContext; +import org.springframework.sbm.parsers.RewriteExecutionContext; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; diff --git a/components/test-helper/pom.xml b/components/test-helper/pom.xml index 5885d1f0e..50f2d90da 100644 --- a/components/test-helper/pom.xml +++ b/components/test-helper/pom.xml @@ -16,14 +16,13 @@ --> + 4.0.0 - spring-boot-migrator org.springframework.sbm + spring-boot-migrator 0.15.2-SNAPSHOT ../../pom.xml - 4.0.0 - test-helper @@ -40,47 +39,9 @@ org.springframework spring-core - - - org.apache.maven.resolver - maven-resolver-spi - 1.9.15 - - - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-api - ${shrinkwrap.resolvers.version} - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-spi - ${shrinkwrap.resolvers.version} - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-api-maven - ${shrinkwrap.resolvers.version} - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-spi-maven - ${shrinkwrap.resolvers.version} - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-impl-maven - ${shrinkwrap.resolvers.version} - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-impl-maven-archive - ${shrinkwrap.resolvers.version} - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-bom + shrinkwrap-resolver-depchain ${shrinkwrap.resolvers.version} pom diff --git a/pom.xml b/pom.xml index b992ed13f..4bfa00258 100644 --- a/pom.xml +++ b/pom.xml @@ -13,23 +13,24 @@ UTF-8 8.1.8 3.1.2 - + 2.5.0 17 17 3.10.1 + 3.2.1 17 5.0.5 2.0.6 - 3.2.0 - 3.2.1 1.18.24 + 3.2.0 + 1.9.13 UTF-8 UTF-8 src/generated/java - + 1.33 0.1.0-SNAPSHOT 0.0.5 @@ -54,6 +55,12 @@ components/sbm-core components/test-helper components/recipe-test-support + components/sbm-support-boot + components/sbm-support-jee + components/sbm-support-weblogic + components/sbm-recipes-jee-to-boot + components/sbm-recipes-spring-cloud + components/sbm-recipes-boot-upgrade @@ -234,11 +241,6 @@ sbm-support-rewrite ${sbm-support-rewrite.version} - - org.springframework.experimental - sbm-support-rewrite - ${sbm-support-rewrite.version} - ${jar.name} diff --git a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java index 8f8c9a039..b68be1340 100644 --- a/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java +++ b/sbm-support-rewrite/src/main/java/org/springframework/sbm/parsers/JavaParserBuilder.java @@ -20,13 +20,10 @@ import org.openrewrite.ExecutionContext; import org.openrewrite.java.JavaParser; import org.openrewrite.java.internal.JavaTypeCache; -import org.springframework.sbm.scopes.annotations.ScanScope; -import org.springframework.stereotype.Component; import java.nio.charset.Charset; import java.util.Collection; - public class JavaParserBuilder extends JavaParser.Builder{ @Getter