Skip to content

Commit

Permalink
Use new JavaTemplate API (#225)
Browse files Browse the repository at this point in the history
Co-authored-by: Sam Snyder <[email protected]>
Co-authored-by: Jonathan Schneider <[email protected]>
  • Loading branch information
3 people authored Jun 1, 2023
1 parent 09f4212 commit 1e8a08b
Show file tree
Hide file tree
Showing 40 changed files with 338 additions and 439 deletions.
33 changes: 15 additions & 18 deletions src/main/java/org/openrewrite/java/migrate/UseJavaUtilBase64.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public String getDisplayName() {
public String getDescription() {
//language=markdown
return "Prefer `java.util.Base64` instead of using `sun.misc` in Java 8 or higher. `sun.misc` is not exported " +
"by the Java module system and accessing this class will result in a warning in Java 11 and an error in Java 17.";
"by the Java module system and accessing this class will result in a warning in Java 11 and an error in Java 17.";
}

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

return Preconditions.check(check, new JavaVisitor<ExecutionContext>() {
final JavaTemplate getDecoderTemplate = JavaTemplate.builder("Base64.getDecoder()")
.context(this::getCursor)
.contextSensitive()
.imports("java.util.Base64")
.build();

Expand Down Expand Up @@ -102,13 +102,13 @@ public J visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (base64EncodeMethod.matches(m) &&
("encode".equals(method.getSimpleName()) || "encodeBuffer".equals(method.getSimpleName()))) {
m = m.withTemplate(encodeToString, getCursor(), m.getCoordinates().replace(), method.getArguments().get(0));
("encode".equals(method.getSimpleName()) || "encodeBuffer".equals(method.getSimpleName()))) {
m = encodeToString.apply(updateCursor(m), m.getCoordinates().replace(), method.getArguments().get(0));
if (method.getSelect() instanceof J.Identifier) {
m = m.withSelect(method.getSelect());
}
} else if (base64DecodeBuffer.matches(method)) {
m = m.withTemplate(decode, getCursor(), m.getCoordinates().replace(), method.getArguments().get(0));
m = decode.apply(updateCursor(m), m.getCoordinates().replace(), method.getArguments().get(0));
if (method.getSelect() instanceof J.Identifier) {
m = m.withSelect(method.getSelect());
}
Expand All @@ -125,14 +125,11 @@ public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
J.NewClass c = (J.NewClass) super.visitNewClass(newClass, ctx);
if (newBase64Encoder.matches(c)) {
// noinspection Convert2MethodRef
return c.withTemplate(
JavaTemplate.compile(this, "getEncoder",
() -> Base64.getEncoder()).build(),
getCursor(),
c.getCoordinates().replace()
);
return JavaTemplate.compile(this, "getEncoder", () -> Base64.getEncoder())
.build()
.apply(updateCursor(c), c.getCoordinates().replace());
} else if (newBase64Decoder.matches(c)) {
return c.withTemplate(getDecoderTemplate, getCursor(), c.getCoordinates().replace());
return getDecoderTemplate.apply(updateCursor(c), c.getCoordinates().replace());
}
return c;
}
Expand All @@ -141,11 +138,11 @@ public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {

private boolean alreadyUsingIncompatibleBase64(JavaSourceFile cu) {
return cu.getClasses().stream().anyMatch(it -> "Base64".equals(it.getSimpleName())) ||
cu.getTypesInUse().getTypesInUse().stream()
.filter(it -> it instanceof JavaType.FullyQualified)
.map(JavaType.FullyQualified.class::cast)
.map(JavaType.FullyQualified::getFullyQualifiedName)
.filter(it -> !"java.util.Base64".equals(it))
.anyMatch(it -> it.endsWith(".Base64"));
cu.getTypesInUse().getTypesInUse().stream()
.filter(it -> it instanceof JavaType.FullyQualified)
.map(JavaType.FullyQualified.class::cast)
.map(JavaType.FullyQualified::getFullyQualifiedName)
.filter(it -> !"java.util.Base64".equals(it))
.anyMatch(it -> it.endsWith(".Base64"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
JavaTemplate t = JavaTemplate.builder(templatePrefix).imports("java.util.Base64").build();
maybeRemoveImport("org.apache.commons.codec.binary.Base64");
maybeAddImport("java.util.Base64");
mi = mi.withTemplate(t, getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0));
mi = t.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0));
}
return mi;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,25 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);
if (readFileToByteArrayMatcher.matches(mi)) {
return mi.withTemplate(JavaTemplate.builder("Files.readAllBytes(#{any(java.io.File)}.toPath())")
.imports("java.nio.file.Files").build(), getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0));
return JavaTemplate.builder("Files.readAllBytes(#{any(java.io.File)}.toPath())")
.imports("java.nio.file.Files")
.build()
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0));
} else if (readLinesToByteArrayMatcher.matches(mi)) {
return mi.withTemplate(JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath())")
.imports("java.nio.file.Files").build(), getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0));
return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath())")
.imports("java.nio.file.Files")
.build()
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0));
} else if (readLinesWithCharsetToByteArrayMatcher.matches(mi)) {
return mi.withTemplate(JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), #{any(java.nio.charset.Charset)})")
.imports("java.nio.file.Files", "java.nio.charset.Charset").build(), getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1));
return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), #{any(java.nio.charset.Charset)})")
.imports("java.nio.file.Files", "java.nio.charset.Charset")
.build()
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1));
} else if (readLinesWithCharsetIdToByteArrayMatcher.matches(mi)) {
return mi.withTemplate(JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), Charset.forName(#{any(String)}))")
.imports("java.nio.file.Files", "java.nio.charset.Charset").build(), getCursor(), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1));
return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), Charset.forName(#{any(String)}))")
.imports("java.nio.file.Files", "java.nio.charset.Charset")
.build()
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1));
}
return mi;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,24 +95,25 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
mi = mi.withSelect(method.getArguments().get(0));
//noinspection ConstantConditions
mi = mi.withMethodType(mi.getMethodType().withName("getBytes"));
mi = mi.withTemplate(JavaTemplate.builder("#{any(String)}.getBytes(StandardCharsets.#{})}")
.javaParser(javaParser)
.imports("java.nio.charset.StandardCharsets")
.build(),
getCursor(),
mi.getCoordinates().replaceMethod(), mi.getArguments().get(0), encoding == null ? "UTF_8" : encoding);
mi = JavaTemplate.builder("#{any(String)}.getBytes(StandardCharsets.#{})}")
.javaParser(javaParser)
.imports("java.nio.charset.StandardCharsets")
.build()
.apply(updateCursor(mi),
mi.getCoordinates().replaceMethod(),
mi.getArguments().get(0), encoding == null ? "UTF_8" : encoding);
} else {
for (Map.Entry<MethodMatcher, String> entry : MATCHER_TEMPLATES.entrySet()) {
if (entry.getKey().matches(mi)) {
List<Object> args = new ArrayList<>(mi.getArguments());
args.add(encoding == null ? "UTF_8" : encoding);
mi = mi.withTemplate(JavaTemplate.builder(entry.getValue())
.context(this::getCursor)
.javaParser(javaParser)
.imports("java.nio.charset.StandardCharsets")
.build(),
getCursor(),
mi.getCoordinates().replaceMethod(), args.toArray());
mi = JavaTemplate.builder(entry.getValue())
.contextSensitive()
.javaParser(javaParser)
.imports("java.nio.charset.StandardCharsets")
.build()
.apply(updateCursor(mi),
mi.getCoordinates().replaceMethod(), args.toArray());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
// Remove excess parentheses
doAfterVisit(new org.openrewrite.java.cleanup.UnnecessaryParentheses().getVisitor());

return mi.withTemplate(replacementTemplate, getCursor(), mi.getCoordinates().replace(), arg, arg);
return replacementTemplate.apply(updateCursor(mi), mi.getCoordinates().replace(), arg, arg);
}
return mi;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public Set<String> getTags() {
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(NEW_ATOMIC_REFERENCE), new JavaVisitor<ExecutionContext>() {
private final JavaTemplate newAtomicReference = JavaTemplate.builder("new AtomicReference<>()")
.context(this::getCursor)
.contextSensitive()
.imports("java.util.concurrent.atomic.AtomicReference")
.build();

Expand All @@ -59,7 +59,7 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
if (NEW_ATOMIC_REFERENCE.matches(method)) {
maybeRemoveImport("com.google.common.util.concurrent.Atomics");
maybeAddImport("java.util.concurrent.atomic.AtomicReference");
return ((J.NewClass) method.withTemplate(newAtomicReference, getCursor(), method.getCoordinates().replace()))
return ((J.NewClass) newAtomicReference.apply(getCursor(), method.getCoordinates().replace()))
.withArguments(method.getArguments());
}
return super.visitMethodInvocation(method, ctx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ private boolean isIOExceptionOrException(@Nullable JavaType.FullyQualified fqCat
}

private J.MethodInvocation toFilesCreateTempDir(J.MethodInvocation methodInvocation) {
JavaTemplate t = JavaTemplate.builder("Files.createTempDirectory(null).toFile()")
return JavaTemplate.builder("Files.createTempDirectory(null).toFile()")
.imports("java.nio.file.Files", "java.io.File")
.build();
return methodInvocation.withTemplate(t, getCursor(), methodInvocation.getCoordinates().replace());
.build()
.apply(updateCursor(methodInvocation), methodInvocation.getCoordinates().replace());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,15 @@ public Set<String> getTags() {
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(DIRECT_EXECUTOR), new JavaVisitor<ExecutionContext>() {
private final JavaTemplate template = JavaTemplate.builder("Runnable::run")
.context(this::getCursor)
.imports("java.lang.Runnable")
.build();

@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
if (DIRECT_EXECUTOR.matches(method)) {
maybeRemoveImport("com.google.common.util.concurrent.MoreExecutors");
return method.withTemplate(template, getCursor(), method.getCoordinates().replace());
return JavaTemplate.builder("Runnable::run")
.contextSensitive()
.imports("java.lang.Runnable")
.build()
.apply(getCursor(), method.getCoordinates().replace());
}
return super.visitMethodInvocation(method, ctx);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,13 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
.map(type -> "#{any(" + type.getFullyQualifiedName() + ")}")
.collect(Collectors.joining(",", "List.of(", ")"));

return method.withTemplate(
JavaTemplate.builder(template)
.context(getCursor())
.imports("java.util.List")
.build(),
getCursor(),
method.getCoordinates().replace(),
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
return JavaTemplate.builder(template)
.contextSensitive()
.imports("java.util.List")
.build()
.apply(getCursor(),
method.getCoordinates().replace(),
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
}
return super.visitMethodInvocation(method, ctx);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
.map(type -> "#{any(" + type.getFullyQualifiedName() + ")}")
.collect(Collectors.joining(",", "Map.of(", ")"));

return method.withTemplate(
JavaTemplate.builder(template)
.context(getCursor())
.imports("java.util.Map")
.build(),
getCursor(),
method.getCoordinates().replace(),
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
return JavaTemplate.builder(template)
.contextSensitive()
.imports("java.util.Map")
.build()
.apply(
updateCursor(method),
method.getCoordinates().replace(),
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
}
return method;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,8 @@ public Duration getEstimatedEffortPerOccurrence() {
// Updates to either may apply to each of the recipes.
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext> check = Preconditions.and(new UsesJavaVersion<>(9),
new UsesType<>("com.google.common.collect.ImmutableSet", false));

return Preconditions.check(check, new JavaVisitor<ExecutionContext>() {

return Preconditions.check(Preconditions.and(new UsesJavaVersion<>(9),
new UsesType<>("com.google.common.collect.ImmutableSet", false)), new JavaVisitor<ExecutionContext>() {
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
if (IMMUTABLE_SET_MATCHER.matches(method) && isParentTypeDownCast()) {
Expand Down Expand Up @@ -109,14 +106,13 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
.map(type -> "#{any(" + type.getFullyQualifiedName() + ")}")
.collect(Collectors.joining(",", "Set.of(", ")"));

return method.withTemplate(
JavaTemplate.builder(template)
.context(getCursor())
.imports("java.util.Set")
.build(),
getCursor(),
method.getCoordinates().replace(),
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
return JavaTemplate.builder(template)
.contextSensitive()
.imports("java.util.Set")
.build()
.apply(getCursor(),
method.getCoordinates().replace(),
method.getArguments().get(0) instanceof J.Empty ? new Object[]{} : method.getArguments().toArray());
}
return super.visitMethodInvocation(method, ctx);
}
Expand Down
Loading

0 comments on commit 1e8a08b

Please sign in to comment.