Skip to content

Commit

Permalink
Adjust to new OpenRewrite 8.0 JavaTemplate API
Browse files Browse the repository at this point in the history
  • Loading branch information
knutwannheden committed Jun 1, 2023
1 parent 5e82c7c commit 73eb21a
Show file tree
Hide file tree
Showing 10 changed files with 91 additions and 106 deletions.
11 changes: 6 additions & 5 deletions src/main/java/org/openrewrite/java/logging/AddLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.openrewrite.java.logging;

import org.openrewrite.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.ListUtils;
Expand Down Expand Up @@ -65,7 +66,7 @@ public static AddLogger addSlf4jLogger(J.ClassDeclaration scope, String loggerNa
return new AddLogger(scope, "org.slf4j.Logger", "org.slf4j.LoggerFactory", loggerName, visitor ->
JavaTemplate
.builder("private static final Logger #{} = LoggerFactory.getLogger(#{}.class);")
.context(visitor::getCursor)
.contextSensitive()
.imports("org.slf4j.Logger", "org.slf4j.LoggerFactory")
.javaParser(JavaParser.fromJavaVersion().classpath("slf4j-api"))
.build()
Expand All @@ -76,7 +77,7 @@ public static AddLogger addJulLogger(J.ClassDeclaration scope, String loggerName
return new AddLogger(scope, "java.util.logging.Logger", "java.util.logging.LogManager", loggerName, visitor ->
JavaTemplate
.builder("private static final Logger #{} = LogManager.getLogger(\"#{}\");")
.context(visitor::getCursor)
.contextSensitive()
.imports("java.util.logging.Logger", "java.util.logging.LogManager")
.build()
);
Expand All @@ -86,7 +87,7 @@ public static AddLogger addLog4j1Logger(J.ClassDeclaration scope, String loggerN
return new AddLogger(scope, "org.apache.log4j.Logger", "org.apache.log4j.LogManager", loggerName, visitor ->
JavaTemplate
.builder("private static final Logger #{} = LogManager.getLogger(#{}.class);")
.context(visitor::getCursor)
.contextSensitive()
.imports("org.apache.log4j.Logger", "org.apache.log4j.LogManager")
.javaParser(JavaParser.fromJavaVersion().classpath("log4j"))
.build()
Expand All @@ -97,7 +98,7 @@ public static AddLogger addLog4j2Logger(J.ClassDeclaration scope, String loggerN
return new AddLogger(scope, "org.apache.logging.log4j.Logger", "org.apache.logging.log4j.LogManager", loggerName, visitor ->
JavaTemplate
.builder("private static final Logger #{} = LogManager.getLogger(#{}.class);")
.context(visitor::getCursor)
.contextSensitive()
.imports("org.apache.logging.log4j.Logger", "org.apache.logging.log4j.LogManager")
.javaParser(JavaParser.fromJavaVersion().classpath("log4j-api"))
.build()
Expand All @@ -113,7 +114,7 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
return cd;
}

cd = cd.withTemplate(template, getCursor(), cd.getBody().getCoordinates().firstStatement(), loggerName, cd.getSimpleName());
cd = template.apply(new Cursor(getCursor().getParent(), cd), cd.getBody().getCoordinates().firstStatement(), loggerName, cd.getSimpleName());

// ensure the appropriate number of blank lines on next statement after new field
J.ClassDeclaration formatted = (J.ClassDeclaration) new AutoFormatVisitor<ExecutionContext>().visitNonNull(cd, ctx, getCursor());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,27 +58,27 @@ public <P> JavaTemplate getErrorTemplate(JavaVisitor<P> visitor, String message)
case SLF4J:
return JavaTemplate
.builder("#{any(org.slf4j.Logger)}.error(" + message + ", #{any(java.lang.Throwable)})")
.context(visitor::getCursor)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion().classpath("slf4j-api"))
.build();
case Log4J1:
return JavaTemplate
.builder("#{any(org.apache.log4j.Category)}.error(" + message + ", #{any(java.lang.Throwable)})")
.context(visitor::getCursor)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion().classpath("log4j"))
.build();

case Log4J2:
return JavaTemplate
.builder("#{any(org.apache.logging.log4j.Logger)}.error(" + message + ", #{any(java.lang.Throwable)})")
.context(visitor::getCursor)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion().classpath("log4j-api"))
.build();
case JUL:
default:
return JavaTemplate
.builder("#{any(java.util.logging.Logger)}.log(Level.SEVERE, " + message + ", #{any(java.lang.Throwable)})")
.context(visitor::getCursor)
.contextSensitive()
.imports("java.util.logging.Level")
.build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,17 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
});
messageBuilder.append("\"");
newArgList.forEach(arg -> messageBuilder.append(", #{any()}"));
m = m.withTemplate(
JavaTemplate.builder(messageBuilder.toString())
.context(getCursor())
.build(),
getCursor(),
m.getCoordinates().replaceArguments(),
newArgList.toArray()
);
m = JavaTemplate.builder(messageBuilder.toString())
.contextSensitive()
.build()
.apply(new Cursor(getCursor().getParent(), m), m.getCoordinates().replaceArguments(), newArgList.toArray());
} else if (!TypeUtils.isString(logMsg.getType()) && logMsg.getType() instanceof JavaType.Class) {
StringBuilder messageBuilder = new StringBuilder("\"{}\"");
m.getArguments().forEach(arg -> messageBuilder.append(", #{any()}"));
m = m.withTemplate(
JavaTemplate.builder(messageBuilder.toString())
.context(getCursor())
.build(),
getCursor(),
m.getCoordinates().replaceArguments(),
m.getArguments().toArray()
);
m = JavaTemplate.builder(messageBuilder.toString())
.contextSensitive()
.build()
.apply(new Cursor(getCursor().getParent(), m), m.getCoordinates().replaceArguments(), m.getArguments().toArray());
}
if (Boolean.TRUE.equals(removeToString)) {
m = m.withArguments(ListUtils.map(m.getArguments(), arg -> (Expression) removeToStringVisitor.visitNonNull(arg, ctx, getCursor())));
Expand All @@ -134,7 +126,7 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
if (TO_STRING.matches(method.getSelect())) {
getCursor().putMessage("DO_NOT_REMOVE", Boolean.TRUE);
} else if (TO_STRING.matches(method)) {
return method.withTemplate(t, getCursor(), method.getCoordinates().replace(), method.getSelect());
return t.apply(getCursor(), method.getCoordinates().replace(), method.getSelect());
}
return super.visitMethodInvocation(method, ctx);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,12 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
J.ClassDeclaration clazz = getCursor().firstEnclosingOrThrow(J.ClassDeclaration.class);
Set<J.VariableDeclarations> loggers = FindFieldsOfType.find(clazz, framework.getLoggerType());
if (!loggers.isEmpty()) {
m = m.withTemplate(framework.getErrorTemplate(this, "\"Exception\""),
getCursor(),
m.getCoordinates().replace(),
loggers.iterator().next().getVariables().get(0).getName(),
m.getSelect());
m = framework.getErrorTemplate(this, "\"Exception\"")
.apply(
new Cursor(getCursor().getParent(), m),
m.getCoordinates().replace(),
loggers.iterator().next().getVariables().get(0).getName(),
m.getSelect());
if (framework == LoggingFramework.JUL) {
maybeAddImport("java.util.logging.Level");
}
Expand Down
45 changes: 26 additions & 19 deletions src/main/java/org/openrewrite/java/logging/SystemErrToLogging.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public class SystemErrToLogging extends Recipe {
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(5);
}

private static final MethodMatcher printStackTrace = new MethodMatcher("java.lang.Throwable printStackTrace(..)");

@Option(displayName = "Add logger",
Expand Down Expand Up @@ -81,6 +82,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
@Override
public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
J.Block b = super.visitBlock(block, ctx);
Cursor blockCursor = new Cursor(getCursor().getParent(), b);

AtomicBoolean addedLogger = new AtomicBoolean(false);
AtomicInteger skip = new AtomicInteger(-1);
Expand All @@ -103,7 +105,8 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
}
}

J.MethodInvocation unchangedIfAddedLogger = logInsteadOfPrint(m, ctx, exceptionPrintStackTrace);
Cursor printCursor = new Cursor(blockCursor, m);
J.MethodInvocation unchangedIfAddedLogger = logInsteadOfPrint(printCursor, ctx, exceptionPrintStackTrace);
addedLogger.set(unchangedIfAddedLogger == m);
return unchangedIfAddedLogger;
}
Expand All @@ -124,37 +127,41 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
if (m.getSelect() != null && m.getSelect() instanceof J.FieldAccess) {
JavaType.Variable field = ((J.FieldAccess) m.getSelect()).getName().getFieldType();
if (field != null && "err".equals(field.getName()) && TypeUtils.isOfClassType(field.getOwner(), "java.lang.System")) {
return logInsteadOfPrint(m, ctx, null);
Cursor printCursor = new Cursor(getCursor().getParent(), m);
return logInsteadOfPrint(printCursor, ctx, null);
}
}
}
}
return m;
}

