Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.dubbo.annotation;

import com.sun.source.util.Trees;
Expand All @@ -27,56 +26,72 @@
import javax.annotation.processing.ProcessingEnvironment;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* The Context Object of Annotation Processor, which stores objects related to javac.
*/
public class AnnotationProcessorContext {
private static final Logger LOGGER = Logger.getLogger(AnnotationProcessorContext.class.getName());

private JavacProcessingEnvironment javacProcessingEnvironment;
private JavacTrees javacTrees;
private TreeMaker treeMaker;
private Names names;
private Context javacContext;
private Trees trees;

private AnnotationProcessorContext() { }
private AnnotationProcessorContext() {
// Private constructor to enforce usage through factory method
}

private static <T> T jbUnwrap(Class<? extends T> iface, T wrapper) {
T unwrapped = null;
try {
final Class<?> apiWrappers = wrapper.getClass().getClassLoader().loadClass("org.jetbrains.jps.javac.APIWrappers");
final Method unwrapMethod = apiWrappers.getDeclaredMethod("unwrap", Class.class, Object.class);
unwrapped = iface.cast(unwrapMethod.invoke(null, iface, wrapper));
} catch (Throwable ignored) {
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to unwrap ProcessingEnvironment: " + e.getMessage(), e);
}

return unwrapped != null ? unwrapped : wrapper;
}

public static AnnotationProcessorContext fromProcessingEnvironment(ProcessingEnvironment processingEnv) {
AnnotationProcessorContext apContext = new AnnotationProcessorContext();

if (processingEnv == null) {
throw new IllegalArgumentException("ProcessingEnvironment cannot be null");
}

Object procEnvToUnwrap = processingEnv.getClass() == JavacProcessingEnvironment.class ?
processingEnv : jbUnwrap(JavacProcessingEnvironment.class, processingEnv);

JavacProcessingEnvironment jcProcessingEnvironment = (JavacProcessingEnvironment) procEnvToUnwrap;
if (!(procEnvToUnwrap instanceof JavacProcessingEnvironment)) {
throw new IllegalStateException("Failed to obtain JavacProcessingEnvironment");
}

JavacProcessingEnvironment jcProcessingEnvironment = (JavacProcessingEnvironment) procEnvToUnwrap;
Context context = jcProcessingEnvironment.getContext();

apContext.javacProcessingEnvironment = jcProcessingEnvironment;

apContext.javacContext = context;
apContext.javacTrees = JavacTrees.instance(jcProcessingEnvironment);
apContext.treeMaker = TreeMaker.instance(context);
apContext.names = Names.instance(context);

apContext.trees = Trees.instance(jcProcessingEnvironment);

// Ensure all required components are initialized
if (apContext.javacTrees == null || apContext.treeMaker == null || apContext.names == null || apContext.trees == null) {
throw new IllegalStateException("Failed to initialize AnnotationProcessorContext due to missing components.");
}

LOGGER.info("Successfully created AnnotationProcessorContext.");
return apContext;
}

// Auto-generated methods.

public JavacTrees getJavacTrees() {
return javacTrees;
}
Expand Down Expand Up @@ -105,35 +120,30 @@ public JavacProcessingEnvironment getJavacProcessingEnvironment() {
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

AnnotationProcessorContext context = (AnnotationProcessorContext) o;

if (!Objects.equals(javacTrees, context.javacTrees)) return false;
if (!Objects.equals(treeMaker, context.treeMaker)) return false;
if (!Objects.equals(names, context.names)) return false;
if (!Objects.equals(javacContext, context.javacContext))
return false;
return Objects.equals(trees, context.trees);

AnnotationProcessorContext that = (AnnotationProcessorContext) o;
return Objects.equals(javacProcessingEnvironment, that.javacProcessingEnvironment) &&
Objects.equals(javacTrees, that.javacTrees) &&
Objects.equals(treeMaker, that.treeMaker) &&
Objects.equals(names, that.names) &&
Objects.equals(javacContext, that.javacContext) &&
Objects.equals(trees, that.trees);
}

@Override
public int hashCode() {
int result = javacTrees != null ? javacTrees.hashCode() : 0;
result = 31 * result + (treeMaker != null ? treeMaker.hashCode() : 0);
result = 31 * result + (names != null ? names.hashCode() : 0);
result = 31 * result + (javacContext != null ? javacContext.hashCode() : 0);
result = 31 * result + (trees != null ? trees.hashCode() : 0);
return result;
return Objects.hash(javacProcessingEnvironment, javacTrees, treeMaker, names, javacContext, trees);
}

@Override
public String toString() {
return "AnnotationProcessorContext{" +
"javacTrees=" + javacTrees +
", treeMaker=" + treeMaker +
", names=" + names +
", javacContext=" + javacContext +
", trees=" + trees +
'}';
"javacProcessingEnvironment=" + javacProcessingEnvironment +
", javacTrees=" + javacTrees +
", treeMaker=" + treeMaker +
", names=" + names +
", javacContext=" + javacContext +
", trees=" + trees +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
Expand Down Expand Up @@ -32,69 +32,68 @@
import java.util.Set;

/**
* Handles @Deprecated annotation and adds logger warn call to the methods that are annotated with it.
* Handles @Deprecated annotation and adds a logger warning and method invocation tracking
* for deprecated methods and constructors.
*/
public class DeprecatedHandler implements AnnotationProcessingHandler {

@Override
public Set<Class<? extends Annotation>> getAnnotationsToHandle() {
return new HashSet<>(
Collections.singletonList(Deprecated.class)
);
return new HashSet<>(Collections.singletonList(Deprecated.class));
}

@Override
public void process(Set<Element> elements, AnnotationProcessorContext apContext) {
for (Element element : elements) {
// Only interested in methods.
if (!(element instanceof Symbol.MethodSymbol)) {
// Only process methods and constructors
if (!(element instanceof Symbol.MethodSymbol methodSymbol)) {
continue;
}

Symbol.ClassSymbol classSymbol = (Symbol.ClassSymbol) element.getEnclosingElement();

// Check if it's a constructor
boolean isConstructor = methodSymbol.name.toString().equals(classSymbol.name.toString());

// Import necessary classes
ASTUtils.addImportStatement(apContext, classSymbol, "org.apache.dubbo.common", "DeprecatedMethodInvocationCounter");
ASTUtils.addImportStatement(apContext, classSymbol, "org.slf4j", "Logger");
ASTUtils.addImportStatement(apContext, classSymbol, "org.slf4j", "LoggerFactory");

JCTree methodTree = apContext.getJavacTrees().getTree(element);
apContext.getMessager().printMessage(javax.tools.Diagnostic.Kind.WARNING,
"Usage of deprecated " + (isConstructor ? "constructor" : "method") + " detected: " + getMethodDefinition(classSymbol, methodSymbol));

methodTree.accept(new TreeTranslator() {
@Override
public void visitMethodDef(JCTree.JCMethodDecl jcMethodDecl) {

JCTree.JCBlock block = jcMethodDecl.body;

if (block == null) {
// No method body. (i.e. interface method declaration.)
// No method body (i.e., interface method declaration)
return;
}

// Insert logging and counter tracking
ASTUtils.insertStatementToHeadOfMethod(block, jcMethodDecl, generateLoggerStatement(apContext, classSymbol));
ASTUtils.insertStatementToHeadOfMethod(block, jcMethodDecl, generateCounterStatement(apContext, classSymbol, jcMethodDecl));
}
});
}
}

/**
* Generate an expression statement like this:
* <code>DeprecatedMethodInvocationCounter.onDeprecatedMethodCalled("....");
*
* @param originalMethodDecl the method declaration that will add logger statement
* @param apContext annotation processor context
* @param classSymbol the enclosing class that will be the logger's name
* @return generated expression statement
* Generate a statement to track deprecated method invocations.
* Example: DeprecatedMethodInvocationCounter.onDeprecatedMethodCalled("class.method(params)");
*/
private JCTree.JCExpressionStatement generateCounterStatement(AnnotationProcessorContext apContext,
Symbol.ClassSymbol classSymbol,
JCTree.JCMethodDecl originalMethodDecl) {

JCTree.JCExpression fullStatement = apContext.getTreeMaker().Apply(
com.sun.tools.javac.util.List.nil(),

apContext.getTreeMaker().Select(
apContext.getTreeMaker().Ident(apContext.getNames().fromString("DeprecatedMethodInvocationCounter")),
apContext.getNames().fromString("onDeprecatedMethodCalled")
),

com.sun.tools.javac.util.List.of(
apContext.getTreeMaker().Literal(getMethodDefinition(classSymbol, originalMethodDecl))
)
Expand All @@ -103,8 +102,43 @@ private JCTree.JCExpressionStatement generateCounterStatement(AnnotationProcesso
return apContext.getTreeMaker().Exec(fullStatement);
}

private String getMethodDefinition(Symbol.ClassSymbol classSymbol, JCTree.JCMethodDecl originalMethodDecl) {
return classSymbol.getQualifiedName() + "."
+ originalMethodDecl.name.toString() + "(" + originalMethodDecl.params.toString() + ")";
/**
* Generate a logger statement that logs a warning when a deprecated method is called.
* Example: logger.warn("Deprecated method called: class.method(params)\n Stack trace: ...");
*/
private JCTree.JCExpressionStatement generateLoggerStatement(AnnotationProcessorContext apContext, Symbol.ClassSymbol classSymbol) {
// Generate logger initialization statement
JCTree.JCExpression loggerInit = apContext.getTreeMaker().Apply(
com.sun.tools.javac.util.List.nil(),
apContext.getTreeMaker().Select(
apContext.getTreeMaker().Ident(apContext.getNames().fromString("LoggerFactory")),
apContext.getNames().fromString("getLogger")
),
com.sun.tools.javac.util.List.of(apContext.getTreeMaker().Literal(classSymbol.getQualifiedName().toString()))
);

// logger.warn("Deprecated method called: ...", new Exception());
JCTree.JCExpression logStatement = apContext.getTreeMaker().Apply(
com.sun.tools.javac.util.List.nil(),
apContext.getTreeMaker().Select(
apContext.getTreeMaker().Ident(apContext.getNames().fromString("logger")),
apContext.getNames().fromString("warn")
),
com.sun.tools.javac.util.List.of(
apContext.getTreeMaker().Literal("Deprecated method called in " + classSymbol.getQualifiedName()),
apContext.getTreeMaker().NewClass(
null, com.sun.tools.javac.util.List.nil(),
apContext.getTreeMaker().Ident(apContext.getNames().fromString("Exception")),
com.sun.tools.javac.util.List.nil(),
null
)
)
);

return apContext.getTreeMaker().Exec(logStatement);
}

private String getMethodDefinition(Symbol.ClassSymbol classSymbol, Symbol.MethodSymbol methodSymbol) {
return classSymbol.getQualifiedName() + "." + methodSymbol.name.toString() + "(" + methodSymbol.params.toString() + ")";
}
}