From 45ca436b41944ec5f7aec0991f4a6be9ed03e73e Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Fri, 2 Aug 2024 12:55:40 +0200 Subject: [PATCH] Isolate JavaTemplate issue with generic type parameters - For https://github.com/openrewrite/rewrite-spring/pull/284 --- .../openrewrite/java/JavaTemplateTest.java | 74 ++++++++++++++++--- 1 file changed, 62 insertions(+), 12 deletions(-) diff --git a/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest.java b/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest.java index 4760868cf5c..30a34b1d8c6 100755 --- a/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest.java +++ b/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest.java @@ -1200,19 +1200,69 @@ void finalMethodParameter() { rewriteRun( spec -> spec.recipe(new ReplaceAnnotation("@org.jetbrains.annotations.NotNull", "@lombok.NonNull", null)), java( - """ - import org.jetbrains.annotations.NotNull; - - class A { - String testMethod(@NotNull final String test) {} - } - """, """ - import lombok.NonNull; - - class A { - String testMethod(@NonNull final String test) {} + """ + import org.jetbrains.annotations.NotNull; + + class A { + String testMethod(@NotNull final String test) {} + } + """, """ + import lombok.NonNull; + + class A { + String testMethod(@NonNull final String test) {} + } + """) + ); + } + + @Test + @Issue("https://github.com/openrewrite/rewrite-spring/pull/284") + void replaceMethodInChainFollowedByGenericTypeParameters() { + rewriteRun( + spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() { + @Override + public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) { + if (new MethodMatcher("batch.StepBuilder create()").matches(method)) { + return JavaTemplate.builder("new StepBuilder()") + .contextSensitive() + .build() + .apply(getCursor(), method.getCoordinates().replace()); } - """) + return super.visitMethodInvocation(method, executionContext); + } + })) + .parser(JavaParser.fromJavaVersion().dependsOn( + """ + package batch; + public class StepBuilder { + public static StepBuilder create() { return new StepBuilder(); } + public StepBuilder() {} + public T method() { return null; } + } + """ + ) + ), + java( + """ + import batch.StepBuilder; + class Foo { + void test() { + StepBuilder.create() + .method(); + } + } + """, + """ + import batch.StepBuilder; + class Foo { + void test() { + new StepBuilder() + .method(); + } + } + """ + ) ); } }