Skip to content

Commit 9e15e8a

Browse files
authored
Merge pull request #117 from openrewrite/java-template-only
Adjust to new OpenRewrite 8.0 `JavaTemplate` API
2 parents d267c8f + 0f1da8f commit 9e15e8a

36 files changed

+197
-243
lines changed

build.gradle.kts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ dependencies {
2121

2222
testImplementation("org.openrewrite:rewrite-groovy")
2323
testImplementation("org.junit-pioneer:junit-pioneer:2.0.0")
24+
testImplementation("junit:junit:4.13.2")
2425

2526
testRuntimeOnly("org.openrewrite:rewrite-java-17")
2627
testRuntimeOnly("com.google.code.findbugs:jsr305:latest.release")

src/main/java/org/openrewrite/staticanalysis/AddSerialVersionUidToSerializable.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public Set<String> getTags() {
5454
@Override
5555
public TreeVisitor<?, ExecutionContext> getVisitor() {
5656
return new JavaIsoVisitor<ExecutionContext>() {
57-
final JavaTemplate template = JavaTemplate.builder("private static final long serialVersionUID = 1;").context(this::getCursor).build();
57+
final JavaTemplate template = JavaTemplate.builder("private static final long serialVersionUID = 1;").contextSensitive().build();
5858

5959
@Override
6060
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext executionContext) {
@@ -90,7 +90,7 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
9090
return s;
9191
})));
9292
if (needsSerialVersionId.get()) {
93-
c = c.withTemplate(template, getCursor(), c.getBody().getCoordinates().firstStatement());
93+
c = template.apply(updateCursor(c), c.getBody().getCoordinates().firstStatement());
9494
}
9595
return c;
9696
}

src/main/java/org/openrewrite/staticanalysis/AtomicPrimitiveEqualsUsesGet.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext execu
6565
JavaType.FullyQualified fqt = TypeUtils.asFullyQualified(mi.getSelect().getType());
6666
if (fqt != null) {
6767
String templateString = "#{any(" + fqt.getFullyQualifiedName() + ")}.get() == #{any(" + fqt.getFullyQualifiedName() + ")}.get()";
68-
return mi.withTemplate(JavaTemplate.builder(templateString)
69-
.imports(fqt.getFullyQualifiedName()).build(),
70-
getCursor(), mi.getCoordinates().replace(), mi.getSelect(), mi.getArguments().get(0));
68+
return JavaTemplate.builder(templateString)
69+
.imports(fqt.getFullyQualifiedName()).build()
70+
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getSelect(), mi.getArguments().get(0));
7171
}
7272
}
7373
return mi;

src/main/java/org/openrewrite/staticanalysis/AvoidBoxedBooleanExpressions.java

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,8 @@ public Expression visitExpression(Expression expression, ExecutionContext ctx) {
5959
Expression e = (Expression) super.visitExpression(expression, ctx);
6060
if (TypeUtils.isOfClassType(e.getType(), "java.lang.Boolean")) {
6161
if (isControlExpression(expression)) {
62-
return e.withTemplate(
63-
JavaTemplate.builder("Boolean.TRUE.equals(#{any(java.lang.Boolean)})").build(),
64-
getCursor(),
65-
e.getCoordinates().replace(),
66-
e
67-
);
62+
return JavaTemplate.apply("Boolean.TRUE.equals(#{any(java.lang.Boolean)})",
63+
updateCursor(e), e.getCoordinates().replace(), e);
6864
}
6965
}
7066
return e;
@@ -74,12 +70,8 @@ public Expression visitExpression(Expression expression, ExecutionContext ctx) {
7470
public J visitUnary(J.Unary unary, ExecutionContext executionContext) {
7571
J.Unary un = (J.Unary) super.visitUnary(unary, executionContext);
7672
if (J.Unary.Type.Not == un.getOperator() && TypeUtils.isOfClassType(un.getExpression().getType(), "java.lang.Boolean")) {
77-
return un.withTemplate(
78-
JavaTemplate.builder("Boolean.FALSE.equals(#{any(java.lang.Boolean)})").build(),
79-
getCursor(),
80-
un.getCoordinates().replace(),
81-
un.getExpression()
82-
);
73+
return JavaTemplate.apply("Boolean.FALSE.equals(#{any(java.lang.Boolean)})",
74+
updateCursor(un), un.getCoordinates().replace(), un.getExpression());
8375
}
8476
return un;
8577
}

src/main/java/org/openrewrite/staticanalysis/BigDecimalRoundingConstantsToEnums.java

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,17 +61,17 @@ public Duration getEstimatedEffortPerOccurrence() {
6161
public TreeVisitor<?, ExecutionContext> getVisitor() {
6262
return Preconditions.check(new UsesType<>("java.math.BigDecimal", false), new JavaIsoVisitor<ExecutionContext>() {
6363
private final JavaTemplate twoArgDivide = JavaTemplate.builder("#{any(java.math.BigDecimal)}, #{}")
64-
.context(this::getCursor)
64+
.contextSensitive()
6565
.imports("java.math.RoundingMode")
6666
.build();
6767

6868
private final JavaTemplate twoArgScale = JavaTemplate.builder("#{any(int)}, #{}")
69-
.context(this::getCursor)
69+
.contextSensitive()
7070
.imports("java.math.RoundingMode")
7171
.build();
7272

7373
private final JavaTemplate threeArg = JavaTemplate.builder("#{any(java.math.BigDecimal)}, #{any(int)}, #{}")
74-
.context(this::getCursor)
74+
.contextSensitive()
7575
.imports("java.math.RoundingMode").build();
7676

7777
@Override
@@ -83,25 +83,22 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
8383
if (roundingModeEnum == null) {
8484
return m;
8585
}
86-
m = m.withTemplate(twoArgDivide, getCursor(), m.getCoordinates().replaceArguments(),
87-
m.getArguments().get(0), roundingModeEnum);
86+
m = twoArgDivide.apply(updateCursor(m), m.getCoordinates().replaceArguments(), m.getArguments().get(0), roundingModeEnum);
8887
maybeAddImport("java.math.RoundingMode");
8988
} else if (BIG_DECIMAL_SET_SCALE.matches(m) && isConvertibleBigDecimalConstant(m.getArguments().get(1))) {
9089
String roundingModeEnum = getTemplateText(m.getArguments().get(1));
9190
if (roundingModeEnum == null) {
9291
return m;
9392
}
94-
m = m.withTemplate(twoArgScale, getCursor(), m.getCoordinates().replaceArguments(),
95-
m.getArguments().get(0), roundingModeEnum);
93+
m = twoArgScale.apply(updateCursor(m), m.getCoordinates().replaceArguments(), m.getArguments().get(0), roundingModeEnum);
9694
maybeAddImport("java.math.RoundingMode");
9795
} else if (BIG_DECIMAL_DIVIDE_WITH_SCALE.matches(m) &&
9896
isConvertibleBigDecimalConstant(m.getArguments().get(2))) {
9997
String roundingModeEnum = getTemplateText(m.getArguments().get(2));
10098
if (roundingModeEnum == null) {
10199
return m;
102100
}
103-
m = m.withTemplate(threeArg, getCursor(), m.getCoordinates().replaceArguments(),
104-
m.getArguments().get(0), m.getArguments().get(1), roundingModeEnum);
101+
m = threeArg.apply(updateCursor(m), m.getCoordinates().replaceArguments(), m.getArguments().get(0), m.getArguments().get(1), roundingModeEnum);
105102
maybeAddImport("java.math.RoundingMode");
106103
}
107104
return m;

src/main/java/org/openrewrite/staticanalysis/CompareEnumsWithEqualityOperator.java

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,11 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext execu
6262
executionContext.putMessage("REMOVE_UNARY_NOT", parent.getValue());
6363
}
6464
String code = "#{any()} " + (isNot ? "!=" : "==") + " #{any()}";
65-
return autoFormat(m.withTemplate(
66-
JavaTemplate
67-
.builder(code)
68-
.context(getCursor())
69-
.build(),
70-
getCursor(),
71-
m.getCoordinates().replace(),
72-
m.getSelect(), m.getArguments().get(0)
73-
), executionContext);
65+
return autoFormat(JavaTemplate
66+
.builder(code)
67+
.contextSensitive()
68+
.build()
69+
.apply(updateCursor(m), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)), executionContext);
7470
}
7571
return m;
7672
}

src/main/java/org/openrewrite/staticanalysis/CovariantEqualsVisitor.java

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package org.openrewrite.staticanalysis;
1717

18+
import org.openrewrite.Cursor;
1819
import org.openrewrite.Incubating;
1920
import org.openrewrite.java.AnnotationMatcher;
2021
import org.openrewrite.java.JavaIsoVisitor;
@@ -45,8 +46,8 @@ private static class ChangeCovariantEqualsMethodVisitor<P> extends JavaIsoVisito
4546
private static final AnnotationMatcher OVERRIDE_ANNOTATION = new AnnotationMatcher("@java.lang.Override");
4647
private static final String EQUALS_BODY_PREFIX_TEMPLATE =
4748
"if (#{} == this) return true;\n" +
48-
"if (#{} == null || getClass() != #{}.getClass()) return false;\n" +
49-
"#{} #{} = (#{}) #{};\n";
49+
"if (#{} == null || getClass() != #{}.getClass()) return false;\n" +
50+
"#{} #{} = (#{}) #{};\n";
5051

5152
private final J.ClassDeclaration enclosingClass;
5253

@@ -69,16 +70,14 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, P
6970

7071
String ecfqn = type.getFullyQualifiedName();
7172
if (new MethodMatcher(ecfqn + " equals(" + ecfqn + ")").matches(m, enclosingClass) &&
72-
m.hasModifier(J.Modifier.Type.Public) &&
73-
m.getReturnTypeExpression() != null &&
74-
JavaType.Primitive.Boolean.equals(m.getReturnTypeExpression().getType())) {
73+
m.hasModifier(J.Modifier.Type.Public) &&
74+
m.getReturnTypeExpression() != null &&
75+
JavaType.Primitive.Boolean.equals(m.getReturnTypeExpression().getType())) {
7576

7677
if (m.getAllAnnotations().stream().noneMatch(OVERRIDE_ANNOTATION::matches)) {
77-
m = m.withTemplate(
78-
JavaTemplate.builder("@Override").build(),
79-
getCursor(),
80-
m.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName))
81-
);
78+
m = JavaTemplate.builder("@Override").build()
79+
.apply(updateCursor(m),
80+
m.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
8281
}
8382

8483
/*
@@ -88,18 +87,17 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, P
8887
*/
8988
J.VariableDeclarations.NamedVariable oldParamName = ((J.VariableDeclarations) m.getParameters().iterator().next()).getVariables().iterator().next();
9089
String paramName = "obj".equals(oldParamName.getSimpleName()) ? "other" : "obj";
91-
m = m.withTemplate(
92-
JavaTemplate.builder("Object #{}").context(() -> getCursor().getParentOrThrow()).build(),
93-
getCursor(),
94-
m.getCoordinates().replaceParameters(),
95-
paramName);
90+
m = JavaTemplate.builder("Object #{}").contextSensitive().build()
91+
.apply(updateCursor(m),
92+
m.getCoordinates().replaceParameters(),
93+
paramName);
9694

9795
/*
9896
* We'll prepend this type-check and type-cast to the beginning of the existing
9997
* equals(..) method body statements, and let the existing equals(..) method definition continue
10098
* with the logic doing what it was doing.
10199
*/
102-
JavaTemplate equalsBodySnippet = JavaTemplate.builder(EQUALS_BODY_PREFIX_TEMPLATE).context(this::getCursor).build();
100+
JavaTemplate equalsBodySnippet = JavaTemplate.builder(EQUALS_BODY_PREFIX_TEMPLATE).contextSensitive().build();
103101

104102
assert m.getBody() != null;
105103
Object[] params = new Object[]{
@@ -112,9 +110,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, P
112110
paramName
113111
};
114112

115-
m = m.withTemplate(
116-
equalsBodySnippet,
117-
getCursor(),
113+
m = equalsBodySnippet.apply(new Cursor(getCursor().getParent(), m),
118114
m.getBody().getStatements().get(0).getCoordinates().before(),
119115
params);
120116
}

src/main/java/org/openrewrite/staticanalysis/EmptyBlockVisitor.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,18 +42,18 @@
4242
public class EmptyBlockVisitor<P> extends JavaIsoVisitor<P> {
4343
EmptyBlockStyle emptyBlockStyle;
4444
JavaTemplate throwException = JavaTemplate.builder("throw new #{}(#{any(String)});")
45-
.context(this::getCursor)
45+
.contextSensitive()
4646
.imports("java.io.UncheckedIOException")
4747
.build();
48-
JavaTemplate continueStatement = JavaTemplate.builder("continue;").context(this::getCursor).build();
48+
JavaTemplate continueStatement = JavaTemplate.builder("continue;").contextSensitive().build();
4949

5050
@Override
5151
public J.WhileLoop visitWhileLoop(J.WhileLoop whileLoop, P p) {
5252
J.WhileLoop w = super.visitWhileLoop(whileLoop, p);
5353

5454
if (Boolean.TRUE.equals(emptyBlockStyle.getLiteralWhile()) && isEmptyBlock(w.getBody())) {
5555
J.Block body = (J.Block) w.getBody();
56-
w = w.withTemplate(continueStatement, getCursor(), body.getCoordinates().lastStatement());
56+
w = continueStatement.apply(updateCursor(w), body.getCoordinates().lastStatement());
5757
}
5858

5959
return w;
@@ -65,7 +65,7 @@ public J.DoWhileLoop visitDoWhileLoop(J.DoWhileLoop doWhileLoop, P p) {
6565

6666
if (Boolean.TRUE.equals(emptyBlockStyle.getLiteralWhile()) && isEmptyBlock(w.getBody())) {
6767
J.Block body = (J.Block) w.getBody();
68-
w = w.withTemplate(continueStatement, getCursor(), body.getCoordinates().lastStatement());
68+
w = continueStatement.apply(updateCursor(w), body.getCoordinates().lastStatement());
6969
}
7070

7171
return w;

src/main/java/org/openrewrite/staticanalysis/ExplicitCharsetOnStringGetBytes.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
5353
return Preconditions.check(new UsesMethod<>(GET_BYTES), new JavaIsoVisitor<ExecutionContext>() {
5454
final JavaTemplate WITH_ENCODING = JavaTemplate
5555
.builder("getBytes(StandardCharsets.#{})")
56-
.context(this::getCursor)
56+
.contextSensitive()
5757
.imports("java.nio.charset.StandardCharsets")
5858
.build();
5959

@@ -62,8 +62,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
6262
J.MethodInvocation m = super.visitMethodInvocation(method, ctx);
6363
if (GET_BYTES.matches(method)) {
6464
maybeAddImport("java.nio.charset.StandardCharsets");
65-
m = m.withTemplate(WITH_ENCODING, getCursor(), method.getCoordinates().replaceMethod(),
66-
encoding == null ? "UTF_8" : encoding);
65+
m = WITH_ENCODING.apply(updateCursor(m), m.getCoordinates().replaceMethod(), encoding == null ? "UTF_8" : encoding);
6766
}
6867
return m;
6968
}

src/main/java/org/openrewrite/staticanalysis/ExternalizableHasNoArgsConstructor.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,10 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
8787
}
8888
}
8989
if (!hasFinalUninitializedFieldVar && !hasNoArgsConstructor(cd) && parentClassHasNoArgsConstructor(cd)) {
90-
cd = cd.withTemplate(JavaTemplate.builder("public " + cd.getSimpleName() + "() {}").context(getCursor()).build(), getCursor(), cd.getBody().getCoordinates().lastStatement());
90+
cd = JavaTemplate.builder("public " + cd.getSimpleName() + "() {}")
91+
.contextSensitive()
92+
.build()
93+
.apply(updateCursor(cd), cd.getBody().getCoordinates().lastStatement());
9194
if (firstMethodDeclarationIndex != null) {
9295
statements.add(firstMethodDeclarationIndex, cd.getBody().getStatements().remove(cd.getBody().getStatements().size() - 1));
9396
cd = cd.withBody(cd.getBody().withStatements(statements));

0 commit comments

Comments
 (0)