eu.lucaventuri.fibry.fsm.FsmTemplate Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fibry Show documentation
Show all versions of fibry Show documentation
The first Java Actor System supporting fibers from Project Loom
package eu.lucaventuri.fibry.fsm;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Finite State machine
*
* @param Type of the states, from an enum
* @param Type of the messages (they will need to support equals)
*/
public class FsmTemplate>, I> {
final Map> mapStates;
public FsmTemplate(Map> mapEnums) {
this.mapStates = new HashMap<>();
ingestKeys(mapEnums);
ingestTransitions(mapEnums);
}
public FsmConsumer newFsmConsumer(S state) {
return new FsmConsumer<>(mapStates, state);
}
/* public FsmActor newFsmActor(S state) {
return new FsmActor<>(mapStates, state);
}*/
private void ingestTransitions(Map> mapEnums) {
for (var st : mapEnums.entrySet()) {
var state = mapStates.get(st.getKey());
for (var tr : st.getValue().transtions) {
state.addTransition(convert(tr));
}
}
}
private TransitionState convert(TransitionEnum tr) {
var targetState = mapStates.get(tr.targetState);
return new TransitionState<>(tr.event, targetState);
}
private void ingestKeys(Map> mapEnums) {
for (var state : mapEnums.entrySet()) {
mapStates.put(state.getKey(), new State(state.getKey(), state.getValue().consumer));
}
if (mapStates.size() < 2)
throw new IllegalArgumentException("You need at least 2 states!");
var usedStates = mapEnums.values().stream().flatMap(state -> state.transtions.stream().map(transition -> transition.targetState)).distinct().collect(Collectors.toList());
for (var st : usedStates) {
if (!mapStates.keySet().contains(st))
throw new IllegalArgumentException("Transition to unknown state " + st);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy