Created
February 5, 2025 03:10
-
-
Save jalotra/cb5bf249aa07f7c78a9b0e383b9bae15 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ai.cbx1.commons.statemachine; | |
// This class gives out methods to take in a list of transitions and turn it into a .dot file | |
// you can use any online digraph visualiser to see the output | |
import static guru.nidi.graphviz.model.Factory.*; | |
import guru.nidi.graphviz.attribute.*; | |
import guru.nidi.graphviz.model.MutableGraph; | |
import guru.nidi.graphviz.model.MutableNode; | |
import java.util.HashMap; | |
import java.util.Map; | |
import org.springframework.statemachine.StateMachine; | |
import org.springframework.statemachine.state.State; | |
import org.springframework.statemachine.transition.Transition; | |
public class StateMachineVisualiser<S, E> { | |
public String getDiagram(StateMachine<S, E> stateMachine, String graphName) { | |
MutableGraph graph = mutGraph(graphName) | |
.setDirected(true) | |
.graphAttrs() | |
.add( | |
Attributes.attr("rankdir", "LR"), | |
Attributes.attr("nodesep", "1.0"), | |
Attributes.attr("ranksep", "1.2"), | |
Attributes.attr("pad", "0.5"), | |
Attributes.attr("fontname", "helvetica")); | |
Map<S, MutableNode> nodes = new HashMap<>(); | |
for (State<S, E> state : stateMachine.getStates()) { | |
MutableNode node = mutNode(state.getId().toString()); | |
if (state.getId().equals(stateMachine.getInitialState().getId())) { | |
node.add(Shape.RECTANGLE).add(Color.LIGHTBLUE).add(Style.ROUNDED); | |
} | |
nodes.put(state.getId(), node); | |
graph.add(node); | |
} | |
for (Transition<S, E> transition : stateMachine.getTransitions()) { | |
MutableNode source = nodes.get(transition.getSource().getId()); | |
MutableNode target = nodes.get(transition.getTarget().getId()); | |
E event = transition.getTrigger().getEvent(); | |
source.addLink(to(target).with(Label.of(event.toString()), Style.SOLID, Color.GREEN, Font.size(10))); | |
} | |
return graph.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment