Skip to content

Commit bb1e273

Browse files
Use JavaTemplate.apply() static method (#7219)
* Use `JavaTemplate.apply()` static method Use this link to re-run the recipe: https://app.moderne.io/recipes/org.openrewrite.java.recipes.UseJavaTemplateStaticApply?organizationId=QUxML01vZGVybmUvTW9kZXJuZSArIE9wZW5SZXdyaXRl Co-authored-by: Moderne <team@moderne.io> * Fix StackOverflowError in static JavaTemplate.apply() The static apply() method was calling itself recursively instead of delegating to builder(template).build().apply(). --------- Co-authored-by: Moderne <team@moderne.io>
1 parent e3a8798 commit bb1e273

11 files changed

Lines changed: 37 additions & 117 deletions

File tree

rewrite-gradle/src/main/java/org/openrewrite/gradle/MigrateDependenciesToVersionCatalog.java

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -491,13 +491,7 @@ private Expression transformDependencyToVersionCatalog(Expression arg, J.MethodI
491491
if (dep != null) {
492492
boolean hasMultipleArgs = methodInvocation.getArguments().size() > 1;
493493

494-
Expression catalogRef = JavaTemplate.builder("libs.#{}")
495-
.build()
496-
.apply(
497-
new Cursor(getCursor(), arg),
498-
arg.getCoordinates().replace(),
499-
dep.getAliasName()
500-
);
494+
Expression catalogRef = JavaTemplate.apply("libs.#{}", new Cursor(getCursor(), arg), arg.getCoordinates().replace(), dep.getAliasName());
501495

502496
catalogRef = catalogRef.withPrefix(literal.getPrefix());
503497

@@ -526,13 +520,7 @@ private Expression transformDependencyToVersionCatalog(Expression arg, J.MethodI
526520
if (dep.gav.getGroupId().equals(group) && dep.gav.getArtifactId().equals(artifact)) {
527521
boolean hasMultipleArgs = methodInvocation.getArguments().size() > 1;
528522

529-
Expression catalogRef = JavaTemplate.builder("libs.#{}")
530-
.build()
531-
.apply(
532-
new Cursor(getCursor(), arg),
533-
arg.getCoordinates().replace(),
534-
dep.getAliasName()
535-
);
523+
Expression catalogRef = JavaTemplate.apply("libs.#{}", new Cursor(getCursor(), arg), arg.getCoordinates().replace(), dep.getAliasName());
536524

537525
catalogRef = catalogRef.withPrefix(gstring.getPrefix());
538526

rewrite-gradle/src/test/java/org/openrewrite/gradle/GradleJavaTemplateTest.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,7 @@ void useJavaTemplateInBuildGradle() {
3434
@Override
3535
public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
3636
if (block.getStatements().isEmpty()) {
37-
return JavaTemplate.builder("implementation(\"com.google.guava:guava:latest.release\")")
38-
.build()
39-
.apply(getCursor(), block.getCoordinates().lastStatement());
37+
return JavaTemplate.apply("implementation(\"com.google.guava:guava:latest.release\")", getCursor(), block.getCoordinates().lastStatement());
4038
}
4139
return super.visitBlock(block, ctx);
4240
}

rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateContextFreeTest.java

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,7 @@ void contextFreeTypeParameter() {
167167
@Override
168168
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
169169
if ("o".equals(multiVariable.getVariables().getFirst().getSimpleName())) {
170-
return JavaTemplate.builder("var o = #{any()};")
171-
.build()
172-
.apply(getCursor(), multiVariable.getCoordinates().replace(), multiVariable.getVariables().getFirst().getInitializer());
170+
return JavaTemplate.apply("var o = #{any()};", getCursor(), multiVariable.getCoordinates().replace(), multiVariable.getVariables().getFirst().getInitializer());
173171
}
174172
return multiVariable;
175173
}
@@ -241,9 +239,7 @@ void contextFreeTypeParameterConflictNames_broken() {
241239
@Override
242240
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) {
243241
if ("printf".equals(method.getSimpleName()) && method.getArguments().size() == 2) {
244-
return JavaTemplate.builder("System.out.printf(#{any()}, #{any()}, 0);")
245-
.build()
246-
.apply(getCursor(), method.getCoordinates().replace(), method.getArguments().toArray());
242+
return JavaTemplate.apply("System.out.printf(#{any()}, #{any()}, 0);", getCursor(), method.getCoordinates().replace(), method.getArguments().toArray());
247243
}
248244
return super.visitMethodInvocation(method, executionContext);
249245
}
@@ -277,9 +273,7 @@ void contextFreeRecursiveTypeParameters() {
277273
@Override
278274
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
279275
if ("o".equals(multiVariable.getVariables().getFirst().getSimpleName())) {
280-
return JavaTemplate.builder("var o = #{any()};")
281-
.build()
282-
.apply(getCursor(), multiVariable.getCoordinates().replace(), multiVariable.getVariables().getFirst().getInitializer());
276+
return JavaTemplate.apply("var o = #{any()};", getCursor(), multiVariable.getCoordinates().replace(), multiVariable.getVariables().getFirst().getInitializer());
283277
}
284278
return multiVariable;
285279
}
@@ -317,9 +311,7 @@ void contextFreeSequenceTypeParameters() {
317311
@Override
318312
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
319313
if ("o".equals(multiVariable.getVariables().getFirst().getSimpleName())) {
320-
return JavaTemplate.builder("var o = #{any()};")
321-
.build()
322-
.apply(getCursor(), multiVariable.getCoordinates().replace(), multiVariable.getVariables().getFirst().getInitializer());
314+
return JavaTemplate.apply("var o = #{any()};", getCursor(), multiVariable.getCoordinates().replace(), multiVariable.getVariables().getFirst().getInitializer());
323315
}
324316
return multiVariable;
325317
}
@@ -359,9 +351,7 @@ void contextFreeMultipleBoundParameters() {
359351
@Override
360352
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
361353
if ("o".equals(multiVariable.getVariables().getFirst().getSimpleName())) {
362-
return JavaTemplate.builder("var o = #{any()};")
363-
.build()
364-
.apply(getCursor(), multiVariable.getCoordinates().replace(), multiVariable.getVariables().getFirst().getInitializer());
354+
return JavaTemplate.apply("var o = #{any()};", getCursor(), multiVariable.getCoordinates().replace(), multiVariable.getVariables().getFirst().getInitializer());
365355
}
366356
return multiVariable;
367357
}

rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateInstanceOfTest.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -479,13 +479,7 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
479479
}
480480

481481
List<Expression> arguments = mi.getArguments();
482-
mi = JavaTemplate.builder("#{any(java.lang.String)}.formatted(#{any()})")
483-
.build()
484-
.apply(
485-
updateCursor(mi),
486-
mi.getCoordinates().replace(),
487-
arguments.toArray()
488-
);
482+
mi = JavaTemplate.apply("#{any(java.lang.String)}.formatted(#{any()})", updateCursor(mi), mi.getCoordinates().replace(), arguments.toArray());
489483

490484
return maybeAutoFormat(mi, mi.withArguments(
491485
ListUtils.map(arguments.subList(1, arguments.size()), (a, b) -> b.withPrefix(arguments.get(a + 1).getPrefix()))), ctx);

rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateNamedTest.java

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,10 @@ void replaceSingleStatement() {
3333
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
3434
@Override
3535
public J visitAssert(J.Assert anAssert, ExecutionContext p) {
36-
return JavaTemplate.builder(
37-
"""
38-
if(#{name:any(int)} != #{}) {
39-
#{name}++;
40-
}"""
41-
)
42-
.build()
43-
.apply(getCursor(), anAssert.getCoordinates().replace(),
44-
((J.Binary) anAssert.getCondition()).getLeft(), "1");
36+
return JavaTemplate.apply("""
37+
if(#{name:any(int)} != #{}) {
38+
#{name}++;
39+
}""", getCursor(), anAssert.getCoordinates().replace(), ((J.Binary) anAssert.getCondition()).getLeft(), "1");
4540
}
4641
})),
4742
java(

rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateSubstitutionsTest.java

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,7 @@ void annotation() {
124124
@Override
125125
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext executionContext) {
126126
if ("test".equals(method.getSimpleName())) {
127-
return JavaTemplate.builder("#{} void test2() {}")
128-
.build()
129-
.apply(getCursor(), method.getCoordinates().replace(), method.getLeadingAnnotations().getFirst());
127+
return JavaTemplate.apply("#{} void test2() {}", getCursor(), method.getCoordinates().replace(), method.getLeadingAnnotations().getFirst());
130128
}
131129
return method;
132130
}
@@ -194,9 +192,7 @@ void block() {
194192
@Override
195193
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext executionContext) {
196194
var s = method.getBody().getStatements().getFirst();
197-
return JavaTemplate.builder("if(true) #{}")
198-
.build()
199-
.apply(getCursor(), s.getCoordinates().replace(), method.getBody());
195+
return JavaTemplate.apply("if(true) #{}", getCursor(), s.getCoordinates().replace(), method.getBody());
200196
}
201197
}).withMaxCycles(1)),
202198
java(
@@ -425,9 +421,7 @@ void anyIsGenericWithUnknownType() {
425421
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
426422
@Override
427423
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
428-
return JavaTemplate.builder("System.out.println(#{any()})")
429-
.build()
430-
.apply(getCursor(), method.getCoordinates().replace(), method);
424+
return JavaTemplate.apply("System.out.println(#{any()})", getCursor(), method.getCoordinates().replace(), method);
431425
}
432426
}).withMaxCycles(1)),
433427
java(
@@ -457,9 +451,7 @@ void throwNewException() {
457451
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
458452
@Override
459453
public J visitMethodInvocation(J.MethodInvocation methodInvocation, ExecutionContext executionContext) {
460-
return JavaTemplate.builder("throw new RuntimeException()")
461-
.build()
462-
.apply(getCursor(), methodInvocation.getCoordinates().replace());
454+
return JavaTemplate.apply("throw new RuntimeException()", getCursor(), methodInvocation.getCoordinates().replace());
463455
}
464456
})),
465457
java(

rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest.java

Lines changed: 10 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,7 @@ void addParentheses() {
110110
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
111111
@Override
112112
public <T extends J> J visitParentheses(J.Parentheses<T> parens, ExecutionContext ctx) {
113-
return JavaTemplate.builder("#{any()}")
114-
.build()
115-
.apply(getCursor(), parens.getCoordinates().replace(), parens.getTree());
113+
return JavaTemplate.apply("#{any()}", getCursor(), parens.getCoordinates().replace(), parens.getTree());
116114
}
117115
}))
118116
.cycles(1)
@@ -138,9 +136,7 @@ void addParenthesesToParameter() {
138136
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
139137
@Override
140138
public J visitBinary(J.Binary binary, ExecutionContext ctx) {
141-
return JavaTemplate.builder("#{any(int)} * 3")
142-
.build()
143-
.apply(getCursor(), binary.getCoordinates().replace(), binary);
139+
return JavaTemplate.apply("#{any(int)} * 3", getCursor(), binary.getCoordinates().replace(), binary);
144140
}
145141
}))
146142
.cycles(1)
@@ -209,9 +205,7 @@ public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations m
209205
return multiVariable;
210206
}
211207
J.VariableDeclarations.NamedVariable var0 = multiVariable.getVariables().getFirst();
212-
return JavaTemplate.builder("var #{} = #{any()};")
213-
.build()
214-
.apply(getCursor(), multiVariable.getCoordinates().replace(), var0.getSimpleName(), var0.getInitializer());
208+
return JavaTemplate.apply("var #{} = #{any()};", getCursor(), multiVariable.getCoordinates().replace(), var0.getSimpleName(), var0.getInitializer());
215209
}
216210
})),
217211
java(
@@ -399,18 +393,11 @@ public J visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ct
399393
if (classDecl.getBody().getStatements().size() > 1) {
400394
return classDecl;
401395
}
402-
return JavaTemplate.builder("""
396+
return JavaTemplate.apply("""
403397
void m2() {
404398
#{any()}
405399
}
406-
"""
407-
)
408-
.build()
409-
.apply(
410-
getCursor(),
411-
classDecl.getBody().getStatements().getFirst().getCoordinates().after(),
412-
((J.MethodDeclaration) classDecl.getBody().getStatements().getFirst()).getBody().getStatements().getFirst()
413-
);
400+
""", getCursor(), classDecl.getBody().getStatements().getFirst().getCoordinates().after(), ((J.MethodDeclaration) classDecl.getBody().getStatements().getFirst()).getBody().getStatements().getFirst());
414401
}
415402
})),
416403
java(
@@ -595,9 +582,7 @@ void templatingWhileLoopCondition() {
595582
public J visitBinary(J.Binary binary, ExecutionContext ctx) {
596583
if (binary.getLeft() instanceof J.MethodInvocation) {
597584
var mi = (J.MethodInvocation) binary.getLeft();
598-
return JavaTemplate.builder("!#{any(java.util.List)}.isEmpty()")
599-
.build()
600-
.apply(getCursor(), mi.getCoordinates().replace(), mi.getSelect());
585+
return JavaTemplate.apply("!#{any(java.util.List)}.isEmpty()", getCursor(), mi.getCoordinates().replace(), mi.getSelect());
601586
} else if (binary.getLeft() instanceof J.Unary) {
602587
return binary.getLeft();
603588
}
@@ -678,12 +663,7 @@ void replaceExpressionWithAnotherExpression() {
678663
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
679664
@Override
680665
public J visitUnary(J.Unary unary, ExecutionContext ctx) {
681-
return JavaTemplate.builder("#{any()}++")
682-
.build().apply(
683-
getCursor(),
684-
unary.getCoordinates().replace(),
685-
unary.getExpression()
686-
);
666+
return JavaTemplate.apply("#{any()}++", getCursor(), unary.getCoordinates().replace(), unary.getExpression());
687667
}
688668
}).withMaxCycles(1)),
689669
java(
@@ -1017,9 +997,7 @@ void nestedEnums() {
1017997
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
1018998
@Override
1019999
public J visitBinary(J.Binary binary, ExecutionContext ctx) {
1020-
return JavaTemplate.builder("\"ab\"")
1021-
.build()
1022-
.apply(getCursor(), binary.getCoordinates().replace());
1000+
return JavaTemplate.apply("\"ab\"", getCursor(), binary.getCoordinates().replace());
10231001
}
10241002
})),
10251003
java(
@@ -1354,9 +1332,7 @@ void replaceMethodInChainFollowedByGenericTypeParameters() {
13541332
@Override
13551333
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
13561334
if (new MethodMatcher("batch.StepBuilder create()").matches(method)) {
1357-
return JavaTemplate.builder("new StepBuilder()")
1358-
.build()
1359-
.apply(getCursor(), method.getCoordinates().replace());
1335+
return JavaTemplate.apply("new StepBuilder()", getCursor(), method.getCoordinates().replace());
13601336
}
13611337
return super.visitMethodInvocation(method, ctx);
13621338
}
@@ -1406,9 +1382,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
14061382
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);
14071383
if (new MethodMatcher("Foo bar(..)").matches(mi) &&
14081384
mi.getArguments().getFirst() instanceof J.Binary) {
1409-
return JavaTemplate.builder("\"Hello, {}\", \"World!\"")
1410-
.build()
1411-
.apply(new Cursor(getCursor().getParent(), mi), mi.getCoordinates().replaceArguments());
1385+
return JavaTemplate.apply("\"Hello, {}\", \"World!\"", new Cursor(getCursor().getParent(), mi), mi.getCoordinates().replaceArguments());
14121386
}
14131387
return mi;
14141388
}

rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest3Test.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,7 @@ void replacePackage() {
4040
@Override
4141
public J.Package visitPackage(J.Package pkg, ExecutionContext p) {
4242
if ("a".equals(pkg.getExpression().printTrimmed(getCursor()))) {
43-
return JavaTemplate.builder("b")
44-
.build()
45-
.apply(getCursor(), pkg.getCoordinates().replace());
43+
return JavaTemplate.apply("b", getCursor(), pkg.getCoordinates().replace());
4644
}
4745
return super.visitPackage(pkg, p);
4846
}

rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest4Test.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,9 +166,7 @@ void replaceAndInterpolateMethodParameters() {
166166
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext p) {
167167
{
168168
if ("test".equals(method.getSimpleName()) && method.getParameters().size() == 1) {
169-
return JavaTemplate.builder("int n, #{}")
170-
.build()
171-
.apply(getCursor(), method.getCoordinates().replaceParameters(), method.getParameters().getFirst());
169+
return JavaTemplate.apply("int n, #{}", getCursor(), method.getCoordinates().replaceParameters(), method.getParameters().getFirst());
172170
}
173171
return method;
174172
}

rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest6Test.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,9 +243,7 @@ void replaceThrows() {
243243
@Override
244244
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext p) {
245245
if (method.getThrows() == null) {
246-
return JavaTemplate.builder("Exception")
247-
.build()
248-
.apply(getCursor(), method.getCoordinates().replaceThrows());
246+
return JavaTemplate.apply("Exception", getCursor(), method.getCoordinates().replaceThrows());
249247
}
250248
return super.visitMethodDeclaration(method, p);
251249
}

0 commit comments

Comments
 (0)