Created
November 18, 2022 06:41
-
-
Save phlego/108479f7f9a7d4327f3326a5c729419c to your computer and use it in GitHub Desktop.
Generate Mermaid Diagram from Spring State Machine
This file contains 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 com.phl.statemachine; | |
import org.springframework.statemachine.StateMachine; | |
public class StateMachineMermaidGenerator { | |
public static <S, E> String generate(StateMachine<S, E> stateMachine) { | |
System.out.println("Generating mermaid 🧜\n"); | |
StringBuilder mmBuilder = new StringBuilder(); | |
mmBuilder.append("%% States %%\n"); | |
generateStates(stateMachine, mmBuilder); | |
mmBuilder.append("\n%% Transitions %%\n"); | |
generateTransitions(stateMachine, mmBuilder); | |
return mmBuilder.toString(); | |
} | |
private static <S, E> void generateStates(StateMachine<S, E> stateMachine, StringBuilder mmBuilder) { | |
stateMachine.getStates().forEach(state -> mmBuilder.append(String.format("%s(%s)\n", state.getId(), state.getId()))); | |
} | |
private static <S, E> void generateTransitions(StateMachine<S, E> stateMachine, StringBuilder mmBuilder) { | |
stateMachine.getTransitions().forEach(transition -> { | |
S source = transition.getSource().getId(); | |
S target = transition.getTarget().getId(); | |
E event = transition.getTrigger().getEvent(); | |
mmBuilder.append(String.format("%s -->|%s| %s\n", source, event, target)); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had made some little improvments on this generator :