Compare commits
12 Commits
ab37eb5d40
...
ai-branch-
| Author | SHA1 | Date | |
|---|---|---|---|
| 9f651e7dc9 | |||
| e06429cb02 | |||
| 9cf2d063b3 | |||
| 073df21395 | |||
| f9e6247eb3 | |||
| 76ac143370 | |||
| 9ca8b2fe37 | |||
| 56cdf96f2d | |||
| c37aa92c78 | |||
| 3ac057618f | |||
| d59f4ac166 | |||
| 19547d3c5f |
1
TODO.md
1
TODO.md
@@ -1,6 +1,5 @@
|
||||
1.extract from all possible formats (ask chatgpt)
|
||||
|
||||
[DONE] json
|
||||
[TODO] xml, maybe yaml
|
||||
|
||||
2. [PLAN] Support external dependencies (JARs/compiled classes):
|
||||
|
||||
@@ -14,8 +14,16 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import click.kamil.springstatemachineexporter.analysis.enricher.routing.HeuristicBeanResolutionEngine;
|
||||
import click.kamil.springstatemachineexporter.analysis.enricher.routing.BeanResolutionEngine;
|
||||
import click.kamil.springstatemachineexporter.analysis.enricher.matching.EventMatchingEngine;
|
||||
import click.kamil.springstatemachineexporter.analysis.enricher.matching.HeuristicEventMatchingEngine;
|
||||
|
||||
public class TransitionLinkerEnricher implements AnalysisEnricher {
|
||||
|
||||
private final BeanResolutionEngine routingEngine = new HeuristicBeanResolutionEngine();
|
||||
private final EventMatchingEngine matchingEngine = new HeuristicEventMatchingEngine();
|
||||
|
||||
@Override
|
||||
public void enrich(AnalysisResult result, CodebaseContext context, CodebaseIntelligenceProvider intelligence) {
|
||||
if (result.getMetadata() == null || result.getMetadata().getCallChains() == null) {
|
||||
@@ -38,40 +46,9 @@ public class TransitionLinkerEnricher implements AnalysisEnricher {
|
||||
List<MatchedTransition> matched = new ArrayList<>();
|
||||
|
||||
for (Transition t : stateMachineTransitions) {
|
||||
if (t.getEvent() != null) {
|
||||
if (t.getEvent() != null && matchingEngine.matches(t.getEvent(), tp)) {
|
||||
String smEventRaw = t.getEvent().fullIdentifier() != null ? t.getEvent().fullIdentifier() : t.getEvent().rawName();
|
||||
String smEvent = simplify(smEventRaw);
|
||||
|
||||
boolean isWildcard = triggerEvent.equals("event") || triggerEvent.equals("e") ||
|
||||
triggerEvent.equals("msg") || triggerEvent.equals("message") ||
|
||||
triggerEvent.equals("payload") || triggerEvent.matches(".*\\.get[A-Z].*\\(\\)");
|
||||
|
||||
if (isWildcard) {
|
||||
String targetVar = chain.getContextMachineId();
|
||||
if (targetVar == null && chain.getTriggerPoint() != null) {
|
||||
targetVar = chain.getTriggerPoint().getStateMachineId();
|
||||
}
|
||||
// We no longer hard-block wildcards without a specific routing context.
|
||||
// If a project doesn't use standard SM persisters (e.g. restores state manually),
|
||||
// contextMachineId will be null. We should still link the wildcard to provide SOME visibility,
|
||||
// rather than completely hiding the endpoint.
|
||||
}
|
||||
|
||||
List<String> polyEvents = tp.getPolymorphicEvents() != null ? tp.getPolymorphicEvents() : java.util.Collections.emptyList();
|
||||
boolean hasPolyMatch = false;
|
||||
for (String pe : polyEvents) {
|
||||
String simplePe = pe;
|
||||
if (pe.contains(".")) {
|
||||
simplePe = pe.substring(pe.lastIndexOf('.') + 1);
|
||||
}
|
||||
if (simplePe.equals(smEventRaw) || simplePe.equals(smEvent)) {
|
||||
hasPolyMatch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPolyMatch || (polyEvents.isEmpty() && (isWildcard || smEvent.equals(triggerEvent) || triggerEvent.toLowerCase().contains(smEvent.toLowerCase()) || smEvent.toLowerCase().contains(triggerEvent.toLowerCase())))) {
|
||||
// Event matches or is a wildcard
|
||||
// Event matches
|
||||
for (State smSourceState : t.getSourceStates()) {
|
||||
String smSourceRaw = smSourceState.fullIdentifier() != null ? smSourceState.fullIdentifier() : smSourceState.rawName();
|
||||
String smSource = simplify(smSourceRaw);
|
||||
@@ -102,7 +79,6 @@ public class TransitionLinkerEnricher implements AnalysisEnricher {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!matched.isEmpty()) {
|
||||
CallChain newChain = chain.toBuilder().matchedTransitions(matched).build();
|
||||
@@ -123,26 +99,9 @@ public class TransitionLinkerEnricher implements AnalysisEnricher {
|
||||
result.setMetadata(updatedMetadata);
|
||||
}
|
||||
|
||||
private boolean isRoutedToCorrectMachine(CallChain chain, String currentMachineName) {
|
||||
// If the chain's target expression or qualifier indicates a specific machine name, verify it
|
||||
String targetVar = chain.getContextMachineId();
|
||||
if (targetVar == null && chain.getTriggerPoint() != null) {
|
||||
targetVar = chain.getTriggerPoint().getStateMachineId();
|
||||
}
|
||||
|
||||
if (targetVar != null && !targetVar.isEmpty()) {
|
||||
targetVar = targetVar.toLowerCase();
|
||||
// E.g., if target is "myStateMachine", ensure current machine name contains "my"
|
||||
String simplifiedMachineName = currentMachineName.substring(currentMachineName.lastIndexOf('.') + 1).toLowerCase();
|
||||
// If the variable name ends with StateMachine, we extract the prefix
|
||||
if (targetVar.endsWith("statemachine")) {
|
||||
String prefix = targetVar.substring(0, targetVar.length() - "statemachine".length());
|
||||
if (!prefix.isEmpty() && !simplifiedMachineName.contains(prefix)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
private boolean isRoutedToCorrectMachine(CallChain chain, String currentMachineName) {
|
||||
return routingEngine.isRoutedToCorrectMachine(chain, currentMachineName);
|
||||
}
|
||||
|
||||
private String simplify(String name) {
|
||||
@@ -157,4 +116,31 @@ public class TransitionLinkerEnricher implements AnalysisEnricher {
|
||||
// For remaining full caps with underscores (like EVENT_X), keep as is or try to simplify
|
||||
return simplified;
|
||||
}
|
||||
|
||||
private boolean isGuardedContains(String smEvent, String triggerEvent) {
|
||||
// Only fire if it looks like a simple identifier (no spaces, no parens)
|
||||
// Prevents unresolved AST nodes (e.g. "event.getPayload()") from accidentally matching "Event"
|
||||
if (smEvent.contains(" ") || smEvent.contains("(") || smEvent.contains(")") ||
|
||||
triggerEvent.contains(" ") || triggerEvent.contains("(") || triggerEvent.contains(")")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String shorter = smEvent.length() < triggerEvent.length() ? smEvent : triggerEvent;
|
||||
String longer = smEvent.length() >= triggerEvent.length() ? smEvent : triggerEvent;
|
||||
|
||||
shorter = shorter.toLowerCase();
|
||||
longer = longer.toLowerCase();
|
||||
|
||||
if (longer.contains(shorter)) {
|
||||
// Guard: If the matching part is very short (< 4 chars), it must be bounded by word separators
|
||||
// to avoid matching completely unrelated words (e.g., "PAY" matching "PAYMENT" or "E" matching "UPDATE")
|
||||
if (shorter.length() < 4) {
|
||||
return longer.matches(".*(^|_|-)" + shorter + "(_|-|$).*");
|
||||
}
|
||||
// For longer strings, a straight contains is usually safe enough
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.enricher.matching;
|
||||
|
||||
import click.kamil.springstatemachineexporter.analysis.model.TriggerPoint;
|
||||
import click.kamil.springstatemachineexporter.model.Event;
|
||||
|
||||
public interface EventMatchingEngine {
|
||||
/**
|
||||
* Determines whether the given trigger point is a match for the state machine event.
|
||||
*/
|
||||
boolean matches(Event stateMachineEvent, TriggerPoint triggerPoint);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.enricher.matching;
|
||||
|
||||
import click.kamil.springstatemachineexporter.analysis.model.TriggerPoint;
|
||||
import click.kamil.springstatemachineexporter.model.Event;
|
||||
import java.util.List;
|
||||
|
||||
public class HeuristicEventMatchingEngine implements EventMatchingEngine {
|
||||
|
||||
@Override
|
||||
public boolean matches(Event stateMachineEvent, TriggerPoint triggerPoint) {
|
||||
if (stateMachineEvent == null || triggerPoint == null || triggerPoint.getEvent() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String triggerEvent = simplify(triggerPoint.getEvent());
|
||||
String smEventRaw = stateMachineEvent.fullIdentifier() != null ? stateMachineEvent.fullIdentifier() : stateMachineEvent.rawName();
|
||||
String smEvent = simplify(smEventRaw);
|
||||
|
||||
boolean isWildcard = isWildcardVariable(triggerEvent);
|
||||
|
||||
List<String> polyEvents = triggerPoint.getPolymorphicEvents() != null ? triggerPoint.getPolymorphicEvents() : java.util.Collections.emptyList();
|
||||
|
||||
boolean hasPolyMatch = false;
|
||||
for (String pe : polyEvents) {
|
||||
String simplePe = pe;
|
||||
if (pe.contains(".")) {
|
||||
simplePe = pe.substring(pe.lastIndexOf('.') + 1);
|
||||
}
|
||||
if (simplePe.equals(smEventRaw) || simplePe.equals(smEvent)) {
|
||||
hasPolyMatch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return hasPolyMatch || smEvent.equals(triggerEvent) || (polyEvents.isEmpty() && isWildcard);
|
||||
}
|
||||
|
||||
private boolean isWildcardVariable(String eventStr) {
|
||||
return eventStr.equals("event") || eventStr.equals("e") ||
|
||||
eventStr.equals("msg") || eventStr.equals("message") ||
|
||||
eventStr.equals("payload");
|
||||
}
|
||||
|
||||
private String simplify(String name) {
|
||||
if (name == null) return null;
|
||||
String simplified = name.replaceAll("(?i)(.*)(Event|Action|Transition|Command)(s)?$", "$1");
|
||||
if (simplified.isEmpty()) {
|
||||
simplified = name;
|
||||
}
|
||||
simplified = simplified.replaceAll("^.*\\.([A-Z0-9_]+)$", "$1");
|
||||
return simplified;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.enricher.routing;
|
||||
|
||||
import click.kamil.springstatemachineexporter.analysis.model.CallChain;
|
||||
|
||||
public interface BeanResolutionEngine {
|
||||
boolean isRoutedToCorrectMachine(CallChain chain, String currentMachineName);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.enricher.routing;
|
||||
|
||||
import click.kamil.springstatemachineexporter.analysis.model.CallChain;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class HeuristicBeanResolutionEngine implements BeanResolutionEngine {
|
||||
|
||||
@Override
|
||||
public boolean isRoutedToCorrectMachine(CallChain chain, String currentMachineName) {
|
||||
String targetVar = chain.getContextMachineId();
|
||||
if (targetVar == null && chain.getTriggerPoint() != null) {
|
||||
targetVar = chain.getTriggerPoint().getStateMachineId();
|
||||
}
|
||||
|
||||
String simplifiedMachineName = currentMachineName != null ? currentMachineName.substring(currentMachineName.lastIndexOf('.') + 1).toLowerCase() : "";
|
||||
|
||||
if (targetVar != null && !targetVar.isEmpty()) {
|
||||
targetVar = targetVar.toLowerCase();
|
||||
if (targetVar.endsWith("statemachine")) {
|
||||
String prefix = targetVar.substring(0, targetVar.length() - "statemachine".length());
|
||||
if (!prefix.isEmpty()) {
|
||||
if (simplifiedMachineName.contains(prefix)) {
|
||||
return true; // Explicit positive match
|
||||
} else {
|
||||
return false; // Explicit negative match
|
||||
}
|
||||
}
|
||||
} else if (simplifiedMachineName.contains(targetVar)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (chain.getMethodChain() != null && !chain.getMethodChain().isEmpty() && currentMachineName != null) {
|
||||
String smPackage = getPackageName(currentMachineName);
|
||||
String smSimple = getSimpleClassName(currentMachineName);
|
||||
String smPrefix = getFirstCamelCaseWord(smSimple);
|
||||
|
||||
boolean hasPositiveMatch = false;
|
||||
boolean hasStrongMismatch = false;
|
||||
|
||||
for (String method : chain.getMethodChain()) {
|
||||
String chainClass = getClassNameOnly(method);
|
||||
String chainPackage = getPackageName(chainClass);
|
||||
String chainSimple = getSimpleClassName(chainClass);
|
||||
String chainPrefix = getFirstCamelCaseWord(chainSimple);
|
||||
|
||||
if (smPrefix != null && chainPrefix != null && smPrefix.equals(chainPrefix)) {
|
||||
hasPositiveMatch = true;
|
||||
}
|
||||
|
||||
if (isDomainMatch(smPackage, chainPackage, smPrefix, chainPrefix)) {
|
||||
hasPositiveMatch = true;
|
||||
}
|
||||
|
||||
if (isDomainMismatch(smPackage, chainPackage, smPrefix, chainPrefix)) {
|
||||
hasStrongMismatch = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPositiveMatch) {
|
||||
return true;
|
||||
}
|
||||
if (hasStrongMismatch) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isDomainMatch(String smPackage, String chainPackage, String smPrefix, String chainPrefix) {
|
||||
if (smPackage == null || chainPackage == null || smPackage.isEmpty() || chainPackage.isEmpty()) return false;
|
||||
|
||||
if (smPackage.startsWith(chainPackage) || chainPackage.startsWith(smPackage)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Find deepest common package root
|
||||
String[] p1 = smPackage.split("\\.");
|
||||
String[] p2 = chainPackage.split("\\.");
|
||||
int matchIdx = -1;
|
||||
for (int i = 0; i < Math.min(p1.length, p2.length); i++) {
|
||||
if (p1[i].equals(p2[i])) {
|
||||
matchIdx = i;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If the state machine's prefix is part of the shared common package,
|
||||
// then the state machine represents the parent domain of the caller.
|
||||
if (smPrefix != null && matchIdx >= 0) {
|
||||
String lowerPrefix = smPrefix.toLowerCase();
|
||||
for (int i = 0; i <= matchIdx; i++) {
|
||||
if (p1[i].toLowerCase().contains(lowerPrefix) || lowerPrefix.contains(p1[i].toLowerCase())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isDomainMismatch(String smPackage, String chainPackage, String smPrefix, String chainPrefix) {
|
||||
if (smPackage == null || chainPackage == null || smPackage.isEmpty() || chainPackage.isEmpty()) return false;
|
||||
|
||||
String[] p1 = smPackage.split("\\.");
|
||||
String[] p2 = chainPackage.split("\\.");
|
||||
|
||||
int matchIdx = -1;
|
||||
for (int i = 0; i < Math.min(p1.length, p2.length); i++) {
|
||||
if (p1[i].equals(p2[i])) {
|
||||
matchIdx = i;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> smDivergentTerms = new HashSet<>();
|
||||
if (smPrefix != null) smDivergentTerms.add(smPrefix.toLowerCase());
|
||||
for (int i = matchIdx + 1; i < p1.length; i++) {
|
||||
smDivergentTerms.add(p1[i].toLowerCase());
|
||||
}
|
||||
|
||||
Set<String> chainDivergentTerms = new HashSet<>();
|
||||
if (chainPrefix != null) chainDivergentTerms.add(chainPrefix.toLowerCase());
|
||||
for (int i = matchIdx + 1; i < p2.length; i++) {
|
||||
chainDivergentTerms.add(p2[i].toLowerCase());
|
||||
}
|
||||
|
||||
if (!smDivergentTerms.isEmpty() && !chainDivergentTerms.isEmpty()) {
|
||||
Set<String> intersection = new HashSet<>(smDivergentTerms);
|
||||
intersection.retainAll(chainDivergentTerms);
|
||||
return intersection.isEmpty();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private Set<String> extractDomainTerms(String pkg, String prefix) {
|
||||
Set<String> terms = new HashSet<>();
|
||||
if (pkg != null && !pkg.isEmpty()) {
|
||||
String[] segments = pkg.split("\\.");
|
||||
// Take segments from index 2 onwards if length > 2
|
||||
int start = segments.length > 2 ? 2 : 0;
|
||||
for (int i = start; i < segments.length; i++) {
|
||||
terms.add(segments[i].toLowerCase());
|
||||
}
|
||||
}
|
||||
if (prefix != null && !prefix.isEmpty()) {
|
||||
terms.add(prefix.toLowerCase());
|
||||
}
|
||||
return terms;
|
||||
}
|
||||
|
||||
private String getPackageName(String fqn) {
|
||||
if (fqn == null || !fqn.contains(".")) return "";
|
||||
return fqn.substring(0, fqn.lastIndexOf('.'));
|
||||
}
|
||||
|
||||
private String getSimpleClassName(String fqn) {
|
||||
if (fqn == null) return "";
|
||||
if (!fqn.contains(".")) return fqn;
|
||||
return fqn.substring(fqn.lastIndexOf('.') + 1);
|
||||
}
|
||||
|
||||
private String getClassNameOnly(String methodFqn) {
|
||||
if (methodFqn == null) return "";
|
||||
String clean = methodFqn;
|
||||
if (clean.contains("(")) {
|
||||
clean = clean.substring(0, clean.indexOf('('));
|
||||
}
|
||||
if (clean.contains(".")) {
|
||||
clean = clean.substring(0, clean.lastIndexOf('.'));
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
|
||||
private String getFirstCamelCaseWord(String simpleName) {
|
||||
if (simpleName == null || simpleName.isEmpty()) return null;
|
||||
String[] words = simpleName.split("(?<!^)(?=[A-Z])");
|
||||
if (words.length > 0) {
|
||||
return words[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class CallEdge {
|
||||
private final String targetMethod;
|
||||
private final List<String> arguments;
|
||||
}
|
||||
@@ -55,7 +55,26 @@ public class ConstantResolver {
|
||||
return resolveManual(sn, context, visited);
|
||||
}
|
||||
|
||||
|
||||
if (expr instanceof MethodInvocation mi) {
|
||||
if ((mi.getName().getIdentifier().equals("name") || mi.getName().getIdentifier().equals("toString")) && mi.arguments().isEmpty()) {
|
||||
String val = resolveInternal(mi.getExpression(), context, visited);
|
||||
if (val != null) {
|
||||
// If it was resolved as a fully qualified enum string like "MyEvents.ORDER_PAID", strip it
|
||||
if (val.contains(".")) {
|
||||
return val.substring(val.lastIndexOf('.') + 1);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
// Fallback for unresolved AST nodes
|
||||
if (mi.getExpression() instanceof QualifiedName qn) {
|
||||
return qn.getName().getIdentifier();
|
||||
} else if (mi.getExpression() instanceof SimpleName sn) {
|
||||
return sn.getIdentifier();
|
||||
}
|
||||
}
|
||||
|
||||
IMethodBinding mb = mi.resolveMethodBinding();
|
||||
if (mb != null) {
|
||||
ITypeBinding returnType = mb.getReturnType();
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
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 java.util.List;
|
||||
|
||||
public interface CallGraphEngine {
|
||||
List<CallChain> findChains(List<EntryPoint> entryPoints, List<TriggerPoint> triggers);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
public class DynamicClasspathResolver {
|
||||
|
||||
public List<String> resolveClasspath(Path projectRoot) {
|
||||
log.info("Attempting dynamic classpath resolution for project at {}", projectRoot);
|
||||
if (projectRoot == null || !Files.exists(projectRoot)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
if (Files.exists(projectRoot.resolve("pom.xml"))) {
|
||||
return resolveMaven(projectRoot);
|
||||
} else if (Files.exists(projectRoot.resolve("build.gradle")) || Files.exists(projectRoot.resolve("build.gradle.kts"))) {
|
||||
return resolveGradle(projectRoot);
|
||||
}
|
||||
|
||||
log.info("No Maven or Gradle configuration found at {}. Proceeding without dynamic classpath.", projectRoot);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
protected List<String> resolveMaven(Path projectRoot) {
|
||||
log.info("Maven project detected. Resolving dependencies...");
|
||||
Path cpFile = null;
|
||||
try {
|
||||
cpFile = Files.createTempFile("state_machine_exporter_cp", ".txt");
|
||||
String mvnCmd = getCommand(projectRoot, "mvnw", "mvn");
|
||||
if (mvnCmd == null) {
|
||||
log.warn("Maven executable not found.");
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
mvnCmd,
|
||||
"-q",
|
||||
"dependency:build-classpath",
|
||||
"-DincludeScope=compile",
|
||||
"-Dmdep.outputFile=" + cpFile.toAbsolutePath().toString()
|
||||
);
|
||||
pb.directory(projectRoot.toFile());
|
||||
|
||||
runProcess(pb);
|
||||
|
||||
if (Files.exists(cpFile)) {
|
||||
String cpString = Files.readString(cpFile).trim();
|
||||
if (!cpString.isEmpty()) {
|
||||
return Arrays.asList(cpString.split(File.pathSeparator));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to dynamically resolve Maven classpath", e);
|
||||
} finally {
|
||||
if (cpFile != null) {
|
||||
try {
|
||||
Files.deleteIfExists(cpFile);
|
||||
} catch (IOException ignored) {}
|
||||
}
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
protected List<String> resolveGradle(Path projectRoot) {
|
||||
log.info("Gradle project detected. Resolving dependencies...");
|
||||
Path initScript = null;
|
||||
try {
|
||||
initScript = Files.createTempFile("state_machine_exporter_init", ".gradle");
|
||||
String gradleCmd = getCommand(projectRoot, "gradlew", "gradle");
|
||||
if (gradleCmd == null) {
|
||||
log.warn("Gradle executable not found.");
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
String scriptContent = """
|
||||
allprojects {
|
||||
task smePrintClasspath {
|
||||
doLast {
|
||||
def cp = []
|
||||
if (configurations.findByName("compileClasspath")) {
|
||||
cp = configurations.compileClasspath.files
|
||||
}
|
||||
println "SME_CLASSPATH_MARKER:" + cp.join(File.pathSeparator)
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
Files.writeString(initScript, scriptContent);
|
||||
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
gradleCmd,
|
||||
"-q",
|
||||
"-I", initScript.toAbsolutePath().toString(),
|
||||
"smePrintClasspath"
|
||||
);
|
||||
pb.directory(projectRoot.toFile());
|
||||
|
||||
String output = runProcessAndGetOutput(pb);
|
||||
for (String line : output.split("\\r?\\n")) {
|
||||
if (line.startsWith("SME_CLASSPATH_MARKER:")) {
|
||||
String cpString = line.substring("SME_CLASSPATH_MARKER:".length()).trim();
|
||||
if (!cpString.isEmpty()) {
|
||||
return Arrays.asList(cpString.split(File.pathSeparator));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to dynamically resolve Gradle classpath", e);
|
||||
} finally {
|
||||
if (initScript != null) {
|
||||
try {
|
||||
Files.deleteIfExists(initScript);
|
||||
} catch (IOException ignored) {}
|
||||
}
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
private String getCommand(Path projectRoot, String wrapper, String systemBinary) {
|
||||
Path wrapperUnix = projectRoot.resolve(wrapper);
|
||||
Path wrapperWin = projectRoot.resolve(wrapper + ".bat");
|
||||
|
||||
boolean isWin = System.getProperty("os.name").toLowerCase().contains("win");
|
||||
|
||||
if (isWin && Files.exists(wrapperWin)) return wrapperWin.toAbsolutePath().toString();
|
||||
if (!isWin && Files.exists(wrapperUnix)) {
|
||||
// Need absolute path like ./gradlew
|
||||
return wrapperUnix.toAbsolutePath().toString();
|
||||
}
|
||||
|
||||
return systemBinary;
|
||||
}
|
||||
|
||||
protected void runProcess(ProcessBuilder pb) throws IOException, InterruptedException {
|
||||
Process p = pb.start();
|
||||
p.waitFor();
|
||||
}
|
||||
|
||||
protected String runProcessAndGetOutput(ProcessBuilder pb) throws IOException, InterruptedException {
|
||||
Process p = pb.start();
|
||||
StringBuilder out = new StringBuilder();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
out.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
p.waitFor();
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
@@ -172,40 +172,97 @@ public class GenericEventDetector {
|
||||
}
|
||||
|
||||
private String extractSourceState(ASTNode node) {
|
||||
ASTNode current = node.getParent();
|
||||
ASTNode current = node;
|
||||
while (current != null && !(current instanceof MethodDeclaration)) {
|
||||
if (current instanceof IfStatement ifStmt) {
|
||||
ASTNode parent = current.getParent();
|
||||
|
||||
// 1. Direct parent is IfStatement wrapper (e.g., if (state == X) { sm.sendEvent() })
|
||||
if (parent instanceof IfStatement ifStmt) {
|
||||
// Only consider if our current node is in the 'then' or 'else' part, not the condition
|
||||
if (ifStmt.getExpression() != current) {
|
||||
Expression expr = ifStmt.getExpression();
|
||||
String state = extractStateFromExpression(expr);
|
||||
if (state != null) return state;
|
||||
} else if (current instanceof SwitchCase switchCase) {
|
||||
if (!switchCase.expressions().isEmpty()) {
|
||||
return getSimpleNameString((Expression) switchCase.expressions().get(0));
|
||||
}
|
||||
} else if (current instanceof SwitchStatement switchStmt) {
|
||||
// If it's a switch block but we haven't hit a SwitchCase directly (AST hierarchy usually has SwitchCase as siblings of block statements)
|
||||
// Actually, walking up from the node, we will hit the SwitchStatement, but we need the SwitchCase right before us in the block.
|
||||
ASTNode parentBlock = current;
|
||||
// It's complex to walk siblings. A simpler heuristic is to just use IfStatement and SwitchCase (if wrapped correctly).
|
||||
}
|
||||
current = current.getParent();
|
||||
|
||||
// 2. Parent is a Block or SwitchStatement: perform sibling traversal
|
||||
if (parent instanceof Block block) {
|
||||
String state = extractStateFromSiblings(current, block.statements());
|
||||
if (state != null) return state;
|
||||
} else if (parent instanceof SwitchStatement switchStmt) {
|
||||
String state = extractStateFromSiblings(current, switchStmt.statements());
|
||||
if (state != null) return state;
|
||||
}
|
||||
|
||||
current = parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String extractStateFromSiblings(ASTNode currentNode, List<?> statements) {
|
||||
int index = statements.indexOf(currentNode);
|
||||
if (index <= 0) return null; // No previous siblings
|
||||
|
||||
// Walk backwards through siblings
|
||||
for (int i = index - 1; i >= 0; i--) {
|
||||
Object stmtObj = statements.get(i);
|
||||
|
||||
if (stmtObj instanceof SwitchCase switchCase) {
|
||||
if (!switchCase.expressions().isEmpty()) {
|
||||
return getSimpleNameString((Expression) switchCase.expressions().get(0));
|
||||
}
|
||||
} else if (stmtObj instanceof IfStatement ifStmt) {
|
||||
// Guard clause detection: check if the 'then' block has a return/throw
|
||||
if (isGuardClause(ifStmt.getThenStatement())) {
|
||||
Expression expr = ifStmt.getExpression();
|
||||
// If it's a guard clause, it usually checks `state != EXPECTED`, so the true state *is* EXPECTED
|
||||
String state = extractStateFromExpression(expr);
|
||||
if (state != null) return state;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isGuardClause(Statement thenStatement) {
|
||||
if (thenStatement instanceof ReturnStatement || thenStatement instanceof ThrowStatement) {
|
||||
return true;
|
||||
}
|
||||
if (thenStatement instanceof Block block) {
|
||||
for (Object obj : block.statements()) {
|
||||
if (obj instanceof ReturnStatement || obj instanceof ThrowStatement) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String extractStateFromExpression(Expression expr) {
|
||||
if (expr instanceof InfixExpression infix) {
|
||||
if (infix.getOperator() == InfixExpression.Operator.EQUALS) {
|
||||
if (infix.getOperator() == InfixExpression.Operator.EQUALS || infix.getOperator() == InfixExpression.Operator.NOT_EQUALS) {
|
||||
Expression left = infix.getLeftOperand();
|
||||
Expression right = infix.getRightOperand();
|
||||
// Usually one is a method call like getState(), the other is an enum
|
||||
if (left instanceof QualifiedName || left instanceof SimpleName && !(right instanceof SimpleName)) {
|
||||
|
||||
// Ignore null checks entirely
|
||||
if (left instanceof NullLiteral || right instanceof NullLiteral) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Usually one is a method call like getState() or a variable like `state`
|
||||
// and the other is the constant enum like `OrderState.PENDING` or `"PENDING"`
|
||||
|
||||
// If one is a QualifiedName (enum constant) or StringLiteral, it's likely the state
|
||||
if (left instanceof QualifiedName || left instanceof StringLiteral || left instanceof FieldAccess) {
|
||||
return getSimpleNameString(left);
|
||||
}
|
||||
if (right instanceof QualifiedName || right instanceof SimpleName && !(left instanceof SimpleName)) {
|
||||
if (right instanceof QualifiedName || right instanceof StringLiteral || right instanceof FieldAccess) {
|
||||
return getSimpleNameString(right);
|
||||
}
|
||||
return getSimpleNameString(right); // Fallback
|
||||
|
||||
// Fallback
|
||||
return getSimpleNameString(right);
|
||||
}
|
||||
} else if (expr instanceof MethodInvocation mi) {
|
||||
if ("equals".equals(mi.getName().getIdentifier()) && !mi.arguments().isEmpty()) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.service;
|
||||
|
||||
import click.kamil.springstatemachineexporter.analysis.model.CallChain;
|
||||
import click.kamil.springstatemachineexporter.analysis.model.CallEdge;
|
||||
import click.kamil.springstatemachineexporter.analysis.model.EntryPoint;
|
||||
import click.kamil.springstatemachineexporter.analysis.model.TriggerPoint;
|
||||
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
|
||||
@@ -11,19 +12,13 @@ import org.eclipse.jdt.core.dom.*;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
public class CallGraphBuilder {
|
||||
public class HeuristicCallGraphEngine implements CallGraphEngine {
|
||||
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) {
|
||||
public HeuristicCallGraphEngine(CodebaseContext context) {
|
||||
this.context = context;
|
||||
this.constantResolver = new ConstantResolver();
|
||||
}
|
||||
@@ -147,30 +142,64 @@ public class CallGraphBuilder {
|
||||
}
|
||||
|
||||
List<String> polymorphicEvents = new ArrayList<>();
|
||||
if (resolvedValue.matches(".*\\.get[A-Z].*\\(\\)")) {
|
||||
String varName = resolvedValue.substring(0, resolvedValue.indexOf('.'));
|
||||
String methodName = resolvedValue.substring(resolvedValue.indexOf('.') + 1, resolvedValue.indexOf('('));
|
||||
if (resolvedValue.matches(".*\\.[a-zA-Z0-9_]+\\(\\)")) {
|
||||
int lastDot = resolvedValue.lastIndexOf('.');
|
||||
int firstDot = resolvedValue.indexOf('.');
|
||||
int openParen = resolvedValue.indexOf('(', lastDot);
|
||||
|
||||
// Resolve in the first method in the path where the variable might be declared
|
||||
if (lastDot > 0 && openParen > lastDot) {
|
||||
String varName = resolvedValue.substring(0, firstDot);
|
||||
if (varName.contains("(")) {
|
||||
varName = null;
|
||||
}
|
||||
String methodName = resolvedValue.substring(lastDot + 1, openParen);
|
||||
|
||||
String declaredType = null;
|
||||
String sourceMethod = null;
|
||||
|
||||
if (varName != null) {
|
||||
for (String methodFqn : path) {
|
||||
String declaredType = getVariableDeclaredType(methodFqn, varName);
|
||||
declaredType = getVariableDeclaredType(methodFqn, varName);
|
||||
if (declaredType != null) {
|
||||
System.out.println("DEEP TRACE: " + methodFqn + " " + varName + " -> " + declaredType);
|
||||
sourceMethod = methodFqn;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String baseExpr = resolvedValue.substring(0, lastDot);
|
||||
if (baseExpr.contains("new ")) {
|
||||
int newIdx = baseExpr.indexOf("new ");
|
||||
int openParenBase = baseExpr.indexOf('(', newIdx);
|
||||
if (openParenBase > newIdx) {
|
||||
declaredType = baseExpr.substring(newIdx + 4, openParenBase).trim();
|
||||
if (declaredType.contains("<")) {
|
||||
declaredType = declaredType.substring(0, declaredType.indexOf('<'));
|
||||
}
|
||||
sourceMethod = "inline-instantiation";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (declaredType != null) {
|
||||
System.out.println("DEEP TRACE: " + sourceMethod + " " + (varName != null ? varName : "inline") + " -> " + declaredType);
|
||||
List<String> typesToInspect = new ArrayList<>();
|
||||
if ("inline-instantiation".equals(sourceMethod)) {
|
||||
typesToInspect.add(declaredType);
|
||||
} else {
|
||||
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('.'));
|
||||
String firstPathMethod = path.get(0);
|
||||
String entryClassName = firstPathMethod.substring(0, firstPathMethod.lastIndexOf('.'));
|
||||
TypeDeclaration entryTd = context.getTypeDeclaration(entryClassName);
|
||||
if (entryTd != null && entryTd.getRoot() instanceof CompilationUnit) {
|
||||
cuToUse = (CompilationUnit) entryTd.getRoot();
|
||||
@@ -184,11 +213,54 @@ public class CallGraphBuilder {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LAST RESORT FALLBACK: If AST deep trace failed to find a valid ALL_CAPS constant
|
||||
// (e.g. it returned a field name like 'type', or nothing), we can scrape the resolvedValue string directly
|
||||
// for string literals or enum-like constants.
|
||||
boolean hasValidConstant = false;
|
||||
for (String ev : polymorphicEvents) {
|
||||
String val = ev.contains(".") ? ev.substring(ev.lastIndexOf('.') + 1) : ev;
|
||||
if (val.equals(val.toUpperCase()) && val.length() > 2) {
|
||||
hasValidConstant = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasValidConstant && resolvedValue.contains("(")) {
|
||||
java.util.List<String> scraped = new java.util.ArrayList<>();
|
||||
|
||||
// Extract "STRING_LITERALS"
|
||||
java.util.regex.Matcher m1 = java.util.regex.Pattern.compile("\"([^\"]+)\"").matcher(resolvedValue);
|
||||
while (m1.find()) {
|
||||
scraped.add(m1.group(1));
|
||||
}
|
||||
|
||||
// Extract ENUM_LIKE_CONSTANTS
|
||||
java.util.regex.Matcher m2 = java.util.regex.Pattern.compile("\\b([A-Z_]{3,})\\b").matcher(resolvedValue);
|
||||
while (m2.find()) {
|
||||
if (!scraped.contains(m2.group(1))) {
|
||||
scraped.add(m2.group(1));
|
||||
}
|
||||
}
|
||||
|
||||
if (!scraped.isEmpty()) {
|
||||
polymorphicEvents.clear();
|
||||
polymorphicEvents.addAll(scraped);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up any remaining invalid AST fallbacks (like 'type', 'event') if we found valid ones
|
||||
if (polymorphicEvents.size() > 1) {
|
||||
polymorphicEvents.removeIf(e -> {
|
||||
String val = e.contains(".") ? e.substring(e.lastIndexOf('.') + 1) : e;
|
||||
return !val.equals(val.toUpperCase()) || val.length() <= 2;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (!resolvedValue.equals(event) || !polymorphicEvents.isEmpty()) {
|
||||
return TriggerPoint.builder()
|
||||
.event(resolvedValue)
|
||||
@@ -263,7 +335,11 @@ public class CallGraphBuilder {
|
||||
if (!visited.add(fqn)) return Collections.emptyList();
|
||||
|
||||
List<String> constants = new ArrayList<>();
|
||||
TypeDeclaration td = contextCu != null ? context.getTypeDeclaration(className, contextCu) : context.getTypeDeclaration(className);
|
||||
TypeDeclaration tempTd = contextCu != null ? context.getTypeDeclaration(className, contextCu) : null;
|
||||
if (tempTd == null) {
|
||||
tempTd = context.getTypeDeclaration(className);
|
||||
}
|
||||
final TypeDeclaration td = tempTd;
|
||||
if (td == null) {
|
||||
System.out.println("DEEP TRACE FAILED TO FIND TD: " + className);
|
||||
}
|
||||
@@ -311,10 +387,15 @@ public class CallGraphBuilder {
|
||||
} else if (retExpr instanceof QualifiedName qn) {
|
||||
constants.add(qn.toString());
|
||||
} else if (retExpr instanceof SimpleName sn) {
|
||||
List<String> consts = traceFieldInConstructors(td, sn.getIdentifier(), context, visited);
|
||||
if (!consts.isEmpty()) {
|
||||
constants.addAll(consts);
|
||||
} else {
|
||||
constants.add(sn.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return super.visit(node);
|
||||
}
|
||||
});
|
||||
@@ -541,9 +622,11 @@ public class CallGraphBuilder {
|
||||
expr = tracedExpr; // Only accept trace if it resolves to a pure constant/primitive/constructor
|
||||
}
|
||||
|
||||
if (expr instanceof ClassInstanceCreation cic) {
|
||||
if (!cic.arguments().isEmpty()) {
|
||||
expr = (Expression) cic.arguments().get(0);
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -772,4 +855,113 @@ public class CallGraphBuilder {
|
||||
}
|
||||
return expr;
|
||||
}
|
||||
|
||||
private List<String> traceFieldInConstructors(TypeDeclaration td, String fieldName, CodebaseContext context, Set<String> visited) {
|
||||
List<String> results = new ArrayList<>();
|
||||
|
||||
// 1. Check Field Declarations
|
||||
for (org.eclipse.jdt.core.dom.FieldDeclaration fd : td.getFields()) {
|
||||
for (Object fragObj : fd.fragments()) {
|
||||
org.eclipse.jdt.core.dom.VariableDeclarationFragment frag = (org.eclipse.jdt.core.dom.VariableDeclarationFragment) fragObj;
|
||||
if (frag.getName().getIdentifier().equals(fieldName) && frag.getInitializer() != null) {
|
||||
Expression right = frag.getInitializer();
|
||||
if (right instanceof MethodInvocation mi) {
|
||||
String calledName = mi.getName().getIdentifier();
|
||||
String targetClass = context.getFqn(td);
|
||||
CompilationUnit cu = td.getRoot() instanceof CompilationUnit ? (CompilationUnit) td.getRoot() : null;
|
||||
results.addAll(resolveMethodReturnConstant(targetClass, calledName, 0, new HashSet<>(visited), cu));
|
||||
} else {
|
||||
String val = constantResolver.resolve(right, context);
|
||||
if (val != null) results.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
org.eclipse.jdt.core.dom.ASTVisitor assignmentVisitor = new org.eclipse.jdt.core.dom.ASTVisitor() {
|
||||
@Override
|
||||
public boolean visit(Assignment node) {
|
||||
Expression left = node.getLeftHandSide();
|
||||
if ((left instanceof SimpleName && ((SimpleName) left).getIdentifier().equals(fieldName)) ||
|
||||
(left instanceof FieldAccess && ((FieldAccess) left).getName().getIdentifier().equals(fieldName))) {
|
||||
|
||||
Expression right = node.getRightHandSide();
|
||||
if (right instanceof MethodInvocation mi) {
|
||||
String calledName = mi.getName().getIdentifier();
|
||||
String targetClass = context.getFqn(td);
|
||||
|
||||
if (mi.getExpression() != null && mi.resolveMethodBinding() != null && mi.resolveMethodBinding().getDeclaringClass() != null) {
|
||||
targetClass = mi.resolveMethodBinding().getDeclaringClass().getQualifiedName();
|
||||
} else if (mi.getExpression() instanceof SimpleName) {
|
||||
String exprName = ((SimpleName) mi.getExpression()).getIdentifier();
|
||||
CompilationUnit cu = td.getRoot() instanceof CompilationUnit ? (CompilationUnit) td.getRoot() : null;
|
||||
TypeDeclaration targetTd = context.resolveStaticImport(exprName, cu);
|
||||
if (targetTd != null) {
|
||||
targetClass = context.getFqn(targetTd);
|
||||
}
|
||||
}
|
||||
|
||||
CompilationUnit cu = td.getRoot() instanceof CompilationUnit ? (CompilationUnit) td.getRoot() : null;
|
||||
results.addAll(resolveMethodReturnConstant(targetClass, calledName, 0, new HashSet<>(visited), cu));
|
||||
} else {
|
||||
String val = constantResolver.resolve(right, context);
|
||||
if (val != null) results.add(val);
|
||||
}
|
||||
}
|
||||
return super.visit(node);
|
||||
}
|
||||
@Override
|
||||
public boolean visit(ConstructorInvocation node) {
|
||||
for (Object argObj : node.arguments()) {
|
||||
Expression arg = (Expression) argObj;
|
||||
String val = constantResolver.resolve(arg, context);
|
||||
if (val != null) {
|
||||
if (val.startsWith("ENUM_SET:")) {
|
||||
for (String eVal : val.substring(9).split(",")) {
|
||||
results.add(eVal.substring(eVal.lastIndexOf('.') + 1));
|
||||
}
|
||||
} else {
|
||||
results.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
return super.visit(node);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean visit(SuperConstructorInvocation node) {
|
||||
for (Object argObj : node.arguments()) {
|
||||
Expression arg = (Expression) argObj;
|
||||
String val = constantResolver.resolve(arg, context);
|
||||
if (val != null) {
|
||||
if (val.startsWith("ENUM_SET:")) {
|
||||
for (String eVal : val.substring(9).split(",")) {
|
||||
results.add(eVal.substring(eVal.lastIndexOf('.') + 1));
|
||||
}
|
||||
} else {
|
||||
results.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
return super.visit(node);
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Check Constructors
|
||||
for (MethodDeclaration md : td.getMethods()) {
|
||||
if (md.isConstructor() && md.getBody() != null) {
|
||||
md.getBody().accept(assignmentVisitor);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Check Initializers
|
||||
for (Object bodyDecl : td.bodyDeclarations()) {
|
||||
if (bodyDecl instanceof org.eclipse.jdt.core.dom.Initializer init && init.getBody() != null) {
|
||||
init.getBody().accept(assignmentVisitor);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,7 +21,7 @@ public class JdtIntelligenceProvider implements CodebaseIntelligenceProvider {
|
||||
private final GenericEventDetector eventDetector;
|
||||
private final SpringMvcDetector mvcDetector;
|
||||
private final MessagingDetector messagingDetector;
|
||||
private final CallGraphBuilder callGraphBuilder;
|
||||
private final CallGraphEngine callGraphEngine;
|
||||
private final LifecycleDetector lifecycleDetector;
|
||||
private final InterceptorDetector interceptorDetector;
|
||||
private final SpringComponentDetector componentDetector;
|
||||
@@ -32,7 +32,7 @@ public class JdtIntelligenceProvider implements CodebaseIntelligenceProvider {
|
||||
this.eventDetector = new GenericEventDetector(context, constantResolver, context.getLibraryHints());
|
||||
this.mvcDetector = new SpringMvcDetector(context, constantResolver);
|
||||
this.messagingDetector = new MessagingDetector(context);
|
||||
this.callGraphBuilder = new CallGraphBuilder(context);
|
||||
this.callGraphEngine = new HeuristicCallGraphEngine(context);
|
||||
this.lifecycleDetector = new LifecycleDetector(context);
|
||||
this.interceptorDetector = new InterceptorDetector(context);
|
||||
this.componentDetector = new SpringComponentDetector(context);
|
||||
@@ -69,7 +69,7 @@ public class JdtIntelligenceProvider implements CodebaseIntelligenceProvider {
|
||||
@Override
|
||||
public List<CallChain> findCallChains(List<EntryPoint> entryPoints, List<TriggerPoint> triggers) {
|
||||
log.info("JdtIntelligenceProvider searching for call chains between {} entry points and {} triggers", entryPoints.size(), triggers.size());
|
||||
return callGraphBuilder.findChains(entryPoints, triggers);
|
||||
return callGraphEngine.findChains(entryPoints, triggers);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -57,6 +57,9 @@ public class ExporterCommand implements Callable<Integer> {
|
||||
@Option(names = {"--debug"}, description = "Enable diagnostic mode to show unresolved call chains and detailed analysis logging.", defaultValue = "false")
|
||||
private boolean debug;
|
||||
|
||||
@Option(names = {"--resolve-classpath"}, description = "Automatically run Maven/Gradle to resolve full classpath dependencies for perfect AST bindings.", defaultValue = "false")
|
||||
private boolean resolveClasspath;
|
||||
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
var out = spec.commandLine().getOut();
|
||||
@@ -87,7 +90,7 @@ public class ExporterCommand implements Callable<Integer> {
|
||||
if (jsonFile != null) {
|
||||
exportService.runJsonExporter(jsonFile, outputDir, selectedFormats, profiles, eventFormat, stateFormat);
|
||||
} else {
|
||||
exportService.runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, profiles, eventFormat, stateFormat);
|
||||
exportService.runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, profiles, null, null, eventFormat, stateFormat, resolveClasspath);
|
||||
}
|
||||
out.println(CommandLine.Help.Ansi.AUTO.string("%n@|bold,green SUCCESS:|@ All state machines have been exported to " + outputDir.toAbsolutePath()));
|
||||
return 0;
|
||||
|
||||
@@ -53,22 +53,22 @@ public class ExportService {
|
||||
public static final Set<String> STATE_MACHINE_RETURN_TYPES = Set.of("StateMachine", "StateMachineFactory", "StateMachineModelFactory");
|
||||
|
||||
public void runExporter(Path inputDir, Path outputDir, List<String> selectedFormats, boolean renderChoicesAsDiamonds) throws IOException {
|
||||
runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, Collections.emptyList(), click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn);
|
||||
runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, Collections.emptyList(), null, null, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, false);
|
||||
}
|
||||
|
||||
public void runExporter(Path inputDir, Path outputDir, List<String> selectedFormats, boolean renderChoicesAsDiamonds, List<String> activeProfiles) throws IOException {
|
||||
runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, activeProfiles, null, null, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn);
|
||||
runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, activeProfiles, null, null, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, false);
|
||||
}
|
||||
|
||||
public void runExporter(Path inputDir, Path outputDir, List<String> selectedFormats, boolean renderChoicesAsDiamonds, List<String> activeProfiles, Path flowsOverride, String machineFilter) throws IOException {
|
||||
runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, activeProfiles, flowsOverride, machineFilter, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn);
|
||||
runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, activeProfiles, flowsOverride, machineFilter, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, false);
|
||||
}
|
||||
|
||||
public void runExporter(Path inputDir, Path outputDir, List<String> selectedFormats, boolean renderChoicesAsDiamonds, List<String> activeProfiles, click.kamil.springstatemachineexporter.exporter.EnumFormat eventFormat, click.kamil.springstatemachineexporter.exporter.EnumFormat stateFormat) throws IOException {
|
||||
runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, activeProfiles, null, null, eventFormat, stateFormat);
|
||||
runExporter(inputDir, outputDir, selectedFormats, renderChoicesAsDiamonds, activeProfiles, null, null, eventFormat, stateFormat, false);
|
||||
}
|
||||
|
||||
public void runExporter(Path inputDir, Path outputDir, List<String> selectedFormats, boolean renderChoicesAsDiamonds, List<String> activeProfiles, Path flowsOverride, String machineFilter, click.kamil.springstatemachineexporter.exporter.EnumFormat eventFormat, click.kamil.springstatemachineexporter.exporter.EnumFormat stateFormat) throws IOException {
|
||||
public void runExporter(Path inputDir, Path outputDir, List<String> selectedFormats, boolean renderChoicesAsDiamonds, List<String> activeProfiles, Path flowsOverride, String machineFilter, click.kamil.springstatemachineexporter.exporter.EnumFormat eventFormat, click.kamil.springstatemachineexporter.exporter.EnumFormat stateFormat, boolean resolveClasspath) throws IOException {
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.setActiveProfiles(activeProfiles);
|
||||
|
||||
@@ -94,6 +94,18 @@ public class ExportService {
|
||||
.collect(Collectors.toList());
|
||||
log.info("Setting JDT sourcepath: {}", sourcepaths);
|
||||
context.setSourcepath(sourcepaths);
|
||||
|
||||
if (resolveClasspath) {
|
||||
click.kamil.springstatemachineexporter.analysis.service.DynamicClasspathResolver classpathResolver = new click.kamil.springstatemachineexporter.analysis.service.DynamicClasspathResolver();
|
||||
List<String> dynamicClasspath = classpathResolver.resolveClasspath(projectRoot);
|
||||
if (!dynamicClasspath.isEmpty()) {
|
||||
context.setClasspath(dynamicClasspath);
|
||||
log.info("Injected {} external JARs into JDT ASTParser", dynamicClasspath.size());
|
||||
}
|
||||
} else {
|
||||
log.info("Dynamic classpath resolution disabled. Use --resolve-classpath to enable.");
|
||||
}
|
||||
|
||||
context.setResolveBindings(true);
|
||||
|
||||
Path hintsFile = inputDir.resolve("hints.json");
|
||||
|
||||
@@ -4,7 +4,7 @@ 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.analysis.resolver.ConstantResolver;
|
||||
import click.kamil.springstatemachineexporter.analysis.service.CallGraphBuilder;
|
||||
import click.kamil.springstatemachineexporter.analysis.service.HeuristicCallGraphEngine;
|
||||
import click.kamil.springstatemachineexporter.analysis.service.GenericEventDetector;
|
||||
import click.kamil.springstatemachineexporter.analysis.service.SpringMvcDetector;
|
||||
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
|
||||
@@ -76,7 +76,7 @@ public class InheritedEventDetectionTest {
|
||||
assertThat(tp.getEvent()).isEqualTo("event");
|
||||
|
||||
// Build Call Chains
|
||||
CallGraphBuilder callGraphBuilder = new CallGraphBuilder(context);
|
||||
HeuristicCallGraphEngine callGraphBuilder = new HeuristicCallGraphEngine(context);
|
||||
List<CallChain> chains = callGraphBuilder.findChains(entryPoints, triggers);
|
||||
|
||||
assertThat(chains).describedAs("Should link ChildController.trigger to BaseController.send").hasSize(1);
|
||||
|
||||
@@ -143,15 +143,47 @@ class TransitionLinkerEnricherTest {
|
||||
assertThat(updatedChain.getMatchedTransitions()).hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
void shouldMatchMethodCallWildcard() {
|
||||
void shouldMatchBaseEventDespiteScrapedPolyEvents() {
|
||||
Transition t1 = new Transition();
|
||||
t1.setSourceStates(List.of(State.of("NEW", "NEW")));
|
||||
t1.setTargetStates(List.of(State.of("PAID", "PAID")));
|
||||
// State machine uses the base event generically
|
||||
t1.setEvent(Event.of("BaseEvent", "BaseEvent"));
|
||||
|
||||
// Trigger point uses "BaseEvent", but polyEvents scraped some implementation/constants
|
||||
CallChain chain = CallChain.builder()
|
||||
.triggerPoint(TriggerPoint.builder()
|
||||
.event("BaseEvent")
|
||||
.polymorphicEvents(List.of("EVENT_A", "EVENT_B"))
|
||||
.build())
|
||||
.contextMachineId("testMachine")
|
||||
.build();
|
||||
|
||||
AnalysisResult result = AnalysisResult.builder()
|
||||
.name("testMachine")
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chain)).build())
|
||||
.build();
|
||||
|
||||
enricher.enrich(result, null, null);
|
||||
|
||||
// It should match because smEvent matches triggerEvent directly, overriding the failed poly search
|
||||
CallChain updatedChain = result.getMetadata().getCallChains().get(0);
|
||||
assertThat(updatedChain.getMatchedTransitions()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotMatchArbitraryGetXMethodWildcard() {
|
||||
Transition t1 = new Transition();
|
||||
t1.setSourceStates(List.of(State.of("NEW", "NEW")));
|
||||
t1.setTargetStates(List.of(State.of("PAID", "PAID")));
|
||||
t1.setEvent(Event.of("PAY", "PAY"));
|
||||
|
||||
CallChain chain = CallChain.builder()
|
||||
.triggerPoint(TriggerPoint.builder().event("richEvent.getType()").build())
|
||||
.triggerPoint(TriggerPoint.builder().event("richEvent.getId()").build())
|
||||
.contextMachineId("testMachine")
|
||||
.build();
|
||||
|
||||
@@ -164,7 +196,7 @@ class TransitionLinkerEnricherTest {
|
||||
enricher.enrich(result, null, null);
|
||||
|
||||
CallChain updatedChain = result.getMetadata().getCallChains().get(0);
|
||||
assertThat(updatedChain.getMatchedTransitions()).hasSize(1);
|
||||
assertThat(updatedChain.getMatchedTransitions()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -190,4 +222,190 @@ class TransitionLinkerEnricherTest {
|
||||
CallChain updatedChain = result.getMetadata().getCallChains().get(0);
|
||||
assertThat(updatedChain.getMatchedTransitions()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotFalsePositiveOnSubstringContains() {
|
||||
// This test proves that the heuristic is entirely removed and false positives are eliminated
|
||||
Transition t1 = new Transition();
|
||||
t1.setSourceStates(List.of(State.of("NEW", "NEW")));
|
||||
t1.setTargetStates(List.of(State.of("PAID", "PAID")));
|
||||
t1.setEvent(Event.of("PAY", "PAY"));
|
||||
|
||||
// Trigger point sends "PAYMENT" which contains "PAY". Under the old heuristics, this would falsely match!
|
||||
CallChain chain = CallChain.builder()
|
||||
.triggerPoint(TriggerPoint.builder().event("PAYMENT").build())
|
||||
.build();
|
||||
|
||||
AnalysisResult result = AnalysisResult.builder()
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chain)).build())
|
||||
.build();
|
||||
|
||||
enricher.enrich(result, null, null);
|
||||
|
||||
// It should NOT match, because "PAYMENT" != "PAY" strictly.
|
||||
CallChain updatedChain = result.getMetadata().getCallChains().get(0);
|
||||
assertThat(updatedChain.getMatchedTransitions()).isNullOrEmpty();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void shouldFilterCrossStateMachineRoutingByVertical() {
|
||||
Transition t1 = new Transition();
|
||||
t1.setSourceStates(List.of(State.of("NEW", "NEW")));
|
||||
t1.setTargetStates(List.of(State.of("ASSEMBLED", "ASSEMBLED")));
|
||||
t1.setEvent(Event.of("ASSEMBLE", "ASSEMBLE"));
|
||||
|
||||
CallChain chain = CallChain.builder()
|
||||
.triggerPoint(TriggerPoint.builder().event("ASSEMBLE").build())
|
||||
.methodChain(List.of(
|
||||
"com.example.electronics.ElectronicsOrderController.post()",
|
||||
"com.example.electronics.ElectronicsOrderService.processOrderEvent()"
|
||||
))
|
||||
.build();
|
||||
|
||||
// Testing against Electronics SM - should match
|
||||
AnalysisResult resultElectronics = AnalysisResult.builder()
|
||||
.name("com.example.electronics.ElectronicsOwnDeliveryStateMachineConfiguration")
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chain)).build())
|
||||
.build();
|
||||
|
||||
enricher.enrich(resultElectronics, null, null);
|
||||
CallChain updatedChainElec = resultElectronics.getMetadata().getCallChains().get(0);
|
||||
assertThat(updatedChainElec.getMatchedTransitions()).hasSize(1);
|
||||
|
||||
// Testing against ComputerStore SM - should NOT match because chain has Electronics service
|
||||
AnalysisResult resultComputer = AnalysisResult.builder()
|
||||
.name("com.example.computerstore.OwnDeliveryStateMachineConfiguration") // the non-electronics one
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chain)).build())
|
||||
.build();
|
||||
|
||||
enricher.enrich(resultComputer, null, null);
|
||||
CallChain updatedChainComp = resultComputer.getMetadata().getCallChains().get(0);
|
||||
assertThat(updatedChainComp.getMatchedTransitions()).isNullOrEmpty();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void shouldAllowSharedServicesToRouteToMultipleStateMachines() {
|
||||
Transition t1 = new Transition();
|
||||
t1.setSourceStates(List.of(State.of("NEW", "NEW")));
|
||||
t1.setTargetStates(List.of(State.of("PROCESSED", "PROCESSED")));
|
||||
t1.setEvent(Event.of("PROCESS", "PROCESS"));
|
||||
|
||||
// Chain contains NO vertical prefix (e.g. CommonOrderService)
|
||||
CallChain chain = CallChain.builder()
|
||||
.triggerPoint(TriggerPoint.builder().event("PROCESS").build())
|
||||
.methodChain(List.of(
|
||||
"com.example.CommonOrderController.post()",
|
||||
"com.example.CommonOrderService.processOrderEvent()"
|
||||
))
|
||||
.build();
|
||||
|
||||
AnalysisResult resultElectronics = AnalysisResult.builder()
|
||||
.name("com.example.electronics.ElectronicsOwnDeliveryStateMachineConfiguration")
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chain)).build())
|
||||
.build();
|
||||
|
||||
enricher.enrich(resultElectronics, null, null);
|
||||
CallChain updatedChainElec = resultElectronics.getMetadata().getCallChains().get(0);
|
||||
|
||||
// Should match Electronics because it's a shared service (no computerstore service in path)
|
||||
assertThat(updatedChainElec.getMatchedTransitions()).hasSize(1);
|
||||
|
||||
AnalysisResult resultComputer = AnalysisResult.builder()
|
||||
.name("com.example.computerstore.OwnDeliveryStateMachineConfiguration")
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chain)).build())
|
||||
.build();
|
||||
|
||||
enricher.enrich(resultComputer, null, null);
|
||||
CallChain updatedChainComp = resultComputer.getMetadata().getCallChains().get(0);
|
||||
|
||||
// Should ALSO match ComputerStore because it's a shared service
|
||||
assertThat(updatedChainComp.getMatchedTransitions()).hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void shouldFilterCrossStateMachineRoutingWithMultipleVerticals() {
|
||||
Transition t1 = new Transition();
|
||||
t1.setSourceStates(List.of(State.of("NEW", "NEW")));
|
||||
t1.setTargetStates(List.of(State.of("ASSEMBLED", "ASSEMBLED")));
|
||||
t1.setEvent(Event.of("ASSEMBLE", "ASSEMBLE"));
|
||||
|
||||
// Chain 1: Electronics
|
||||
CallChain chainElec = CallChain.builder()
|
||||
.triggerPoint(TriggerPoint.builder().event("ASSEMBLE").build())
|
||||
.methodChain(List.of("com.example.electronics.ElectronicsOrderController.post()"))
|
||||
.build();
|
||||
|
||||
// Chain 2: Furniture
|
||||
CallChain chainFurn = CallChain.builder()
|
||||
.triggerPoint(TriggerPoint.builder().event("ASSEMBLE").build())
|
||||
.methodChain(List.of("com.example.furniture.FurnitureOrderController.post()"))
|
||||
.build();
|
||||
|
||||
// Chain 3: Groceries
|
||||
CallChain chainGroc = CallChain.builder()
|
||||
.triggerPoint(TriggerPoint.builder().event("ASSEMBLE").build())
|
||||
.methodChain(List.of("com.example.groceries.GroceriesOrderController.post()"))
|
||||
.build();
|
||||
|
||||
// SM 1: Electronics
|
||||
AnalysisResult resElec = AnalysisResult.builder()
|
||||
.name("com.example.electronics.ElectronicsOwnDeliveryStateMachineConfiguration")
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chainElec, chainFurn, chainGroc)).build())
|
||||
.build();
|
||||
|
||||
// SM 2: Furniture
|
||||
AnalysisResult resFurn = AnalysisResult.builder()
|
||||
.name("com.example.furniture.FurnitureOwnDeliveryStateMachineConfiguration")
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chainElec, chainFurn, chainGroc)).build())
|
||||
.build();
|
||||
|
||||
// SM 3: Groceries
|
||||
AnalysisResult resGroc = AnalysisResult.builder()
|
||||
.name("com.example.groceries.GroceriesStateMachineConfiguration")
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chainElec, chainFurn, chainGroc)).build())
|
||||
.build();
|
||||
|
||||
// SM 4: Computer Store (The catch-all base one in computerstore package)
|
||||
AnalysisResult resComp = AnalysisResult.builder()
|
||||
.name("com.example.computerstore.OwnDeliveryStateMachineConfiguration")
|
||||
.transitions(List.of(t1))
|
||||
.metadata(CodebaseMetadata.builder().callChains(List.of(chainElec, chainFurn, chainGroc)).build())
|
||||
.build();
|
||||
|
||||
// Test Electronics SM - Should only keep Electronics Chain
|
||||
enricher.enrich(resElec, null, null);
|
||||
assertThat(resElec.getMetadata().getCallChains().get(0).getMatchedTransitions()).hasSize(1); // Elec
|
||||
assertThat(resElec.getMetadata().getCallChains().get(1).getMatchedTransitions()).isNullOrEmpty(); // Furn
|
||||
assertThat(resElec.getMetadata().getCallChains().get(2).getMatchedTransitions()).isNullOrEmpty(); // Groc
|
||||
|
||||
// Test Furniture SM - Should only keep Furniture Chain
|
||||
enricher.enrich(resFurn, null, null);
|
||||
assertThat(resFurn.getMetadata().getCallChains().get(0).getMatchedTransitions()).isNullOrEmpty(); // Elec
|
||||
assertThat(resFurn.getMetadata().getCallChains().get(1).getMatchedTransitions()).hasSize(1); // Furn
|
||||
assertThat(resFurn.getMetadata().getCallChains().get(2).getMatchedTransitions()).isNullOrEmpty(); // Groc
|
||||
|
||||
// Test Groceries SM - Should only keep Groceries Chain
|
||||
enricher.enrich(resGroc, null, null);
|
||||
assertThat(resGroc.getMetadata().getCallChains().get(0).getMatchedTransitions()).isNullOrEmpty(); // Elec
|
||||
assertThat(resGroc.getMetadata().getCallChains().get(1).getMatchedTransitions()).isNullOrEmpty(); // Furn
|
||||
assertThat(resGroc.getMetadata().getCallChains().get(2).getMatchedTransitions()).hasSize(1); // Groc
|
||||
|
||||
// Test ComputerStore SM - Should reject ALL because none belong to computerstore
|
||||
enricher.enrich(resComp, null, null);
|
||||
assertThat(resComp.getMetadata().getCallChains().get(0).getMatchedTransitions()).isNullOrEmpty(); // Elec
|
||||
assertThat(resComp.getMetadata().getCallChains().get(1).getMatchedTransitions()).isNullOrEmpty(); // Furn
|
||||
assertThat(resComp.getMetadata().getCallChains().get(2).getMatchedTransitions()).isNullOrEmpty(); // Groc
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.enricher.routing;
|
||||
|
||||
import click.kamil.springstatemachineexporter.analysis.model.CallChain;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@Tag("heuristic_bean_resolution")
|
||||
public class HeuristicBeanResolutionEngineTest {
|
||||
|
||||
private final HeuristicBeanResolutionEngine engine = new HeuristicBeanResolutionEngine();
|
||||
|
||||
@Test
|
||||
public void testDeepPackageDivergenceMismatch() {
|
||||
// This is the bug case: sharing a deep root, but diverging into different domains
|
||||
CallChain chain = CallChain.builder()
|
||||
.methodChain(Arrays.asList("com.acme.corp.division.project.orders.OrderService.pay()"))
|
||||
.build();
|
||||
|
||||
String machineName = "com.acme.corp.division.project.payments.PaymentStateMachine";
|
||||
|
||||
boolean result = engine.isRoutedToCorrectMachine(chain, machineName);
|
||||
|
||||
// They share com.acme.corp.division.project, but diverge into orders vs payments
|
||||
// This should be a strong mismatch, so it should return false
|
||||
assertFalse(result, "Deep package divergence into different domains should be rejected");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSameDomainMatch() {
|
||||
CallChain chain = CallChain.builder()
|
||||
.methodChain(Arrays.asList("com.acme.ecommerce.orders.OrderService.process()"))
|
||||
.build();
|
||||
|
||||
String machineName = "com.acme.ecommerce.orders.OrderStateMachine";
|
||||
|
||||
boolean result = engine.isRoutedToCorrectMachine(chain, machineName);
|
||||
|
||||
// Same exact domain, should match
|
||||
assertTrue(result, "Same domain should be accepted");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSubPackageMatch() {
|
||||
CallChain chain = CallChain.builder()
|
||||
.methodChain(Arrays.asList("com.acme.ecommerce.orders.impl.OrderServiceImpl.process()"))
|
||||
.build();
|
||||
|
||||
String machineName = "com.acme.ecommerce.orders.OrderStateMachine";
|
||||
|
||||
boolean result = engine.isRoutedToCorrectMachine(chain, machineName);
|
||||
|
||||
// Subpackage should match
|
||||
assertTrue(result, "Sub-packages of the same domain should be accepted");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSharedDomainTermMatch() {
|
||||
CallChain chain = CallChain.builder()
|
||||
.methodChain(Arrays.asList("com.acme.orders.web.OrderController.submit()"))
|
||||
.build();
|
||||
|
||||
String machineName = "com.acme.orders.service.OrderStateMachine";
|
||||
|
||||
boolean result = engine.isRoutedToCorrectMachine(chain, machineName);
|
||||
|
||||
// Different subpackages, but they share the "order" domain term and common prefix
|
||||
assertTrue(result, "Divergent packages that share a domain term should be accepted");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExplicitTargetVariableMatch() {
|
||||
CallChain chain = CallChain.builder()
|
||||
.methodChain(Arrays.asList("com.acme.common.GlobalTrigger.fire()"))
|
||||
.contextMachineId("paymentStateMachine") // Explicitly targets payment
|
||||
.build();
|
||||
|
||||
String machineName = "com.acme.corp.payments.PaymentStateMachine";
|
||||
|
||||
boolean result = engine.isRoutedToCorrectMachine(chain, machineName);
|
||||
|
||||
// Mismatched domains, but explicit variable targeting works
|
||||
assertTrue(result, "Explicit variable target matching the machine name should be accepted");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExplicitTargetVariableMismatch() {
|
||||
CallChain chain = CallChain.builder()
|
||||
.methodChain(Arrays.asList("com.acme.common.GlobalTrigger.fire()"))
|
||||
.contextMachineId("paymentStateMachine") // Explicitly targets payment
|
||||
.build();
|
||||
|
||||
String machineName = "com.acme.corp.orders.OrderStateMachine"; // But this is Order
|
||||
|
||||
boolean result = engine.isRoutedToCorrectMachine(chain, machineName);
|
||||
|
||||
// Explicit variable targeting completely conflicts
|
||||
assertFalse(result, "Explicit variable target mismatching the machine name should be rejected");
|
||||
}
|
||||
}
|
||||
@@ -1,957 +0,0 @@
|
||||
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 org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class CallGraphBuilderTest {
|
||||
|
||||
@Test
|
||||
void shouldFindCallChainWithLambdaMethodReference(@TempDir Path tempDir) throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderService {
|
||||
private final EventDispatcher dispatcher = new EventDispatcher();
|
||||
|
||||
public void processOrder() {
|
||||
dispatcher.dispatch("order", this::sendEvent);
|
||||
}
|
||||
|
||||
public void sendEvent(String event) {
|
||||
// Dummy trigger
|
||||
}
|
||||
}
|
||||
|
||||
class EventDispatcher {
|
||||
public void dispatch(String order, java.util.function.Consumer<String> callback) {
|
||||
callback.accept("MY_EVENT");
|
||||
}
|
||||
}
|
||||
""";
|
||||
Files.writeString(tempDir.resolve("OrderService.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("processOrder")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("sendEvent")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getMethodChain()).containsExactly(
|
||||
"com.example.OrderService.processOrder",
|
||||
"com.example.OrderService.sendEvent"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExtractContextMachineId(@TempDir Path tempDir) throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class PersisterService {
|
||||
private final StateMachinePersister persister = new StateMachinePersister();
|
||||
|
||||
public void updateOrderState(String orderId) {
|
||||
StateMachine sm = persister.restore(null, "machine:" + orderId);
|
||||
sm.sendEvent("PAY");
|
||||
}
|
||||
}
|
||||
|
||||
class StateMachinePersister {
|
||||
public StateMachine restore(Object sm, String contextObj) {
|
||||
return new StateMachine();
|
||||
}
|
||||
}
|
||||
|
||||
class StateMachine {
|
||||
public void sendEvent(String event) {}
|
||||
}
|
||||
""";
|
||||
Files.writeString(tempDir.resolve("PersisterService.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.PersisterService")
|
||||
.methodName("updateOrderState")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.StateMachine")
|
||||
.methodName("sendEvent")
|
||||
.event("PAY")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getContextMachineId()).isNotNull();
|
||||
// Since it's tracing constant concatenation: "machine:" + orderId, which might resolve dynamically or string format.
|
||||
// It should at least be present (it typically extracts 'machine:' + orderId into expression).
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveTriggerPointParametersAcrossChain() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void createOrder() {
|
||||
service.updateOrderState(OrderEvents.CREATE);
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
private StateMachine sm;
|
||||
public void updateOrderState(OrderEvents event) {
|
||||
sm.sendEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
class StateMachine {
|
||||
public void sendEvent(Object event) {}
|
||||
}
|
||||
|
||||
enum OrderEvents { CREATE, PAY }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("createOrder")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("OrderEvents.CREATE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveTriggerPointLocalVariableAcrossChain() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(MyOrderEvent domainEvent) {
|
||||
doProcessOrderEvent(domainEvent);
|
||||
}
|
||||
|
||||
private void doProcessOrderEvent(MyOrderEvent domainEvent) {
|
||||
OrderEvents eventType = domainEvent.getType();
|
||||
service.updateOrderState(eventType);
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {
|
||||
// sendEvent
|
||||
}
|
||||
}
|
||||
|
||||
class MyOrderEvent {
|
||||
public OrderEvents getType() { return OrderEvents.PAY; }
|
||||
}
|
||||
|
||||
enum OrderEvents { CREATE, PAY }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test2");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getPolymorphicEvents())
|
||||
.as("Resolved event was: " + chain.getTriggerPoint().getEvent())
|
||||
.containsExactlyInAnyOrder("OrderEvents.PAY");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolvePolymorphicInheritanceAcrossChain() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(RichOrderEvent domainEvent) {
|
||||
doProcessOrderEvent(domainEvent);
|
||||
}
|
||||
|
||||
private void doProcessOrderEvent(RichOrderEvent domainEvent) {
|
||||
OrderEvents eventType = assertSupportedOrderEvent(domainEvent.getType());
|
||||
service.updateOrderState(eventType);
|
||||
}
|
||||
|
||||
private OrderEvents assertSupportedOrderEvent(OrderEvents e) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {
|
||||
// sendEvent
|
||||
}
|
||||
}
|
||||
|
||||
interface RichOrderEvent {
|
||||
OrderEvents getType();
|
||||
}
|
||||
|
||||
class CancelOrderEvent implements RichOrderEvent {
|
||||
public OrderEvents getType() { return OrderEvents.CANCELLED; }
|
||||
}
|
||||
|
||||
class ReceiveOrderEvent implements RichOrderEvent {
|
||||
public OrderEvents getType() { return OrderEvents.RECEIVED; }
|
||||
}
|
||||
|
||||
enum OrderEvents { CREATE, PAY, CANCELLED, RECEIVED }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_poly");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getPolymorphicEvents())
|
||||
.as("Resolved event was: " + chain.getTriggerPoint().getEvent())
|
||||
.containsExactlyInAnyOrder("OrderEvents.CANCELLED", "OrderEvents.RECEIVED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldUnwrapDeepMethodWrappers() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(RichOrderEvent domainEvent) {
|
||||
OrderEvents eventType = wrap3(wrap2(wrap1(domainEvent.getType())));
|
||||
service.updateOrderState(eventType);
|
||||
}
|
||||
|
||||
private OrderEvents wrap1(OrderEvents e) { return e; }
|
||||
private OrderEvents wrap2(OrderEvents e) { return e; }
|
||||
private OrderEvents wrap3(OrderEvents e) { return e; }
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) { }
|
||||
}
|
||||
|
||||
class RichOrderEvent {
|
||||
public OrderEvents getType() { return OrderEvents.CREATE; }
|
||||
}
|
||||
|
||||
enum OrderEvents { CREATE }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_deep_wrap");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getPolymorphicEvents())
|
||||
.as("Resolved event was: " + chain.getTriggerPoint().getEvent())
|
||||
.containsExactlyInAnyOrder("OrderEvents.CREATE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolvePolymorphicInheritanceThroughDelegation() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(BaseEvent domainEvent) {
|
||||
service.updateOrderState(domainEvent.getType());
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
interface BaseEvent {
|
||||
OrderEvents getType();
|
||||
}
|
||||
|
||||
abstract class AbstractEvent implements BaseEvent {
|
||||
protected OrderEvents internalGetType() {
|
||||
return OrderEvents.PAY;
|
||||
}
|
||||
}
|
||||
|
||||
class ConcreteEvent extends AbstractEvent {
|
||||
public OrderEvents getType() {
|
||||
return internalGetType();
|
||||
}
|
||||
}
|
||||
|
||||
class AnotherConcreteEvent implements BaseEvent {
|
||||
public OrderEvents getType() {
|
||||
return delegateToHelper();
|
||||
}
|
||||
private OrderEvents delegateToHelper() {
|
||||
return OrderEvents.CANCELLED;
|
||||
}
|
||||
}
|
||||
|
||||
enum OrderEvents { PAY, CANCELLED }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_poly_delegation");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getPolymorphicEvents())
|
||||
.containsExactlyInAnyOrder("OrderEvents.PAY", "OrderEvents.CANCELLED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleMissingImplementationsGracefully() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(UnknownEvent domainEvent) {
|
||||
service.updateOrderState(domainEvent.getType());
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
// UnknownEvent is not defined in the source (e.g. from a third-party library)
|
||||
|
||||
enum OrderEvents { CREATE }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_missing_impl");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("domainEvent.getType()");
|
||||
assertThat(chain.getTriggerPoint().getPolymorphicEvents()).isNullOrEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTraceMultipleLocalVariableAssignments() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(RichOrderEvent domainEvent) {
|
||||
OrderEvents type1 = domainEvent.getType();
|
||||
OrderEvents type2 = type1;
|
||||
OrderEvents type3 = type2;
|
||||
service.updateOrderState(type3);
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
class RichOrderEvent {
|
||||
public OrderEvents getType() { return OrderEvents.RECEIVED; }
|
||||
}
|
||||
|
||||
enum OrderEvents { RECEIVED }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_multiple_assign");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getPolymorphicEvents())
|
||||
.containsExactlyInAnyOrder("OrderEvents.RECEIVED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveMethodInheritedFromAbstractBaseClass() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(BaseEvent domainEvent) {
|
||||
service.updateOrderState(domainEvent.getType());
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
interface BaseEvent {
|
||||
OrderEvents getType();
|
||||
}
|
||||
|
||||
abstract class AbstractEvent implements BaseEvent {
|
||||
public OrderEvents getType() {
|
||||
return OrderEvents.PAY;
|
||||
}
|
||||
}
|
||||
|
||||
// Concrete subclass inherits getType() but doesn't override it!
|
||||
class InheritingEvent extends AbstractEvent {
|
||||
}
|
||||
|
||||
enum OrderEvents { PAY }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_inherited");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getPolymorphicEvents())
|
||||
.containsExactlyInAnyOrder("OrderEvents.PAY");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldStopTracingRecursiveMethodsGracefully() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(RecursiveEvent domainEvent) {
|
||||
service.updateOrderState(domainEvent.getType());
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
class RecursiveEvent {
|
||||
public OrderEvents getType() {
|
||||
return this.getType();
|
||||
}
|
||||
}
|
||||
|
||||
enum OrderEvents { PAY }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_recursive");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
// Should safely complete without stack overflow and return an empty result
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("domainEvent.getType()");
|
||||
assertThat(chain.getTriggerPoint().getPolymorphicEvents()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleChainedMethodCallsGracefully() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(EventWrapper wrapper) {
|
||||
service.updateOrderState(wrapper.getEvent().getType());
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
class EventWrapper {
|
||||
public RichEvent getEvent() { return new RichEvent(); }
|
||||
}
|
||||
|
||||
class RichEvent {
|
||||
public OrderEvents getType() { return OrderEvents.PAY; }
|
||||
}
|
||||
|
||||
enum OrderEvents { PAY }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_chained");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
// It might not fully resolve chained method calls, but it must not crash!
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("wrapper.getEvent().getType()");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTraceStaticFieldReferences() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private static final OrderEvents CONSTANT_EVENT = OrderEvents.CANCELLED;
|
||||
private OrderService service;
|
||||
public void processOrderEvent() {
|
||||
service.updateOrderState(CONSTANT_EVENT);
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
enum OrderEvents { CANCELLED }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_static_field");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("OrderEvents.CANCELLED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleAnonymousInnerClassesGracefully() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent() {
|
||||
RichEvent event = new RichEvent() {
|
||||
public OrderEvents getType() {
|
||||
return OrderEvents.CREATE;
|
||||
}
|
||||
};
|
||||
service.updateOrderState(event.getType());
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
interface RichEvent {
|
||||
OrderEvents getType();
|
||||
}
|
||||
|
||||
enum OrderEvents { CREATE }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_anonymous");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
// It successfully traces the local variable 'event' to its anonymous class initializer
|
||||
assertThat(chain.getTriggerPoint().getEvent()).startsWith("new RichEvent(){");
|
||||
assertThat(chain.getTriggerPoint().getEvent()).endsWith(".getType()");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldLinkCallsInsideLambdasToEnclosingMethod() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent() {
|
||||
Runnable r = () -> service.updateOrderState(OrderEvents.PAY);
|
||||
r.run();
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
enum OrderEvents { PAY }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_lambda_scope");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("OrderEvents.PAY");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleTernaryOperatorsGracefully() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent(boolean flag) {
|
||||
OrderEvents event = flag ? OrderEvents.PAY : OrderEvents.CANCELLED;
|
||||
service.updateOrderState(event);
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
enum OrderEvents { PAY, CANCELLED }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_ternary");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
// It should gracefully fallback to the string representation of the ternary operator
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("flag ? OrderEvents.PAY : OrderEvents.CANCELLED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTraceLastTextualAssignmentInTryCatchBlocks() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent() {
|
||||
OrderEvents event;
|
||||
try {
|
||||
event = OrderEvents.PAY;
|
||||
} catch (Exception e) {
|
||||
event = OrderEvents.CANCELLED;
|
||||
}
|
||||
service.updateOrderState(event);
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
enum OrderEvents { PAY, CANCELLED }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_try_catch");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
// The ASTVisitor picks up Assignments in textual order.
|
||||
// CANCELLED is the last one textually in the method.
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("OrderEvents.CANCELLED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTraceArrayAndCollectionAccessGracefully() throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderController {
|
||||
private OrderService service;
|
||||
public void processOrderEvent() {
|
||||
OrderEvents[] events = new OrderEvents[]{OrderEvents.PAY};
|
||||
service.updateOrderState(events[0]);
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
public void updateOrderState(OrderEvents event) {}
|
||||
}
|
||||
|
||||
enum OrderEvents { PAY }
|
||||
""";
|
||||
Path tempDir = Files.createTempDirectory("callgraph_test_array");
|
||||
Files.writeString(tempDir.resolve("OrderConfig.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
CallGraphBuilder builder = new CallGraphBuilder(context);
|
||||
|
||||
EntryPoint entryPoint = EntryPoint.builder()
|
||||
.className("com.example.OrderController")
|
||||
.methodName("processOrderEvent")
|
||||
.build();
|
||||
|
||||
TriggerPoint trigger = TriggerPoint.builder()
|
||||
.className("com.example.OrderService")
|
||||
.methodName("updateOrderState")
|
||||
.event("event")
|
||||
.build();
|
||||
|
||||
List<CallChain> chains = builder.findChains(List.of(entryPoint), List.of(trigger));
|
||||
|
||||
assertThat(chains).hasSize(1);
|
||||
CallChain chain = chains.get(0);
|
||||
// We don't dynamically resolve array indexes, but it shouldn't crash.
|
||||
// It returns the array access expression as a string.
|
||||
assertThat(chain.getTriggerPoint().getEvent()).isEqualTo("events[0]");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.service;
|
||||
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@Tag("dynamic_classpath_resolver")
|
||||
class DynamicClasspathResolverTest {
|
||||
|
||||
@Test
|
||||
void shouldResolveMavenClasspathDynamically(@TempDir Path tempDir) throws IOException {
|
||||
// Create dummy pom.xml
|
||||
Files.createFile(tempDir.resolve("pom.xml"));
|
||||
|
||||
// Mock the resolver so it doesn't actually run maven, but writes the expected output file
|
||||
DynamicClasspathResolver resolver = new DynamicClasspathResolver() {
|
||||
@Override
|
||||
protected void runProcess(ProcessBuilder pb) throws IOException {
|
||||
// Pretend maven executed and generated the cp.txt
|
||||
String cp = "/fake/m2/repo/spring-core.jar" + File.pathSeparator + "/fake/m2/repo/spring-context.jar";
|
||||
|
||||
String outputFileArg = pb.command().stream()
|
||||
.filter(arg -> arg.startsWith("-Dmdep.outputFile="))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
Path outputFile = Path.of(outputFileArg.substring("-Dmdep.outputFile=".length()));
|
||||
|
||||
Files.writeString(outputFile, cp);
|
||||
}
|
||||
};
|
||||
|
||||
List<String> classpath = resolver.resolveClasspath(tempDir);
|
||||
|
||||
assertThat(classpath).containsExactly(
|
||||
"/fake/m2/repo/spring-core.jar",
|
||||
"/fake/m2/repo/spring-context.jar"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveGradleClasspathDynamically(@TempDir Path tempDir) throws IOException {
|
||||
// Create dummy build.gradle
|
||||
Files.createFile(tempDir.resolve("build.gradle"));
|
||||
|
||||
DynamicClasspathResolver resolver = new DynamicClasspathResolver() {
|
||||
@Override
|
||||
protected String runProcessAndGetOutput(ProcessBuilder pb) {
|
||||
// Pretend gradle executed and printed the marker
|
||||
String cp = "/fake/gradle/caches/spring-core.jar" + File.pathSeparator + "/fake/gradle/caches/spring-context.jar";
|
||||
return "Some noisy gradle output\n" +
|
||||
"SME_CLASSPATH_MARKER:" + cp + "\n" +
|
||||
"BUILD SUCCESSFUL\n";
|
||||
}
|
||||
};
|
||||
|
||||
List<String> classpath = resolver.resolveClasspath(tempDir);
|
||||
|
||||
assertThat(classpath).containsExactly(
|
||||
"/fake/gradle/caches/spring-core.jar",
|
||||
"/fake/gradle/caches/spring-context.jar"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnEmptyListIfNoBuildFileFound(@TempDir Path tempDir) {
|
||||
DynamicClasspathResolver resolver = new DynamicClasspathResolver();
|
||||
List<String> classpath = resolver.resolveClasspath(tempDir);
|
||||
assertThat(classpath).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package click.kamil.springstatemachineexporter.analysis.service;
|
||||
|
||||
import click.kamil.springstatemachineexporter.analysis.model.TriggerPoint;
|
||||
import click.kamil.springstatemachineexporter.analysis.resolver.ConstantResolver;
|
||||
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@Tag("control_flow_sibling_avoidance")
|
||||
class GenericEventDetectorControlFlowTest {
|
||||
|
||||
@Test
|
||||
void shouldDetectStateFromDirectIfWrapper(@TempDir Path tempDir) throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderService {
|
||||
private StateMachine sm;
|
||||
public void processOrder(OrderState state) {
|
||||
if (state == OrderState.PENDING) {
|
||||
sm.sendEvent(OrderEvent.PAY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class StateMachine {
|
||||
public void sendEvent(OrderEvent e) {}
|
||||
}
|
||||
|
||||
enum OrderState { PENDING }
|
||||
enum OrderEvent { PAY }
|
||||
""";
|
||||
Files.writeString(tempDir.resolve("OrderService.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
GenericEventDetector detector = new GenericEventDetector(context, new ConstantResolver(), Collections.emptyList());
|
||||
List<TriggerPoint> triggers = detector.detect((org.eclipse.jdt.core.dom.CompilationUnit) context.getTypeDeclaration("com.example.OrderService").getRoot());
|
||||
|
||||
assertThat(triggers).hasSize(1);
|
||||
TriggerPoint tp = triggers.get(0);
|
||||
assertThat(tp.getEvent()).isEqualTo("OrderEvent.PAY");
|
||||
assertThat(tp.getSourceState()).isEqualTo("PENDING");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDetectStateFromGuardClauseSibling(@TempDir Path tempDir) throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderService {
|
||||
private StateMachine sm;
|
||||
public void processOrder(OrderState state) {
|
||||
if (state != OrderState.PENDING) {
|
||||
return;
|
||||
}
|
||||
|
||||
sm.sendEvent(OrderEvent.PAY);
|
||||
}
|
||||
}
|
||||
|
||||
class StateMachine {
|
||||
public void sendEvent(OrderEvent e) {}
|
||||
}
|
||||
|
||||
enum OrderState { PENDING }
|
||||
enum OrderEvent { PAY }
|
||||
""";
|
||||
Files.writeString(tempDir.resolve("OrderService.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
GenericEventDetector detector = new GenericEventDetector(context, new ConstantResolver(), Collections.emptyList());
|
||||
List<TriggerPoint> triggers = detector.detect((org.eclipse.jdt.core.dom.CompilationUnit) context.getTypeDeclaration("com.example.OrderService").getRoot());
|
||||
|
||||
assertThat(triggers).hasSize(1);
|
||||
TriggerPoint tp = triggers.get(0);
|
||||
assertThat(tp.getEvent()).isEqualTo("OrderEvent.PAY");
|
||||
assertThat(tp.getSourceState()).isEqualTo("PENDING");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDetectStateFromSwitchCaseSibling(@TempDir Path tempDir) throws IOException {
|
||||
String source = """
|
||||
package com.example;
|
||||
public class OrderService {
|
||||
private StateMachine sm;
|
||||
public void processOrder(OrderState state) {
|
||||
switch (state) {
|
||||
case PENDING:
|
||||
sm.sendEvent(OrderEvent.PAY);
|
||||
break;
|
||||
case PAID:
|
||||
sm.sendEvent(OrderEvent.SHIP);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class StateMachine {
|
||||
public void sendEvent(OrderEvent e) {}
|
||||
}
|
||||
|
||||
enum OrderState { PENDING, PAID }
|
||||
enum OrderEvent { PAY, SHIP }
|
||||
""";
|
||||
Files.writeString(tempDir.resolve("OrderService.java"), source);
|
||||
|
||||
CodebaseContext context = new CodebaseContext();
|
||||
context.scan(tempDir);
|
||||
|
||||
GenericEventDetector detector = new GenericEventDetector(context, new ConstantResolver(), Collections.emptyList());
|
||||
List<TriggerPoint> triggers = detector.detect((org.eclipse.jdt.core.dom.CompilationUnit) context.getTypeDeclaration("com.example.OrderService").getRoot());
|
||||
|
||||
assertThat(triggers).hasSize(2);
|
||||
|
||||
TriggerPoint payTrigger = triggers.stream().filter(t -> t.getEvent().equals("OrderEvent.PAY")).findFirst().get();
|
||||
assertThat(payTrigger.getSourceState()).isEqualTo("PENDING");
|
||||
|
||||
TriggerPoint shipTrigger = triggers.stream().filter(t -> t.getEvent().equals("OrderEvent.SHIP")).findFirst().get();
|
||||
assertThat(shipTrigger.getSourceState()).isEqualTo("PAID");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -238,10 +238,27 @@
|
||||
.tooltip-content {
|
||||
padding: 20px;
|
||||
max-width: 500px;
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Custom Scrollbar for Tooltips */
|
||||
.tooltip-content::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
.tooltip-content::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
.tooltip-content::-webkit-scrollbar-thumb {
|
||||
background: #cbd5e1;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.tooltip-content::-webkit-scrollbar-thumb:hover {
|
||||
background: #94a3b8;
|
||||
}
|
||||
|
||||
.payload-box {
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
|
||||
@@ -81,13 +81,6 @@ public class HtmlExporterTest {
|
||||
|
||||
// 7. Assertions - Surgical SVG Identification
|
||||
// Every event should be wrapped in an identifying hyperlink for robust JS selection
|
||||
java.nio.file.Files.writeString(java.nio.file.Paths.get("debug_html.html"), html);
|
||||
|
||||
click.kamil.springstatemachineexporter.exporter.ExportOptions plantUmlOptions = click.kamil.springstatemachineexporter.exporter.ExportOptions.builder()
|
||||
.embedIdentifiers(true)
|
||||
.build();
|
||||
click.kamil.springstatemachineexporter.exporter.PlantUml pumlExporter = new click.kamil.springstatemachineexporter.exporter.PlantUml();
|
||||
java.nio.file.Files.writeString(java.nio.file.Paths.get("debug_puml.puml"), pumlExporter.export(result, plantUmlOptions));
|
||||
|
||||
assertThat(html).contains("__CREATE");
|
||||
assertThat(html).contains("__ASSIGN");
|
||||
|
||||
Reference in New Issue
Block a user