All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eu.lucaventuri.fibry.fsm.FsmTemplate Maven / Gradle / Ivy

There is a newer version: 3.0.1
Show newest version
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);
        }
    }
}