Skip to content

Commit

Permalink
First use of JavaTemplate#compile
Browse files Browse the repository at this point in the history
  • Loading branch information
jkschneider committed Feb 13, 2023
1 parent f9ddc84 commit 823a70d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
2 changes: 2 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ dependencies {
annotationProcessor("org.projectlombok:lombok:latest.release")
testImplementation("org.projectlombok:lombok:latest.release")

annotationProcessor("org.openrewrite:rewrite-templating:latest.integration")

implementation(platform("org.openrewrite:rewrite-bom:${rewriteVersion}"))
implementation("org.openrewrite:rewrite-java")
implementation("org.openrewrite:rewrite-maven")
Expand Down
1 change: 1 addition & 0 deletions src/main/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
generated/
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaSourceFile;

import java.util.Base64;

public class UseJavaUtilBase64 extends Recipe {
private final String sunPackage;

Expand Down Expand Up @@ -64,9 +66,6 @@ protected JavaVisitor<ExecutionContext> getVisitor() {
MethodMatcher newBase64Decoder = new MethodMatcher(sunPackage + ".BASE64Decoder <constructor>()");

return new JavaVisitor<ExecutionContext>() {
final JavaTemplate getEncoderTemplate = JavaTemplate.builder(this::getCursor, "Base64.getEncoder()")
.imports("java.util.Base64")
.build();
final JavaTemplate getDecoderTemplate = JavaTemplate.builder(this::getCursor, "Base64.getDecoder()")
.imports("java.util.Base64")
.build();
Expand All @@ -81,7 +80,6 @@ protected JavaVisitor<ExecutionContext> getVisitor() {

@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) {

J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, executionContext);
if (base64EncodeMethod.matches(m) &&
("encode".equals(method.getSimpleName()) || "encodeBuffer".equals(method.getSimpleName()))) {
Expand Down Expand Up @@ -118,7 +116,11 @@ public J visitJavaSourceFile(JavaSourceFile cu, ExecutionContext ctx) {
public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
J.NewClass c = (J.NewClass) super.visitNewClass(newClass, ctx);
if (newBase64Encoder.matches(c)) {
return c.withTemplate(getEncoderTemplate, c.getCoordinates().replace());
return c.withTemplate(
JavaTemplate.compile(this, "getEncoder",
() -> Base64.getEncoder()).build(),
c.getCoordinates().replace()
);
}
if (newBase64Decoder.matches(newClass)) {
return c.withTemplate(getDecoderTemplate, c.getCoordinates().replace());
Expand Down

0 comments on commit 823a70d

Please sign in to comment.