private J.MethodInvocation logInsteadOfPrint(J.MethodInvocation print, ExecutionContext ctx, @Nullable Expression exceptionPrintStackTrace) {
private J.MethodInvocation logInsteadOfPrint(Cursor printCursor, ExecutionContext ctx, @Nullable Expression exceptionPrintStackTrace) {
J.MethodInvocation print = printCursor.getValue();
J.ClassDeclaration clazz = getCursor().firstEnclosingOrThrow(J.ClassDeclaration.class);
Set<J.VariableDeclarations> loggers = FindFieldsOfType.find(clazz, framework.getLoggerType());
if (!loggers.isEmpty()) {
J.Identifier computedLoggerName = loggers.iterator().next().getVariables().get(0).getName();
if (exceptionPrintStackTrace == null) {
print = print.withTemplate(getErrorTemplateNoException(this),
getCursor(),
print.getCoordinates().replace(),
computedLoggerName,
print.getArguments().get(0));
print = getErrorTemplateNoException(this)
.apply(
printCursor,
print.getCoordinates().replace(),
computedLoggerName,
print.getArguments().get(0));
} else {
print = print.withTemplate(framework.getErrorTemplate(this, "#{any(String)}"),
getCursor(),
print.getCoordinates().replace(),
computedLoggerName,
print.getArguments().get(0),
exceptionPrintStackTrace);
print = framework.getErrorTemplate(this, "#{any(String)}")
.apply(
printCursor,
print.getCoordinates().replace(),
computedLoggerName,
print.getArguments().get(0),
exceptionPrintStackTrace);
}

print = (J.MethodInvocation) new ParameterizedLogging(framework.getLoggerType() + " error(..)", false)
.getVisitor()
.visitNonNull(print, ctx, getCursor());
.visitNonNull(print, ctx, printCursor);

if (framework == LoggingFramework.JUL) {
maybeAddImport("java.util.logging.Level");
Expand All @@ -173,27 +180,27 @@ public <P> JavaTemplate getErrorTemplateNoException(JavaVisitor<P> visitor) {
case SLF4J:
return JavaTemplate
.builder("#{any(org.slf4j.Logger)}.error(#{any(String)})")
.context(visitor::getCursor)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion().classpath("slf4j-api"))
.build();
case Log4J1:
return JavaTemplate
.builder("#{any(org.apache.log4j.Category)}.error(#{any(String)})")
.context(visitor::getCursor)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion().classpath("log4j"))
.build();

case Log4J2:
return JavaTemplate
.builder("#{any(org.apache.logging.log4j.Logger)}.error(#{any(String)})")
.context(visitor::getCursor)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion().classpath("log4j-api"))
.build();
case JUL:
default:
return JavaTemplate
.builder("#{any(java.util.logging.Logger)}.log(Level.SEVERE, #{any(String)})")
.context(visitor::getCursor)
.contextSensitive()
.imports("java.util.logging.Level")
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,27 +88,28 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
if (m.getSelect() != null && m.getSelect() instanceof J.FieldAccess) {
JavaType.Variable field = ((J.FieldAccess) m.getSelect()).getName().getFieldType();
if (field != null && "out".equals(field.getName()) && TypeUtils.isOfClassType(field.getOwner(), "java.lang.System")) {
return logInsteadOfPrint(m, ctx);
return logInsteadOfPrint(new Cursor(getCursor().getParent(), m), ctx);
}
}
}
return m;
}

private J.MethodInvocation logInsteadOfPrint(J.MethodInvocation print, ExecutionContext ctx) {
private J.MethodInvocation logInsteadOfPrint(Cursor printCursor, ExecutionContext ctx) {
J.MethodInvocation print = printCursor.getValue();
J.ClassDeclaration clazz = getCursor().firstEnclosingOrThrow(J.ClassDeclaration.class);
Set<J.VariableDeclarations> loggers = FindFieldsOfType.find(clazz, framework.getLoggerType());
if (!loggers.isEmpty()) {
J.Identifier computedLoggerName = loggers.iterator().next().getVariables().get(0).getName();
print = print.withTemplate(getInfoTemplate(this),
getCursor(),
print = getInfoTemplate(this).apply(
printCursor,
print.getCoordinates().replace(),
computedLoggerName,
print.getArguments().get(0));

print = (J.MethodInvocation) new ParameterizedLogging(framework.getLoggerType() + " " + getLevel() + "(..)", false)
.getVisitor()
.visitNonNull(print, ctx, getCursor());
.visitNonNull(print, ctx, printCursor);

if (framework == LoggingFramework.JUL) {
maybeAddImport("java.util.logging.Level");
Expand Down Expand Up @@ -153,7 +154,7 @@ private <P> JavaTemplate getInfoTemplate(JavaVisitor<P> visitor) {

private String getLevel() {
String levelOrDefault = level == null ? "info" : level;
if(framework == LoggingFramework.JUL) {
if (framework == LoggingFramework.JUL) {
String julLevel = levelOrDefault.toUpperCase();
if ("debug".equals(levelOrDefault)) {
julLevel = "FINE";
Expand Down
Loading

0 comments on commit 73eb21a

Please sign in to comment.