Add CallGraphBuilder with tests and maven/multi-module golden fixtures.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-12 08:30:48 +02:00
parent cc35546d01
commit 9ede60049b
6 changed files with 2786 additions and 0 deletions

View File

@@ -0,0 +1,777 @@
package click.kamil.springstatemachineexporter.analysis.service;
import click.kamil.springstatemachineexporter.analysis.model.CallChain;
import click.kamil.springstatemachineexporter.analysis.model.EntryPoint;
import click.kamil.springstatemachineexporter.analysis.model.TriggerPoint;
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
import click.kamil.springstatemachineexporter.analysis.resolver.ConstantResolver;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jdt.core.dom.*;
import java.util.*;
@Slf4j
public class CallGraphBuilder {
private final CodebaseContext context;
private final ConstantResolver constantResolver;
private String currentMethodFqn;
private Map<String, List<CallEdge>> graph;
@lombok.Data
private static class CallEdge {
private final String targetMethod;
private final List<String> arguments;
}
public CallGraphBuilder(CodebaseContext context) {
this.context = context;
this.constantResolver = new ConstantResolver();
}
public List<CallChain> findChains(List<EntryPoint> entryPoints, List<TriggerPoint> triggers) {
Map<String, List<CallEdge>> callGraph = buildCallGraph();
List<CallChain> chains = new ArrayList<>();
for (EntryPoint ep : entryPoints) {
String startMethod = ep.getClassName() + "." + ep.getMethodName();
boolean foundAny = false;
for (TriggerPoint tp : triggers) {
String targetMethod = tp.getClassName() + "." + tp.getMethodName();
List<String> path = findPath(startMethod, targetMethod, callGraph, new HashSet<>());
if (path != null) {
foundAny = true;
TriggerPoint resolvedTp = resolveTriggerPointParameters(tp, path, callGraph);
String contextMachineId = extractContextMachineId(path, callGraph);
chains.add(CallChain.builder()
.entryPoint(ep)
.triggerPoint(resolvedTp)
.methodChain(path)
.contextMachineId(contextMachineId)
.build());
}
}
if (!foundAny && log.isDebugEnabled()) {
log.debug("Entry point {} ({}) did not reach any trigger points. Graph nodes available: {}", ep.getName(), startMethod, callGraph.keySet());
}
}
return chains;
}
private TriggerPoint resolveTriggerPointParameters(TriggerPoint tp, List<String> path, Map<String, List<CallEdge>> callGraph) {
if (path.size() < 2) return tp;
String event = tp.getEvent();
if (event == null || event.isEmpty() || event.contains("\"")) return tp;
String currentParamName = event;
String resolvedValue = event;
String methodSuffix = "";
// Extract method calls like .getType() so we can trace the base parameter
int dotIndex = currentParamName.indexOf('.');
if (dotIndex > 0 && dotIndex + 1 < currentParamName.length()) {
char nextChar = currentParamName.charAt(dotIndex + 1);
if (Character.isLowerCase(nextChar)) {
methodSuffix = currentParamName.substring(dotIndex);
currentParamName = currentParamName.substring(0, dotIndex);
}
}
// Walk backwards up the call chain
for (int i = path.size() - 1; i > 0; i--) {
String target = path.get(i);
String caller = path.get(i - 1);
// Find parameter index in target method
int paramIndex = getParameterIndex(target, currentParamName);
if (paramIndex < 0) {
// Not a parameter. Maybe it's a local variable initialized from a parameter or method call?
String tracedVar = traceLocalVariable(target, currentParamName);
if (tracedVar != null && !tracedVar.equals(currentParamName)) {
// Extract method calls like .getType() from the traced variable
int dotIdx = tracedVar.indexOf('.');
if (dotIdx > 0 && dotIdx + 1 < tracedVar.length() && Character.isLowerCase(tracedVar.charAt(dotIdx + 1))) {
methodSuffix = tracedVar.substring(dotIdx) + methodSuffix;
tracedVar = tracedVar.substring(0, dotIdx);
}
currentParamName = tracedVar;
resolvedValue = tracedVar + methodSuffix;
paramIndex = getParameterIndex(target, currentParamName);
}
}
if (paramIndex < 0) {
break; // Parameter name changed or not found, stop tracing
}
// Find the edge from caller to target to get the argument passed
List<CallEdge> edges = callGraph.get(caller);
boolean found = false;
if (edges != null) {
for (CallEdge edge : edges) {
if (edge.getTargetMethod().equals(target) || isHeuristicMatch(edge.getTargetMethod(), target)) {
if (paramIndex < edge.getArguments().size()) {
String arg = edge.getArguments().get(paramIndex);
if (arg != null) {
// If the argument passed has a method call, extract it
int dotIdx = arg.indexOf('.');
if (dotIdx > 0 && dotIdx + 1 < arg.length() && Character.isLowerCase(arg.charAt(dotIdx + 1))) {
methodSuffix = arg.substring(dotIdx) + methodSuffix;
arg = arg.substring(0, dotIdx);
}
currentParamName = arg;
resolvedValue = arg + methodSuffix;
found = true;
break;
}
}
}
}
}
if (!found) break; // Could not map argument
}
// Final check on the entry method
String entryMethod = path.get(0);
int entryParamIndex = getParameterIndex(entryMethod, currentParamName);
if (entryParamIndex < 0) {
String tracedVar = traceLocalVariable(entryMethod, currentParamName);
if (tracedVar != null && !tracedVar.equals(currentParamName)) {
int dotIdx = tracedVar.indexOf('.');
if (dotIdx > 0 && dotIdx + 1 < tracedVar.length() && Character.isLowerCase(tracedVar.charAt(dotIdx + 1))) {
methodSuffix = tracedVar.substring(dotIdx) + methodSuffix;
tracedVar = tracedVar.substring(0, dotIdx);
}
currentParamName = tracedVar;
resolvedValue = tracedVar + methodSuffix;
}
}
List<String> polymorphicEvents = new ArrayList<>();
if (resolvedValue.matches(".*\\.[a-zA-Z0-9_]+\\(\\)")) {
String varName = resolvedValue.substring(0, resolvedValue.indexOf('.'));
String methodName = resolvedValue.substring(resolvedValue.indexOf('.') + 1, resolvedValue.indexOf('('));
// Resolve in the first method in the path where the variable might be declared
for (String methodFqn : path) {
String declaredType = getVariableDeclaredType(methodFqn, varName);
if (declaredType != null) {
System.out.println("DEEP TRACE: " + methodFqn + " " + varName + " -> " + declaredType);
List<String> typesToInspect = new ArrayList<>();
typesToInspect.add(declaredType);
typesToInspect.addAll(context.getImplementations(declaredType));
System.out.println("DEEP TRACE IMPLS: " + typesToInspect);
for (String type : typesToInspect) {
Set<String> visited = new HashSet<>();
// We must find the compilation unit to pass for simple names!
// Let's pass the first available CU for this class
TypeDeclaration baseTd = context.getTypeDeclaration(type);
CompilationUnit cuToUse = null;
if (baseTd != null && baseTd.getRoot() instanceof CompilationUnit) {
cuToUse = (CompilationUnit) baseTd.getRoot();
} else {
String entryClassName = methodFqn.substring(0, methodFqn.lastIndexOf('.'));
TypeDeclaration entryTd = context.getTypeDeclaration(entryClassName);
if (entryTd != null && entryTd.getRoot() instanceof CompilationUnit) {
cuToUse = (CompilationUnit) entryTd.getRoot();
}
}
List<String> constants = resolveMethodReturnConstant(type, methodName, 0, visited, cuToUse);
System.out.println("DEEP TRACE RETURN: " + type + " -> " + constants);
for (String constant : constants) {
if (!polymorphicEvents.contains(constant)) {
polymorphicEvents.add(constant);
}
}
}
break;
}
}
}
if (!resolvedValue.equals(event) || !polymorphicEvents.isEmpty()) {
return TriggerPoint.builder()
.event(resolvedValue)
.className(tp.getClassName())
.methodName(tp.getMethodName())
.sourceFile(tp.getSourceFile())
.lineNumber(tp.getLineNumber())
.polymorphicEvents(polymorphicEvents)
.build();
}
return tp;
}
private int getParameterIndex(String methodFqn, String paramName) {
if (methodFqn == null || !methodFqn.contains(".")) return -1;
String className = methodFqn.substring(0, methodFqn.lastIndexOf('.'));
String methodName = methodFqn.substring(methodFqn.lastIndexOf('.') + 1);
TypeDeclaration td = context.getTypeDeclaration(className);
if (td != null) {
MethodDeclaration md = context.findMethodDeclaration(td, methodName, true);
if (md != null) {
for (int i = 0; i < md.parameters().size(); i++) {
SingleVariableDeclaration svd = (SingleVariableDeclaration) md.parameters().get(i);
if (svd.getName().getIdentifier().equals(paramName)) {
return i;
}
}
}
}
return -1;
}
private String getVariableDeclaredType(String methodFqn, String varName) {
if (methodFqn == null || !methodFqn.contains(".")) return null;
String className = methodFqn.substring(0, methodFqn.lastIndexOf('.'));
String methodName = methodFqn.substring(methodFqn.lastIndexOf('.') + 1);
TypeDeclaration td = context.getTypeDeclaration(className);
if (td != null) {
MethodDeclaration md = context.findMethodDeclaration(td, methodName, true);
if (md != null) {
for (Object pObj : md.parameters()) {
SingleVariableDeclaration svd = (SingleVariableDeclaration) pObj;
if (svd.getName().getIdentifier().equals(varName)) {
return svd.getType().toString();
}
}
final String[] foundType = new String[1];
if (md.getBody() != null) {
md.getBody().accept(new ASTVisitor() {
@Override
public boolean visit(VariableDeclarationStatement node) {
for (Object fragObj : node.fragments()) {
VariableDeclarationFragment frag = (VariableDeclarationFragment) fragObj;
if (frag.getName().getIdentifier().equals(varName)) {
foundType[0] = node.getType().toString();
}
}
return super.visit(node);
}
});
}
return foundType[0];
}
}
return null;
}
private List<String> resolveMethodReturnConstant(String className, String methodName, int depth, Set<String> visited, CompilationUnit contextCu) {
if (depth > 20) return Collections.emptyList();
String fqn = className + "." + methodName;
if (!visited.add(fqn)) return Collections.emptyList();
List<String> constants = new ArrayList<>();
TypeDeclaration td = contextCu != null ? context.getTypeDeclaration(className, contextCu) : context.getTypeDeclaration(className);
if (td == null) {
System.out.println("DEEP TRACE FAILED TO FIND TD: " + className);
}
if (td != null) {
MethodDeclaration md = context.findMethodDeclaration(td, methodName, true);
if (md != null && md.getBody() != null) {
md.getBody().accept(new ASTVisitor() {
@Override
public boolean visit(ReturnStatement node) {
Expression retExpr = node.getExpression();
if (retExpr != null) {
boolean handled = false;
if (retExpr instanceof MethodInvocation mi) {
// Follow delegation first
String called = resolveCalledMethod(mi);
System.out.println("DEEP TRACE RESOLVED CALLED: " + called);
if (called != null && called.contains(".")) {
if (visited.contains(called)) {
handled = true;
} else {
String cName = called.substring(0, called.lastIndexOf('.'));
String mName = called.substring(called.lastIndexOf('.') + 1);
TypeDeclaration targetTd = contextCu != null ? context.getTypeDeclaration(cName, contextCu) : context.getTypeDeclaration(cName);
if (targetTd == null) targetTd = context.getTypeDeclaration(cName);
if (targetTd != null && context.findMethodDeclaration(targetTd, mName, true) != null) {
List<String> delegationResult = resolveMethodReturnConstant(cName, mName, depth + 1, visited, contextCu);
constants.addAll(delegationResult);
handled = true;
}
}
}
}
if (!handled) {
String val = constantResolver.resolve(retExpr, context);
if (val != null) {
if (val.startsWith("ENUM_SET:")) {
for (String eVal : val.substring(9).split(",")) {
constants.add(eVal.substring(eVal.lastIndexOf('.') + 1));
}
} else {
constants.add(val);
}
} else if (retExpr instanceof QualifiedName qn) {
constants.add(qn.toString());
} else if (retExpr instanceof SimpleName sn) {
constants.add(sn.toString());
}
}
}
return super.visit(node);
}
});
}
}
visited.remove(fqn);
return constants;
}
private String traceLocalVariable(String methodFqn, String varName) {
if (methodFqn == null || !methodFqn.contains(".")) return null;
String className = methodFqn.substring(0, methodFqn.lastIndexOf('.'));
String methodName = methodFqn.substring(methodFqn.lastIndexOf('.') + 1);
TypeDeclaration td = context.getTypeDeclaration(className);
if (td != null) {
MethodDeclaration md = context.findMethodDeclaration(td, methodName, true);
if (md != null && md.getBody() != null) {
final Expression[] initializer = new Expression[1];
md.getBody().accept(new ASTVisitor() {
@Override
public boolean visit(VariableDeclarationFragment node) {
if (node.getName().getIdentifier().equals(varName) && node.getInitializer() != null) {
initializer[0] = node.getInitializer();
}
return super.visit(node);
}
@Override
public boolean visit(Assignment node) {
if (node.getLeftHandSide() instanceof SimpleName asn && asn.getIdentifier().equals(varName)) {
initializer[0] = node.getRightHandSide();
}
return super.visit(node);
}
});
if (initializer[0] != null) {
Expression expr = traceVariable(initializer[0]);
if (expr instanceof MethodInvocation mi) {
// Unwrapper logic: If wrapper method is called, extract its arguments recursively
Expression innerMost = unwrapMethodInvocation(mi, 0);
if (innerMost instanceof MethodInvocation innerMi) {
if (innerMi.getExpression() instanceof SimpleName sn) {
return sn.getIdentifier() + "." + innerMi.getName().getIdentifier() + "()";
}
return innerMi.getName().getIdentifier() + "()";
}
if (innerMost instanceof SimpleName sn) {
return sn.getIdentifier();
}
return innerMost.toString();
}
if (expr instanceof SimpleName sn) {
return sn.getIdentifier();
}
return expr.toString();
}
}
}
return null;
}
private Expression unwrapMethodInvocation(MethodInvocation mi, int depth) {
if (depth > 5) return mi;
if (!mi.arguments().isEmpty()) {
Expression arg = (Expression) mi.arguments().get(0);
if (arg instanceof MethodInvocation innerMi) {
return unwrapMethodInvocation(innerMi, depth + 1);
}
return arg;
}
return mi;
}
private String extractContextMachineId(List<String> path, Map<String, List<CallEdge>> callGraph) {
for (String node : path) {
List<CallEdge> edges = callGraph.get(node);
if (edges != null) {
for (CallEdge edge : edges) {
String target = edge.getTargetMethod();
if (target != null && (target.contains(".restore") || target.contains(".read"))) {
// Persister signatures usually like: restore(stateMachine, contextObj)
if (edge.getArguments().size() >= 2) {
return edge.getArguments().get(1); // The contextObj / machineId
}
}
}
}
}
return null;
}
private MethodDeclaration findEnclosingMethod(ASTNode node) {
ASTNode parent = node.getParent();
while (parent != null && !(parent instanceof MethodDeclaration)) {
parent = parent.getParent();
}
return (MethodDeclaration) parent;
}
private Map<String, List<CallEdge>> buildCallGraph() {
graph = new HashMap<>();
for (CompilationUnit cu : context.getCompilationUnits()) {
cu.accept(new ASTVisitor() {
@Override
public boolean visit(MethodInvocation node) {
MethodDeclaration md = findEnclosingMethod(node);
if (md != null) {
TypeDeclaration td = findEnclosingType(md);
if (td != null) {
String currentMethodFqn = context.getFqn(td) + "." + md.getName().getIdentifier();
List<String> calledMethods = resolveCalledMethodsPolymorphic(node);
List<String> args = resolveArguments(node.arguments());
for (String calledMethod : calledMethods) {
graph.computeIfAbsent(currentMethodFqn, k -> new ArrayList<>()).add(new CallEdge(calledMethod, args));
}
for (Object argObj : node.arguments()) {
if (argObj instanceof ExpressionMethodReference emr) {
String typeName = emr.getExpression().toString();
if ("this".equals(typeName) || "super".equals(typeName)) {
TypeDeclaration td2 = findEnclosingType(node);
if (td2 != null) {
String refMethod = resolveMethodInType(td2, emr.getName().getIdentifier());
if (refMethod != null) {
graph.computeIfAbsent(currentMethodFqn, k -> new ArrayList<>()).add(new CallEdge(refMethod, args));
}
}
} else {
String fallbackTypeFqn = null;
ITypeBinding binding = emr.getExpression().resolveTypeBinding();
if (binding != null) {
fallbackTypeFqn = binding.getQualifiedName();
} else if (emr.getExpression() instanceof SimpleName sn) {
fallbackTypeFqn = resolveReceiverTypeFallback(sn);
}
if (fallbackTypeFqn != null) {
String calledMethod = fallbackTypeFqn + "." + emr.getName().getIdentifier();
graph.computeIfAbsent(currentMethodFqn, k -> new ArrayList<>()).add(new CallEdge(calledMethod, args));
List<String> impls = context.getImplementations(fallbackTypeFqn);
for (String impl : impls) {
graph.computeIfAbsent(currentMethodFqn, k -> new ArrayList<>()).add(new CallEdge(impl + "." + emr.getName().getIdentifier(), args));
}
}
}
}
}
}
}
return super.visit(node);
}
@Override
public boolean visit(SuperMethodInvocation node) {
MethodDeclaration md = findEnclosingMethod(node);
if (md != null) {
TypeDeclaration tdOuter = findEnclosingType(md);
if (tdOuter != null) {
String currentMethodFqn = context.getFqn(tdOuter) + "." + md.getName().getIdentifier();
String methodName = node.getName().getIdentifier();
TypeDeclaration td = findEnclosingType(node);
if (td != null) {
String superFqn = context.getSuperclassFqn(td);
if (superFqn != null) {
TypeDeclaration superTd = context.getTypeDeclaration(superFqn);
String calledMethod = null;
if (superTd != null) {
calledMethod = resolveMethodInType(superTd, methodName);
}
if (calledMethod == null) {
calledMethod = superFqn + "." + methodName;
}
List<String> args = resolveArguments(node.arguments());
graph.computeIfAbsent(currentMethodFqn, k -> new ArrayList<>()).add(new CallEdge(calledMethod, args));
}
}
}
}
return super.visit(node);
}
});
}
return graph;
}
private List<String> resolveArguments(List<?> astArguments) {
List<String> args = new ArrayList<>();
for (Object argObj : astArguments) {
Expression expr = (Expression) argObj;
// Extract from lambda
if (expr instanceof LambdaExpression le) {
ASTNode body = le.getBody();
if (body instanceof Expression bodyExpr) {
expr = bodyExpr;
} else if (body instanceof Block block) {
for (Object stmtObj : block.statements()) {
if (stmtObj instanceof ReturnStatement rs && rs.getExpression() != null) {
expr = rs.getExpression();
break;
}
}
}
}
if (expr instanceof ExpressionMethodReference emr) {
TypeDeclaration td = findEnclosingType(expr);
if (td != null) {
MethodDeclaration md = context.findMethodDeclaration(td, emr.getName().getIdentifier(), true);
if (md != null && md.getBody() != null) {
for (Object stmtObj : md.getBody().statements()) {
if (stmtObj instanceof ReturnStatement rs && rs.getExpression() != null) {
expr = rs.getExpression();
break;
}
}
}
}
}
// Extract from constructor args (e.g., new CustomMessage(OrderEvent.PROCESS, ...))
Expression tracedExpr = traceVariable(expr);
if (tracedExpr instanceof QualifiedName || tracedExpr instanceof ClassInstanceCreation || tracedExpr instanceof StringLiteral || tracedExpr instanceof NumberLiteral) {
expr = tracedExpr; // Only accept trace if it resolves to a pure constant/primitive/constructor
}
if (expr instanceof ClassInstanceCreation cic && !cic.arguments().isEmpty()) {
Expression firstArg = (Expression) cic.arguments().get(0);
String resolved = constantResolver.resolve(firstArg, context);
if (resolved != null) {
expr = firstArg; // Only unwrap if it's actually a constant
}
}
String val = constantResolver.resolve(expr, context);
if (val == null) {
val = expr.toString(); // Fallback to raw string (handles Enums, 'new Class()', etc)
}
args.add(val);
}
return args;
}
private List<String> resolveCalledMethodsPolymorphic(MethodInvocation node) {
String baseCalled = resolveCalledMethod(node);
if (baseCalled == null) return Collections.emptyList();
List<String> allResolved = new ArrayList<>();
allResolved.add(baseCalled);
if (baseCalled.contains(".")) {
String className = baseCalled.substring(0, baseCalled.lastIndexOf('.'));
String methodName = baseCalled.substring(baseCalled.lastIndexOf('.') + 1);
List<String> impls = context.getImplementations(className);
for (String impl : impls) {
allResolved.add(impl + "." + methodName);
}
}
return allResolved;
}
private String resolveCalledMethod(MethodInvocation node) {
Expression receiver = node.getExpression();
String methodName = node.getName().getIdentifier();
if (receiver == null) {
TypeDeclaration td = findEnclosingType(node);
if (td != null) {
return resolveMethodInType(td, methodName);
}
return null;
}
ITypeBinding binding = receiver.resolveTypeBinding();
if (binding != null) {
return binding.getQualifiedName() + "." + methodName;
}
if (receiver instanceof ThisExpression) {
TypeDeclaration td = findEnclosingType(node);
if (td != null) {
return context.getFqn(td) + "." + methodName;
}
}
if (receiver instanceof SimpleName sn) {
String fallbackTypeFqn = resolveReceiverTypeFallback(sn);
if (fallbackTypeFqn != null) {
return fallbackTypeFqn + "." + methodName;
}
String receiverName = sn.getIdentifier();
return receiverName + "." + methodName;
}
return null;
}
private String resolveReceiverTypeFallback(SimpleName receiverNameNode) {
String varName = receiverNameNode.getIdentifier();
// 1. Check local variables in enclosing method
MethodDeclaration enclosingMethod = findEnclosingMethod(receiverNameNode);
if (enclosingMethod != null) {
// Check parameters
for (Object paramObj : enclosingMethod.parameters()) {
SingleVariableDeclaration svd = (SingleVariableDeclaration) paramObj;
if (svd.getName().getIdentifier().equals(varName)) {
return resolveTypeToFqn(svd.getType(), receiverNameNode);
}
}
// Check method body (local variables)
if (enclosingMethod.getBody() != null) {
Type[] foundType = new Type[1];
enclosingMethod.getBody().accept(new ASTVisitor() {
@Override
public boolean visit(VariableDeclarationStatement node) {
for (Object fragObj : node.fragments()) {
VariableDeclarationFragment frag = (VariableDeclarationFragment) fragObj;
if (frag.getName().getIdentifier().equals(varName)) {
foundType[0] = node.getType();
}
}
return super.visit(node);
}
});
if (foundType[0] != null) {
return resolveTypeToFqn(foundType[0], receiverNameNode);
}
}
}
// 2. Check fields in enclosing class
TypeDeclaration enclosingType = findEnclosingType(receiverNameNode);
if (enclosingType != null) {
for (FieldDeclaration field : enclosingType.getFields()) {
for (Object fragObj : field.fragments()) {
VariableDeclarationFragment frag = (VariableDeclarationFragment) fragObj;
if (frag.getName().getIdentifier().equals(varName)) {
return resolveTypeToFqn(field.getType(), receiverNameNode);
}
}
}
}
return null;
}
private String resolveTypeToFqn(Type type, ASTNode contextNode) {
if (type == null) return null;
String simpleName;
if (type.isSimpleType()) {
simpleName = ((SimpleType) type).getName().getFullyQualifiedName();
} else if (type.isParameterizedType()) {
return resolveTypeToFqn(((ParameterizedType) type).getType(), contextNode);
} else {
simpleName = type.toString();
}
CompilationUnit cu = (CompilationUnit) contextNode.getRoot();
TypeDeclaration td = context.getTypeDeclaration(simpleName, cu);
if (td != null) {
return context.getFqn(td);
}
// Fallback to import matching if CodebaseContext doesn't know it (e.g., external library)
for (Object impObj : cu.imports()) {
ImportDeclaration imp = (ImportDeclaration) impObj;
String impName = imp.getName().getFullyQualifiedName();
if (impName.endsWith("." + simpleName)) {
return impName;
}
}
return simpleName;
}
private String resolveMethodInType(TypeDeclaration td, String methodName) {
MethodDeclaration md = context.findMethodDeclaration(td, methodName, true);
if (md != null) {
TypeDeclaration declaringTd = findEnclosingType(md);
return context.getFqn(declaringTd) + "." + methodName;
}
return null;
}
private List<String> findPath(String start, String target, Map<String, List<CallEdge>> graph, Set<String> visited) {
if (start.equals(target)) return new ArrayList<>(List.of(start));
if (!visited.add(start)) return null; // Path-scoped cycle detection
List<CallEdge> neighbors = graph.get(start);
if (neighbors != null) {
for (CallEdge edge : neighbors) {
String neighbor = edge.getTargetMethod();
if (neighbor.equals(target) || isHeuristicMatch(neighbor, target)) {
visited.remove(start);
return new ArrayList<>(List.of(start, target));
}
List<String> path = findPath(neighbor, target, graph, visited);
if (path != null) {
path.add(0, start);
visited.remove(start);
return path;
}
}
}
if (log.isDebugEnabled()) {
log.debug("Path search dead-end at {} when looking for {}", start, target);
}
visited.remove(start);
return null;
}
private boolean isHeuristicMatch(String neighbor, String target) {
if (target.endsWith("." + neighbor)) return true;
String simpleTarget = target.contains(".") ? target.substring(target.lastIndexOf('.') + 1) : target;
String simpleNeighbor = neighbor.contains(".") ? neighbor.substring(neighbor.lastIndexOf('.') + 1) : neighbor;
return simpleNeighbor.equals(simpleTarget);
}
private TypeDeclaration findEnclosingType(ASTNode node) {
ASTNode parent = node.getParent();
while (parent != null && !(parent instanceof TypeDeclaration)) {
parent = parent.getParent();
}
return (TypeDeclaration) parent;
}
private Expression traceVariable(Expression expr) {
if (expr instanceof SimpleName sn) {
String varName = sn.getIdentifier();
MethodDeclaration enclosingMethod = findEnclosingMethod(expr);
if (enclosingMethod != null) {
final Expression[] initializer = new Expression[1];
enclosingMethod.accept(new ASTVisitor() {
@Override
public boolean visit(VariableDeclarationFragment node) {
if (node.getName().getIdentifier().equals(varName) && node.getInitializer() != null) {
initializer[0] = node.getInitializer();
}
return super.visit(node);
}
@Override
public boolean visit(Assignment node) {
if (node.getLeftHandSide() instanceof SimpleName asn && asn.getIdentifier().equals(varName)) {
initializer[0] = node.getRightHandSide();
}
return super.visit(node);
}
});
if (initializer[0] != null) {
return traceVariable(initializer[0]);
}
}
}
return expr;
}
}

View File

@@ -0,0 +1,679 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>State Machine Explorer - click.kamil.maven.core.MavenOrderStateMachine</title>
<!-- Popper and Tippy for tooltips -->
<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>
<link rel="stylesheet" href="https://unpkg.com/tippy.js@6/animations/scale.css"/>
<!-- SVG Pan & Zoom -->
<script src="https://cdn.jsdelivr.net/npm/svg-pan-zoom@3.6.1/dist/svg-pan-zoom.min.js"></script>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;900&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {
--sidebar-bg: #ffffff;
--main-bg: #f8fafc;
--accent: #ef4444;
--primary: #3b82f6;
--text: #0f172a;
--text-muted: #64748b;
--border: #e2e8f0;
}
body {
margin: 0;
display: flex;
height: 100vh;
font-family: 'Inter', -apple-system, sans-serif;
background: var(--main-bg);
color: var(--text);
overflow: hidden;
}
#sidebar {
width: 480px;
min-width: 350px;
max-width: 900px;
background: var(--sidebar-bg);
border-right: 2px solid var(--border);
display: flex;
flex-direction: column;
box-shadow: 10px 0 15px rgba(0,0,0,0.02);
z-index: 10;
overflow-x: hidden;
resize: horizontal;
position: relative;
transition: width 0.3s ease, min-width 0.3s ease, padding 0.3s ease;
}
#sidebar.collapsed {
width: 0 !important;
min-width: 0 !important;
border-right: none;
padding: 0;
overflow: hidden;
resize: none;
}
#toggle-sidebar {
position: absolute;
top: 20px;
left: 20px;
z-index: 50;
background: #fff;
border: 1px solid var(--border);
border-radius: 8px;
padding: 8px;
cursor: pointer;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
}
#toggle-sidebar:hover {
background: #f8fafc;
border-color: var(--primary);
}
#toggle-sidebar svg {
width: 20px;
height: 20px;
fill: none;
stroke: var(--text-muted);
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
#sidebar::after {
content: '⋮';
position: absolute;
right: 2px; top: 50%;
transform: translateY(-50%);
color: var(--border);
font-size: 1.2rem;
pointer-events: none;
}
.sidebar-header {
padding: 30px 30px 10px;
}
header h1 { font-weight: 900; font-size: 1.6rem; color: var(--text); margin: 0 0 5px 0; letter-spacing: -0.5px; }
header p { font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; color: var(--text-muted); margin: 0 0 15px 0; opacity: 0.7; }
.tabs {
display: flex;
padding: 0 30px;
border-bottom: 1px solid var(--border);
gap: 20px;
}
.tab {
padding: 10px 0;
font-size: 0.85rem;
font-weight: 600;
color: var(--text-muted);
cursor: pointer;
position: relative;
transition: color 0.2s;
}
.tab:hover { color: var(--text); }
.tab.active { color: var(--primary); }
.tab.active::after {
content: '';
position: absolute;
bottom: -1px; left: 0; right: 0;
height: 2px;
background: var(--primary);
}
.tab-content {
flex-grow: 1;
padding: 25px 30px;
overflow-y: auto;
display: none;
}
.tab-content.active { display: block; }
.ep-card, .flow-card {
padding: 18px;
background: #fff;
border: 1px solid var(--border);
border-radius: 14px;
margin-bottom: 15px;
cursor: pointer;
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 1px 3px rgba(0,0,0,0.04);
position: relative;
word-break: break-all;
overflow-wrap: anywhere;
}
.ep-card:hover, .flow-card:hover {
border-color: var(--primary);
transform: translateX(5px);
box-shadow: 0 15px 30px -10px rgba(59, 130, 246, 0.15);
}
.ep-type {
font-size: 0.6rem;
font-weight: 900;
padding: 3px 8px;
border-radius: 6px;
display: inline-block;
margin-bottom: 10px;
text-transform: uppercase;
letter-spacing: 0.8px;
}
.type-rest { background: #eff6ff; color: #1d4ed8; }
.type-custom { background: #fef2f2; color: #b91c1c; }
.type-jms { background: #f5f3ff; color: #7c3aed; }
.type-sqs { background: #fff7ed; color: #ea580c; }
.type-sns { background: #fff1f2; color: #e11d48; }
.type-kafka { background: #fefce8; color: #854d0e; }
.type-rabbit { background: #f0fdf4; color: #166534; }
.ep-name, .flow-name { font-weight: 700; font-size: 0.95rem; margin-bottom: 6px; color: var(--text); }
.ep-fqn, .flow-desc { font-family: 'Inter', sans-serif; font-size: 0.75rem; color: var(--text-muted); opacity: 0.9; line-height: 1.4; }
#main { flex-grow: 1; position: relative; background: var(--main-bg); overflow: hidden; }
#svg-container {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
display: flex;
align-items: center;
justify-content: center;
}
svg {
width: 100%;
height: 100%;
display: block;
}
/* SVG Interactivity Styles */
svg a { text-decoration: none !important; }
.active-path {
stroke: var(--accent) !important;
stroke-width: 2.5px !important;
filter: drop-shadow(0 0 8px rgba(239, 68, 68, 0.3));
transition: all 0.3s;
}
.active-path text, a.active-path text {
fill: #000 !important;
font-weight: 900 !important;
paint-order: stroke;
stroke: #fff;
stroke-width: 3.5px;
}
.dimmed {
opacity: 0.2 !important;
filter: grayscale(1);
transition: opacity 0.4s ease;
pointer-events: none;
}
/* Tippy Styling */
.tippy-box[data-theme~='modern'] {
background-color: #fff;
color: var(--text);
box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
border: 1px solid var(--border);
border-radius: 16px;
padding: 0;
max-width: 550px !important;
}
.tooltip-content {
padding: 20px;
max-width: 500px;
word-break: break-word;
overflow-wrap: anywhere;
}
.payload-box {
background: #0f172a;
color: #e2e8f0;
border-radius: 8px;
padding: 12px;
font-family: 'JetBrains Mono', monospace;
font-size: 0.75rem;
line-height: 1.5;
margin-top: 10px;
}
.payload-param {
margin-bottom: 4px;
}
.payload-param:last-child { margin-bottom: 0; }
</style>
</head>
<body>
<div id="sidebar">
<div class="sidebar-header">
<header>
<h1>Explorer</h1>
<p>click.kamil.maven.core.MavenOrderStateMachine</p>
</header>
</div>
<div class="tabs">
<div class="tab active" data-tab="explorer">Explorer</div>
<div class="tab" data-tab="flows">Business Flows</div>
</div>
<div id="tab-explorer" class="tab-content active">
<div id="ep-list"></div>
</div>
<div id="tab-flows" class="tab-content">
<div id="flow-list"></div>
</div>
</div>
<div id="main">
<button id="toggle-sidebar" aria-label="Toggle Sidebar" title="Toggle Sidebar">
<svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16"></path></svg>
</button>
<div id="svg-container">
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="100%" preserveAspectRatio="xMidYMid meet" version="1.1" viewBox="0 0 187 255" width="100%" zoomAndPan="magnify"><defs/><g><ellipse cx="35.5208" cy="34.375" fill="#222222" rx="11.4583" ry="11.4583" style="stroke:#222222;stroke-width:1.1458333333333333;"/><rect fill="#FFFFFF" height="45.8333" rx="14.3229" ry="14.3229" style="stroke:#94A3B8;stroke-width:1.1458333333333333;" width="57.2917" x="6.875" y="101.9792"/><text fill="#000000" font-family="Inter" font-size="10.3125" font-weight="bold" lengthAdjust="spacing" textLength="21.7708" x="24.6354" y="128.7932">INIT</text><rect fill="#FFFFFF" height="45.8333" rx="14.3229" ry="14.3229" style="stroke:#94A3B8;stroke-width:1.1458333333333333;" width="57.2917" x="6.875" y="202.8125"/><text fill="#000000" font-family="Inter" font-size="10.3125" font-weight="bold" lengthAdjust="spacing" textLength="27.5" x="21.7708" y="229.6266">BUSY</text><rect fill="#FFFFFF" height="45.8333" rx="14.3229" ry="14.3229" style="stroke:#94A3B8;stroke-width:1.1458333333333333;" width="57.2917" x="68.75" y="13.75"/><text fill="#000000" font-family="Inter" font-size="10.3125" font-weight="bold" lengthAdjust="spacing" textLength="29.7917" x="82.5" y="40.5641">DONE</text><ellipse cx="97.3958" cy="123.75" fill="none" rx="12.6042" ry="12.6042" style="stroke:#222222;stroke-width:1.1458333333333333;"/><ellipse cx="97.3958" cy="123.75" fill="#222222" rx="6.875" ry="6.875" style="stroke:#222222;stroke-width:1.1458333333333333;"/><polygon fill="#CBD5E1" points="35.5208,101.6748,40.1042,91.3623,35.5208,95.9456,30.9375,91.3623,35.5208,101.6748" style="stroke:#CBD5E1;stroke-width:1.1458333333333333;"/><path d="M35.5208,50.4929 C35.5208,63.9394 35.5208,78.5626 35.5208,94.7998 " fill="none" style="stroke:#CBD5E1;stroke-width:1.1458333333333333;"/><polygon fill="#1E90FF" points="35.5208,202.7749,40.1042,192.4624,35.5208,197.0457,30.9375,192.4624,35.5208,202.7749" style="stroke:#1E90FF;stroke-width:1.1458333333333333;"/><path d="M35.5208,147.9113 C35.5208,164.2413 35.5208,179.5846 35.5208,195.8999 " fill="none" style="stroke:#1E90FF;stroke-width:2.2916666666666665;"/><a href="#link_ORDER_EVENT" target="_self" title="#link_ORDER_EVENT" xlink:actuate="onRequest" xlink:href="#link_ORDER_EVENT" xlink:show="new" xlink:title="#link_ORDER_EVENT" xlink:type="simple"><text fill="#0000FF" font-family="JetBrains Mono" font-size="9.1667" lengthAdjust="spacing" text-decoration="underline" textLength="142.0833" x="36.6667" y="178.4456">ORDER_EVENT / loggingAction()</text></a><polygon fill="#CBD5E1" points="97.3958,110.7767,101.9792,100.4642,97.3958,105.0475,92.8125,100.4642,97.3958,110.7767" style="stroke:#CBD5E1;stroke-width:1.1458333333333333;"/><path d="M97.3958,59.9435 C97.3958,76.0566 97.3958,90.453 97.3958,103.9017 " fill="none" style="stroke:#CBD5E1;stroke-width:1.1458333333333333;"/><!--SRC=[RP5lJy8m4CRVzrESuOqQYSm_2HX20Z8IZ881D364a6CzjeQkNTeYJkDtjmF4XVYgrz-rzpntTv8PZ5C4YRbUEx0fELJ8BFcOCZJej06b5R54S09ACvS39niPaJcXrGvRHuQqopDYTYLKyI_r41t15mFeOBIAZLuhVg-bhxT9XAE2QyF9x5YbSOFNY_g1JX8HhHHP2u5dFQtS05E2ll9IUp0MdmIDtulB9S52I-x1QATb51cugddmZ9mB5VjQtsM72NAzAVWIfIrxRnkZDmVH1t8TWq9PUD9A__TiQwL-dDbt5YtuBGN7oNA3VocU2GY2MjdaU_mer6g29lPBcLkIIyQcvpEeLblG7_GdZB7YWEgq4eIDMgztKKnXvhETb_4RD9lquMUcKBPQnMK-77N3qJny3GSJJ-vWEgr8Br3cK8ulGUeuzbDgHyN6JyzcCyQwmq6uTU2T_000]--></g></svg>
</div>
</div>
<script id="metadata-json" type="application/json">
{
"name" : "click.kamil.maven.core.MavenOrderStateMachine",
"states" : [ {
"rawName" : "DONE",
"fullIdentifier" : "DONE"
}, {
"rawName" : "\"INIT\"",
"fullIdentifier" : "INIT"
}, {
"rawName" : "\"BUSY\"",
"fullIdentifier" : "BUSY"
}, {
"rawName" : "INIT",
"fullIdentifier" : "INIT"
} ],
"transitions" : [ {
"type" : "EXTERNAL",
"sourceStates" : [ {
"rawName" : "\"INIT\"",
"fullIdentifier" : "INIT"
} ],
"targetStates" : [ {
"rawName" : "\"BUSY\"",
"fullIdentifier" : "BUSY"
} ],
"event" : "ORDER_EVENT",
"guard" : null,
"actions" : [ {
"expression" : "loggingAction()",
"isLambda" : false,
"internalLogic" : "context -> {\n System.out.println(\"LOG: State transition in progress...\");\n}\n",
"lineNumber" : 23
} ],
"order" : null
} ],
"startStates" : [ "INIT" ],
"endStates" : [ "DONE" ],
"renderChoicesAsDiamonds" : true,
"flows" : [ ],
"metadata" : {
"triggers" : [ {
"event" : "ORDER_EVENT",
"className" : "click.kamil.maven.core.OrderService",
"methodName" : "onMessage",
"sourceModule" : null,
"stateMachineId" : null,
"lineNumber" : 34
} ],
"entryPoints" : [ {
"type" : "REST",
"name" : "POST /reactive/order",
"className" : "click.kamil.maven.api.ReactiveOrderApi",
"methodName" : "orderRoutes",
"metadata" : {
"path" : "/reactive/order",
"verb" : "POST",
"style" : "WebFlux Functional"
},
"parameters" : [ ]
}, {
"type" : "JMS",
"name" : "JMS: order.queue",
"className" : "click.kamil.maven.api.JmsOrderListener",
"methodName" : "onMessage",
"metadata" : {
"protocol" : "JMS",
"destination" : "order.queue"
},
"parameters" : [ {
"name" : "message",
"type" : "String",
"annotations" : [ ]
} ]
} ],
"callChains" : [ ],
"properties" : {
"default" : { }
}
}
}
</script>
<script>
const metadata = JSON.parse(document.getElementById('metadata-json').textContent);
let panZoomInstance;
document.addEventListener('DOMContentLoaded', () => {
const svg = document.querySelector('#svg-container svg');
panZoomInstance = svgPanZoom(svg, { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true });
document.getElementById('toggle-sidebar').addEventListener('click', () => {
const sidebar = document.getElementById('sidebar');
sidebar.classList.toggle('collapsed');
// Re-center SVG pan-zoom after transition
setTimeout(() => {
if (panZoomInstance) {
panZoomInstance.resize();
panZoomInstance.center();
}
}, 300);
});
setupTabs();
populateSidebar();
populateFlows();
attachInteractivity();
});
function setupTabs() {
const flows = metadata.flows || [];
if (flows.length === 0) {
document.querySelector('.tabs').style.display = 'none';
document.querySelector('.tab-content[data-tab="flows"]')?.remove();
return;
}
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.tab, .tab-content').forEach(el => el.classList.remove('active'));
tab.classList.add('active');
document.getElementById('tab-' + tab.dataset.tab).classList.add('active');
});
});
}
function populateSidebar() {
const list = document.getElementById('ep-list');
const entryPoints = metadata.metadata.entryPoints || [];
const machineEvents = new Set(metadata.transitions.map(t => t.event).filter(Boolean));
entryPoints.forEach(ep => {
// Quality Filter: Hide if it doesn't trigger a machine event
const chains = (metadata.metadata.callChains || []).filter(c =>
c.entryPoint.className === ep.className &&
c.entryPoint.methodName === ep.methodName &&
machineEvents.has(c.triggerPoint.event)
);
if (chains.length === 0) return;
const card = document.createElement('div');
card.className = 'ep-card';
card.innerHTML = `
<div class="ep-type type-${ep.type.toLowerCase()}">${ep.type}</div>
<div class="ep-name">${ep.name}</div>
<div class="ep-fqn">${ep.className}.${ep.methodName}</div>
`;
card.onmouseenter = () => highlightEntryPoint(ep);
card.onmouseleave = clearHighlights;
list.appendChild(card);
});
}
function populateFlows() {
const list = document.getElementById('flow-list');
const flows = metadata.flows || [];
if (flows.length === 0) {
list.innerHTML = '<p style="color:var(--text-muted); font-size:0.8rem; font-style:italic;">No business flows defined.</p>';
return;
}
flows.forEach(flow => {
const card = document.createElement('div');
card.className = 'flow-card';
card.innerHTML = `
<div class="flow-name">${flow.name}</div>
<div class="flow-desc">${flow.description}</div>
`;
card.onmouseenter = () => highlightFlow(flow);
card.onmouseleave = clearHighlights;
list.appendChild(card);
});
}
function highlightEntryPoint(ep) {
clearHighlights();
const machineEvents = new Set(metadata.transitions.map(t => t.event).filter(Boolean));
const chains = metadata.metadata.callChains || [];
const relevantEvents = chains
.filter(c => c.entryPoint.className === ep.className && c.entryPoint.methodName === ep.methodName && machineEvents.has(c.triggerPoint.event))
.map(c => c.triggerPoint.event);
if (relevantEvents.length === 0) return;
highlightEvents(relevantEvents);
}
function highlightFlow(flow) {
clearHighlights();
if (!flow.steps || flow.steps.length === 0) return;
highlightEvents(flow.steps);
}
function highlightEvents(steps) {
const svg = document.querySelector('#svg-container svg');
// Dim everything first
svg.querySelectorAll('path, rect, circle, ellipse, text, polygon').forEach(el => {
el.classList.add('dimmed');
});
steps.forEach(step => {
let linkId = "";
if (step.includes("->")) {
// Named Choice Branch: "SRC->TGT"
const parts = step.split("->");
linkId = "#link_anon_" + normalize(parts[0]) + "_" + normalize(parts[1]);
} else {
// Standard Event
linkId = "#link_" + normalize(step);
}
svg.querySelectorAll('a').forEach(link => {
const href = link.getAttribute('xlink:href') || link.getAttribute('href');
if (href === linkId) {
highlightLinkGroup(link);
}
});
});
// Un-dim all state nodes for context
svg.querySelectorAll('rect, circle, ellipse, polygon').forEach(el => {
const isChoice = el.tagName === 'polygon' && el.points?.numberOfItems === 4;
if (isChoice || ['rect', 'circle', 'ellipse'].includes(el.tagName)) {
el.classList.remove('dimmed');
let next = el.nextElementSibling;
while(next && next.tagName === 'text') {
next.classList.remove('dimmed');
next = next.nextElementSibling;
}
}
});
}
function highlightLinkGroup(link) {
link.classList.add('active-path');
link.querySelectorAll('*').forEach(child => child.classList.remove('dimmed'));
// Find path and polygon immediately before the <a> tag (interleaved)
let prev = link.previousElementSibling;
let foundPath = false;
let foundPolygon = false;
while (prev) {
if (prev.tagName === 'path' && !foundPath) {
prev.classList.remove('dimmed');
prev.classList.add('active-path');
foundPath = true;
} else if (prev.tagName === 'polygon' && !foundPolygon && prev.points?.numberOfItems !== 4) {
prev.classList.remove('dimmed');
prev.classList.add('active-path');
foundPolygon = true;
} else if (['rect', 'circle', 'ellipse'].includes(prev.tagName) ||
(prev.tagName === 'polygon' && prev.points?.numberOfItems === 4)) {
// Hit a state node, stop traversal
break;
}
if (foundPath && foundPolygon) break;
prev = prev.previousElementSibling;
}
}
function clearHighlights() {
document.querySelectorAll('.dimmed, .active-path').forEach(el => {
el.classList.remove('dimmed', 'active-path');
});
}
function attachInteractivity() {
const svg = document.querySelector('#svg-container svg');
const transitions = metadata.transitions || [];
svg.querySelectorAll('a').forEach(link => {
const href = link.getAttribute('xlink:href') || link.getAttribute('href');
if (!href || !href.startsWith('#link_')) return;
const linkId = href.replace('#link_', '');
const isAnon = linkId.startsWith('anon_');
let metaTrans = null;
if (isAnon) {
metaTrans = transitions.find(t =>
!t.event &&
"anon_" + normalize(t.sourceStates[0].fullIdentifier) + "_" + normalize(t.targetStates[0].fullIdentifier) === linkId
);
} else {
metaTrans = transitions.find(t => normalize(t.event) === linkId);
}
if (metaTrans || isAnon) {
link.style.cursor = 'pointer';
const setupTippy = (el) => {
tippy(el, {
content: createTooltip(isAnon ? "Internal logic" : linkId, metaTrans),
allowHTML: true,
theme: 'modern',
interactive: true,
appendTo: document.body,
placement: 'right',
offset: [0, 20]
});
};
setupTippy(link);
let path = link.previousElementSibling;
while(path && path.tagName !== 'path') path = path.previousElementSibling;
if (path) {
path.style.cursor = 'pointer';
setupTippy(path);
}
}
});
}
function normalize(s) {
if (!s) return "";
return s.replace(/[^a-zA-Z0-9]/g, '_');
}
function createTooltip(name, trans) {
const chains = (metadata.metadata.callChains || []).filter(c => normalize(c.triggerPoint.event) === name);
let html = `<div class="tooltip-content">
<div style="font-weight:900; font-size:1.1rem; margin-bottom:12px; border-bottom:1px solid #eee; padding-bottom:8px; line-height:1.3;">
${name === 'Internal logic' ? name : 'Event: <span style="color:var(--accent)">' + name + '</span>'}
</div>`;
if (trans && trans.guard) {
const lineInfo = trans.guard.lineNumber ? ` <span style="color:#94a3b8; font-weight:400; font-size:0.6rem;">(Line: ${trans.guard.lineNumber})</span>` : '';
html += `<div style="font-size:0.7rem; font-weight:800; color:#94a3b8; text-transform:uppercase; margin-bottom:4px">Guard${lineInfo}</div>
<div style="background:#f1f5f9; padding:6px; border-radius:4px; font-family:monospace; font-size:0.8rem; margin-bottom:12px; border:1px solid #e2e8f0;">${trans.guard.expression}</div>`;
if (trans.guard.internalLogic) {
html += `<div style="font-size:0.65rem; font-weight:800; color:#cbd5e1; text-transform:uppercase; margin-bottom:4px">Internal Logic</div>
<pre style="background:#1e293b; color:#f8fafc; padding:8px; border-radius:4px; font-family:'JetBrains Mono', monospace; font-size:0.7rem; overflow-x:auto; margin-bottom:12px;"><code>${trans.guard.internalLogic.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code></pre>`;
}
}
if (trans && trans.actions && trans.actions.length > 0) {
html += `<div style="font-size:0.7rem; font-weight:800; color:#94a3b8; text-transform:uppercase; margin-bottom:4px">Actions</div>`;
trans.actions.forEach(action => {
const lineInfo = action.lineNumber ? ` <span style="color:#94a3b8; font-weight:400; font-size:0.6rem;">(Line: ${action.lineNumber})</span>` : '';
html += `<div style="font-size:0.7rem; font-weight:800; color:#94a3b8; text-transform:uppercase; margin-bottom:4px">Action${lineInfo}</div>
<div style="background:#f1f5f9; padding:6px; border-radius:4px; font-family:monospace; font-size:0.8rem; margin-bottom:12px; border:1px solid #e2e8f0;">${action.expression}</div>`;
if (action.internalLogic) {
html += `<div style="font-size:0.65rem; font-weight:800; color:#cbd5e1; text-transform:uppercase; margin-bottom:4px">Internal Logic</div>
<pre style="background:#1e293b; color:#f8fafc; padding:8px; border-radius:4px; font-family:'JetBrains Mono', monospace; font-size:0.7rem; overflow-x:auto; margin-bottom:12px;"><code>${action.internalLogic.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code></pre>`;
}
});
}
if (chains && chains.length > 0) {
html += `<div style="font-size:0.7rem; font-weight:800; color:#94a3b8; text-transform:uppercase; margin-bottom:10px; border-top:1px solid #eee; padding-top:10px">Triggered by</div>`;
chains.forEach(c => {
html += `<div style="margin-bottom:20px">
<div style="font-weight:700; font-size:0.85rem; color:var(--text);">${c.entryPoint.name}</div>
${renderParameters(c.entryPoint.parameters)}
<div style="margin-left:10px; border-left:2px solid #e2e8f0; padding-left:12px; margin-top:10px">
${c.methodChain.map((m, i) => `<div style="font-size:0.7rem; color:#475569; margin-top:4px; font-family:'JetBrains Mono', monospace;"><b>${i+1}</b> ${m}</div>`).join('')}
</div>
</div>`;
});
}
html += `</div>`;
return html;
}
function renderParameters(params) {
if (!params || params.length === 0) return "";
let html = `<div style="font-size:0.65rem; font-weight:700; color:#94a3b8; margin-top:8px; margin-bottom:4px; text-transform:uppercase;">Input Data</div>`;
html += `<div class="payload-box">`;
params.forEach(p => {
const annotation = (p.annotations || []).find(a => a.endsWith("RequestBody") || a.endsWith("PathVariable") || a.endsWith("RequestParam"));
const cleanAnn = annotation ? "@" + annotation.substring(annotation.lastIndexOf('.') + 1) : "";
html += `<div class="payload-param">
<span style="color:#f43f5e; font-size:0.65rem; font-weight:bold;">${cleanAnn}</span>
<span style="color:#38bdf8;">${p.type}</span>
<span style="color:#a3e635;">${p.name}</span>
</div>`;
});
html += `</div>`;
return html;
}
</script>
</body>
</html>

View File

@@ -0,0 +1,66 @@
{
"metadata" : {
"triggers" : [ {
"event" : "ORDER_EVENT",
"className" : "click.kamil.maven.core.OrderService",
"methodName" : "onMessage",
"sourceModule" : null,
"stateMachineId" : null,
"lineNumber" : 34
} ],
"entryPoints" : [ {
"type" : "REST",
"name" : "POST /reactive/order",
"className" : "click.kamil.maven.api.ReactiveOrderApi",
"methodName" : "orderRoutes",
"metadata" : {
"path" : "/reactive/order",
"verb" : "POST",
"style" : "WebFlux Functional"
},
"parameters" : [ ]
}, {
"type" : "JMS",
"name" : "JMS: order.queue",
"className" : "click.kamil.maven.api.JmsOrderListener",
"methodName" : "onMessage",
"metadata" : {
"protocol" : "JMS",
"destination" : "order.queue"
},
"parameters" : [ {
"name" : "message",
"type" : "String",
"annotations" : [ ]
} ]
} ],
"callChains" : [ ],
"properties" : {
"default" : { }
}
},
"name" : "click.kamil.maven.core.MavenOrderStateMachine",
"renderChoicesAsDiamonds" : true,
"startStates" : [ "INIT" ],
"transitions" : [ {
"type" : "EXTERNAL",
"sourceStates" : [ {
"rawName" : "\"INIT\"",
"fullIdentifier" : "INIT"
} ],
"targetStates" : [ {
"rawName" : "\"BUSY\"",
"fullIdentifier" : "BUSY"
} ],
"event" : "ORDER_EVENT",
"guard" : null,
"actions" : [ {
"expression" : "loggingAction()",
"isLambda" : false,
"internalLogic" : "context -> {\n System.out.println(\"LOG: State transition in progress...\");\n}\n",
"lineNumber" : 23
} ],
"order" : null
} ],
"endStates" : [ "DONE" ]
}

View File

@@ -0,0 +1,31 @@
@startuml
!pragma layout smetana
set separator none
hide empty description
hide stereotype
skinparam state {
BackgroundColor white
BorderColor #94a3b8
BorderThickness 1
FontName Inter
FontSize 9
FontStyle bold
RoundCorner 20
Padding 1
}
skinparam shadowing false
skinparam ArrowFontName JetBrains Mono
skinparam ArrowFontSize 8
skinparam ArrowColor #cbd5e1
skinparam ArrowThickness 1
skinparam dpi 110
skinparam svgLinkTarget _self
[*] --> INIT
INIT -[#1E90FF,bold]-> BUSY <<external>> <<e_ORDER_EVENT>> : ORDER_EVENT / loggingAction()
DONE --> [*]
@enduml

View File

@@ -0,0 +1,108 @@
{
"metadata" : {
"triggers" : [ {
"event" : "SUBMIT",
"className" : "click.kamil.multi.core.OrderController",
"methodName" : "submitOrder",
"sourceModule" : null,
"stateMachineId" : null,
"lineNumber" : 18
} ],
"entryPoints" : [ {
"type" : "REST",
"name" : "POST /orders/submit",
"className" : "click.kamil.multi.core.OrderController",
"methodName" : "submitOrder",
"metadata" : {
"path" : "/orders/submit",
"verb" : "POST"
},
"parameters" : [ {
"name" : "orderId",
"type" : "String",
"annotations" : [ "RequestBody" ]
} ]
}, {
"type" : "REST",
"name" : "POST /orders/submit",
"className" : "click.kamil.multi.api.OrderApi",
"methodName" : "submitOrder",
"metadata" : {
"path" : "/orders/submit",
"verb" : "POST"
},
"parameters" : [ {
"name" : "orderId",
"type" : "String",
"annotations" : [ "RequestBody" ]
} ]
} ],
"callChains" : [ {
"entryPoint" : {
"type" : "REST",
"name" : "POST /orders/submit",
"className" : "click.kamil.multi.core.OrderController",
"methodName" : "submitOrder",
"metadata" : {
"path" : "/orders/submit",
"verb" : "POST"
},
"parameters" : [ {
"name" : "orderId",
"type" : "String",
"annotations" : [ "RequestBody" ]
} ]
},
"methodChain" : [ "click.kamil.multi.core.OrderController.submitOrder" ],
"triggerPoint" : {
"event" : "SUBMIT",
"className" : "click.kamil.multi.core.OrderController",
"methodName" : "submitOrder",
"sourceModule" : null,
"stateMachineId" : null,
"lineNumber" : 18
}
} ],
"properties" : {
"default" : { }
}
},
"name" : "click.kamil.multi.core.OrderStateMachineConfig",
"renderChoicesAsDiamonds" : true,
"startStates" : [ "NEW" ],
"transitions" : [ {
"type" : "EXTERNAL",
"sourceStates" : [ {
"rawName" : "\"NEW\"",
"fullIdentifier" : "NEW"
} ],
"targetStates" : [ {
"rawName" : "\"PROCESSING\"",
"fullIdentifier" : "PROCESSING"
} ],
"event" : "SUBMIT",
"guard" : null,
"actions" : [ {
"expression" : "processAction()",
"isLambda" : false,
"internalLogic" : "@Override default void execute(StateContext<String,String> context){\n System.out.println(\"Processing order: \" + context.getMessageHeader(\"orderId\"));\n}\n",
"lineNumber" : 31
} ],
"order" : null
}, {
"type" : "EXTERNAL",
"sourceStates" : [ {
"rawName" : "\"PROCESSING\"",
"fullIdentifier" : "PROCESSING"
} ],
"targetStates" : [ {
"rawName" : "\"COMPLETED\"",
"fullIdentifier" : "COMPLETED"
} ],
"event" : "FINISH",
"guard" : null,
"actions" : [ ],
"order" : null
} ],
"endStates" : [ "COMPLETED" ]
}