Skip to content

Commit 1e8a08b

Browse files
knutwannhedensambsnydjkschneider
authored
Use new JavaTemplate API (#225)
Co-authored-by: Sam Snyder <[email protected]> Co-authored-by: Jonathan Schneider <[email protected]>
1 parent 09f4212 commit 1e8a08b

40 files changed

+338
-439
lines changed

src/main/java/org/openrewrite/java/migrate/UseJavaUtilBase64.java

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public String getDisplayName() {
4545
public String getDescription() {
4646
//language=markdown
4747
return "Prefer `java.util.Base64` instead of using `sun.misc` in Java 8 or higher. `sun.misc` is not exported " +
48-
"by the Java module system and accessing this class will result in a warning in Java 11 and an error in Java 17.";
48+
"by the Java module system and accessing this class will result in a warning in Java 11 and an error in Java 17.";
4949
}
5050

5151
public UseJavaUtilBase64(String sunPackage) {
@@ -71,7 +71,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
7171

7272
return Preconditions.check(check, new JavaVisitor<ExecutionContext>() {
7373
final JavaTemplate getDecoderTemplate = JavaTemplate.builder("Base64.getDecoder()")
74-
.context(this::getCursor)
74+
.contextSensitive()
7575
.imports("java.util.Base64")
7676
.build();
7777

@@ -102,13 +102,13 @@ public J visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
102102
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
103103
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
104104
if (base64EncodeMethod.matches(m) &&
105-
("encode".equals(method.getSimpleName()) || "encodeBuffer".equals(method.getSimpleName()))) {
106-
m = m.withTemplate(encodeToString, getCursor(), m.getCoordinates().replace(), method.getArguments().get(0));
105+
("encode".equals(method.getSimpleName()) || "encodeBuffer".equals(method.getSimpleName()))) {
106+
m = encodeToString.apply(updateCursor(m), m.getCoordinates().replace(), method.getArguments().get(0));
107107
if (method.getSelect() instanceof J.Identifier) {
108108
m = m.withSelect(method.getSelect());
109109
}
110110
} else if (base64DecodeBuffer.matches(method)) {
111-
m = m.withTemplate(decode, getCursor(), m.getCoordinates().replace(), method.getArguments().get(0));
111+
m = decode.apply(updateCursor(m), m.getCoordinates().replace(), method.getArguments().get(0));
112112
if (method.getSelect() instanceof J.Identifier) {
113113
m = m.withSelect(method.getSelect());
114114
}
@@ -125,14 +125,11 @@ public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
125125
J.NewClass c = (J.NewClass) super.visitNewClass(newClass, ctx);
126126
if (newBase64Encoder.matches(c)) {
127127
// noinspection Convert2MethodRef
128-
return c.withTemplate(
129-
JavaTemplate.compile(this, "getEncoder",
130-
() -> Base64.getEncoder()).build(),
131-
getCursor(),
132-
c.getCoordinates().replace()
133-
);
128+
return JavaTemplate.compile(this, "getEncoder", () -> Base64.getEncoder())
129+
.build()
130+
.apply(updateCursor(c), c.getCoordinates().replace());
134131
} else if (newBase64Decoder.matches(c)) {
135-
return c.withTemplate(getDecoderTemplate, getCursor(), c.getCoordinates().replace());
132+
return getDecoderTemplate.apply(updateCursor(c), c.getCoordinates().replace());
136133
}
137134
return c;
138135
}
@@ -141,11 +138,11 @@ public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
141138

142139
private boolean alreadyUsingIncompatibleBase64(JavaSourceFile cu) {
143140
return cu.getClasses().stream().anyMatch(it -> "Base64".equals(it.getSimpleName())) ||
144-
cu.getTypesInUse().getTypesInUse().stream()
145-
.filter(it -> it instanceof JavaType.FullyQualified)
146-
.map(JavaType.FullyQualified.class::cast)
147-
.map(JavaType.FullyQualified::getFullyQualifiedName)
148-
.filter(it -> !"java.util.Base64".equals(it))
149-
.anyMatch(it -> it.endsWith(".Base64"));
141+
cu.getTypesInUse().getTypesInUse().stream()
142+
.filter(it -> it instanceof JavaType.FullyQualified)
143+
.map(JavaType.FullyQualified.class::cast)
144+
.map(JavaType.FullyQualified::getFullyQualifiedName)
145+
.filter(it -> !"java.util.Base64".equals(it))
146+
.anyMatch(it -> it.endsWith(".Base64"));
150147
}
151148
}

src/main/java/org/openrewrite/java/migrate/apache/commons/codec/ApacheBase64ToJavaBase64.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
7575
JavaTemplate t = JavaTemplate.builder(templatePrefix).imports("java.util.Base64").build();
7676
maybeRemoveImport("org.apache.commons.codec.binary.Base64");
7777
maybeAddImport("java.util.Base64");
78-
mi = mi.withTemplate(t, getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0));
78+
mi = t.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0));
7979
}
8080
return mi;
8181
}

src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheFileUtilsToJavaFiles.java

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,17 +67,25 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
6767
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
6868
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);
6969
if (readFileToByteArrayMatcher.matches(mi)) {
70-
return mi.withTemplate(JavaTemplate.builder("Files.readAllBytes(#{any(java.io.File)}.toPath())")
71-
.imports("java.nio.file.Files").build(), getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0));
70+
return JavaTemplate.builder("Files.readAllBytes(#{any(java.io.File)}.toPath())")
71+
.imports("java.nio.file.Files")
72+
.build()
73+
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0));
7274
} else if (readLinesToByteArrayMatcher.matches(mi)) {
73-
return mi.withTemplate(JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath())")
74-
.imports("java.nio.file.Files").build(), getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0));
75+
return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath())")
76+
.imports("java.nio.file.Files")
77+
.build()
78+
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0));
7579
} else if (readLinesWithCharsetToByteArrayMatcher.matches(mi)) {
76-
return mi.withTemplate(JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), #{any(java.nio.charset.Charset)})")
77-
.imports("java.nio.file.Files", "java.nio.charset.Charset").build(), getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1));
80+
return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), #{any(java.nio.charset.Charset)})")
81+
.imports("java.nio.file.Files", "java.nio.charset.Charset")
82+
.build()
83+
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1));
7884
} else if (readLinesWithCharsetIdToByteArrayMatcher.matches(mi)) {
79-
return mi.withTemplate(JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), Charset.forName(#{any(String)}))")
80-
.imports("java.nio.file.Files", "java.nio.charset.Charset").build(), getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1));
85+
return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), Charset.forName(#{any(String)}))")
86+
.imports("java.nio.file.Files", "java.nio.charset.Charset")
87+
.build()
88+
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1));
8189
}
8290
return mi;
8391
}

src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheIOUtilsUseExplicitCharset.java

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -95,24 +95,25 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
9595
mi = mi.withSelect(method.getArguments().get(0));
9696
//noinspection ConstantConditions
9797
mi = mi.withMethodType(mi.getMethodType().withName("getBytes"));
98-
mi = mi.withTemplate(JavaTemplate.builder("#{any(String)}.getBytes(StandardCharsets.#{})}")
99-
.javaParser(javaParser)
100-
.imports("java.nio.charset.StandardCharsets")
101-
.build(),
102-
getCursor(),
103-
mi.getCoordinates().replaceMethod(), mi.getArguments().get(0), encoding == null ? "UTF_8" : encoding);
98+
mi = JavaTemplate.builder("#{any(String)}.getBytes(StandardCharsets.#{})}")
99+
.javaParser(javaParser)
100+
.imports("java.nio.charset.StandardCharsets")
101+
.build()
102+
.apply(updateCursor(mi),
103+
mi.getCoordinates().replaceMethod(),
104+
mi.getArguments().get(0), encoding == null ? "UTF_8" : encoding);
104105
} else {
105106
for (Map.Entry<MethodMatcher, String> entry : MATCHER_TEMPLATES.entrySet()) {
106107
if (entry.getKey().matches(mi)) {
107108
List<Object> args = new ArrayList<>(mi.getArguments());
108109
args.add(encoding == null ? "UTF_8" : encoding);
109-
mi = mi.withTemplate(JavaTemplate.builder(entry.getValue())
110-
.context(this::getCursor)
111-
.javaParser(javaParser)
112-
.imports("java.nio.charset.StandardCharsets")
113-
.build(),
114-
getCursor(),
115-
mi.getCoordinates().replaceMethod(), args.toArray());
110+
mi = JavaTemplate.builder(entry.getValue())
111+
.contextSensitive()
112+
.javaParser(javaParser)
113+
.imports("java.nio.charset.StandardCharsets")
114+
.build()
115+
.apply(updateCursor(mi),
116+
mi.getCoordinates().replaceMethod(), args.toArray());
116117
}
117118
}
118119
}

src/main/java/org/openrewrite/java/migrate/apache/commons/lang/IsNotEmptyToJdk.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
9292
// Remove excess parentheses
9393
doAfterVisit(new org.openrewrite.java.cleanup.UnnecessaryParentheses().getVisitor());
9494

95-
return mi.withTemplate(replacementTemplate, getCursor(), mi.getCoordinates().replace(), arg, arg);
95+
return replacementTemplate.apply(updateCursor(mi), mi.getCoordinates().replace(), arg, arg);
9696
}
9797
return mi;
9898
}

src/main/java/org/openrewrite/java/migrate/guava/NoGuavaAtomicsNewReference.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public Set<String> getTags() {
5050
public TreeVisitor<?, ExecutionContext> getVisitor() {
5151
return Preconditions.check(new UsesMethod<>(NEW_ATOMIC_REFERENCE), new JavaVisitor<ExecutionContext>() {
5252
private final JavaTemplate newAtomicReference = JavaTemplate.builder("new AtomicReference<>()")
53-
.context(this::getCursor)
53+
.contextSensitive()
5454
.imports("java.util.concurrent.atomic.AtomicReference")
5555
.build();
5656

@@ -59,7 +59,7 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
5959
if (NEW_ATOMIC_REFERENCE.matches(method)) {
6060
maybeRemoveImport("com.google.common.util.concurrent.Atomics");
6161
maybeAddImport("java.util.concurrent.atomic.AtomicReference");
62-
return ((J.NewClass) method.withTemplate(newAtomicReference, getCursor(), method.getCoordinates().replace()))
62+
return ((J.NewClass) newAtomicReference.apply(getCursor(), method.getCoordinates().replace()))
6363
.withArguments(method.getArguments());
6464
}
6565
return super.visitMethodInvocation(method, ctx);

src/main/java/org/openrewrite/java/migrate/guava/NoGuavaCreateTempDir.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,10 @@ private boolean isIOExceptionOrException(@Nullable JavaType.FullyQualified fqCat
9191
}
9292

9393
private J.MethodInvocation toFilesCreateTempDir(J.MethodInvocation methodInvocation) {
94-
JavaTemplate t = JavaTemplate.builder("Files.createTempDirectory(null).toFile()")
94+
return JavaTemplate.builder("Files.createTempDirectory(null).toFile()")
9595
.imports("java.nio.file.Files", "java.io.File")
96-
.build();
97-
return methodInvocation.withTemplate(t, getCursor(), methodInvocation.getCoordinates().replace());
96+
.build()
97+
.apply(updateCursor(methodInvocation), methodInvocation.getCoordinates().replace());
9898
}
9999
}
100100
}

src/main/java/org/openrewrite/java/migrate/guava/NoGuavaDirectExecutor.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,15 @@ public Set<String> getTags() {
4949
@Override
5050
public TreeVisitor<?, ExecutionContext> getVisitor() {
5151
return Preconditions.check(new UsesMethod<>(DIRECT_EXECUTOR), new JavaVisitor<ExecutionContext>() {
52-
private final JavaTemplate template = JavaTemplate.builder("Runnable::run")
53-
.context(this::getCursor)
54-
.imports("java.lang.Runnable")
55-
.build();
56-
5752
@Override
5853
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
5954
if (DIRECT_EXECUTOR.matches(method)) {
6055
maybeRemoveImport("com.google.common.util.concurrent.MoreExecutors");
61-
return method.withTemplate(template, getCursor(), method.getCoordinates().replace());
56+
return JavaTemplate.builder("Runnable::run")
57+
.contextSensitive()
58+
.imports("java.lang.Runnable")
59+
.build()
60+
.apply(getCursor(), method.getCoordinates().replace());
6261
}
6362
return super.visitMethodInvocation(method, ctx);
6463
}

src/main/java/org/openrewrite/java/migrate/guava/NoGuavaImmutableListOf.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,13 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
9999
.map(type -> "#{any(" + type.getFullyQualifiedName() + ")}")
100100
.collect(Collectors.joining(",", "List.of(", ")"));
101101

102-
return method.withTemplate(
103-
JavaTemplate.builder(template)
104-
.context(getCursor())
105-
.imports("java.util.List")
106-
.build(),
107-
getCursor(),
108-
method.getCoordinates().replace(),
109-
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
102+
return JavaTemplate.builder(template)
103+
.contextSensitive()
104+
.imports("java.util.List")
105+
.build()
106+
.apply(getCursor(),
107+
method.getCoordinates().replace(),
108+
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
110109
}
111110
return super.visitMethodInvocation(method, ctx);
112111
}

src/main/java/org/openrewrite/java/migrate/guava/NoGuavaImmutableMapOf.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -101,14 +101,14 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
101101
.map(type -> "#{any(" + type.getFullyQualifiedName() + ")}")
102102
.collect(Collectors.joining(",", "Map.of(", ")"));
103103

104-
return method.withTemplate(
105-
JavaTemplate.builder(template)
106-
.context(getCursor())
107-
.imports("java.util.Map")
108-
.build(),
109-
getCursor(),
110-
method.getCoordinates().replace(),
111-
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
104+
return JavaTemplate.builder(template)
105+
.contextSensitive()
106+
.imports("java.util.Map")
107+
.build()
108+
.apply(
109+
updateCursor(method),
110+
method.getCoordinates().replace(),
111+
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
112112
}
113113
return method;
114114
}

0 commit comments

Comments
 (0)