Giter Site home page Giter Site logo

easy-states's Introduction


Easy States
The simple, stupid finite state machine for Java™

MIT license Build Status Maven Central Javadoc


Latest news

  • 13/03/2020: Version 2.0.0 is now released! This version is based on Java 8 and comes with a number of enhancements. Take a look at the release notes for all details.

What is Easy States?

Easy States is an event-driven Deterministic Finite Automaton implementation in Java.

It is inspired by Erlang design principles which describe a Finite State Machine as a set of relations of the form:

State(S) x Event(E) -> Actions(A), State(S')

These relations are interpreted like follows:

If we are in state S and the event E occurs, we should perform action(s) A and make a transition to the state S'.

How does it work?

Easy States provides APIs for key concepts of state machines:

  • State: a particular state on which the machine can be at a given point in time
  • Event: represents an event that may trigger an action and change the state of the machine
  • Transition: represents a transition between two states of the machine when an event occurs
  • FiniteStateMachine: core abstraction of a finite state machine

Using Easy States, you can define FSM transitions with an intuitive fluent API:

Transition t = new TransitionBuilder()
        .sourceState(s0) //if we are in state s0
        .eventType(Event.class) // and the event E occurs
        .eventHandler(myActionA) // we should perform the actions A
        .targetState(s1) // and make a transition to the state s1
        .build();

How to use it?

Easy States has no dependencies. You can download the easy-states-2.0.0.jar file and add it to your application's classpath. If you use maven, add the following dependency to your pom.xml:

<dependency>
    <groupId>org.jeasy</groupId>
    <artifactId>easy-states</artifactId>
    <version>2.0.0</version>
</dependency>

Easy States requires a Java 8+ runtime.

Two minutes tutorial

This tutorial is an implementation of the turnstile example described in wikipedia:

A turnstile has two states: Locked and Unlocked. There are two inputs that affect its state: putting a coin in the slot (coin) and pushing the arm (push). In the locked state, pushing on the arm has no effect; no matter how many times the input push is given it stays in the locked state. Putting a coin in, that is giving the machine a coin input, shifts the state from Locked to Unlocked. In the unlocked state, putting additional coins in has no effect; that is, giving additional coin inputs does not change the state.

turnsitle

For this example, we define:

  • two states: Locked and Unlocked
  • two events: PushEvent and CoinEvent
  • two actions: Lock and Unlock
  • and four transitions: pushLocked, unlock, coinUnlocked and lock

1. First, let's define states

State locked = new State("locked");
State unlocked = new State("unlocked");

Set<State> states = new HashSet<>();
states.add(locked);
states.add(unlocked);

2. Then, define events

class PushEvent extends AbstractEvent { }
class CoinEvent extends AbstractEvent { }

3. Then transitions

Transition unlock = new TransitionBuilder()
        .name("unlock")
        .sourceState(locked)
        .eventType(CoinEvent.class)
        .eventHandler(new Unlock())
        .targetState(unlocked)
        .build();

Transition pushLocked = new TransitionBuilder()
        .name("pushLocked")
        .sourceState(locked)
        .eventType(PushEvent.class)
        .targetState(locked)
        .build();

Transition lock = new TransitionBuilder()
        .name("lock")
        .sourceState(unlocked)
        .eventType(PushEvent.class)
        .eventHandler(new Lock())
        .targetState(locked)
        .build();

Transition coinUnlocked = new TransitionBuilder()
        .name("coinUnlocked")
        .sourceState(unlocked)
        .eventType(CoinEvent.class)
        .targetState(unlocked)
        .build();

4. And finally the finite state machine

FiniteStateMachine turnstileStateMachine = new FiniteStateMachineBuilder(states, locked)
        .registerTransition(lock)
        .registerTransition(pushLocked)
        .registerTransition(unlock)
        .registerTransition(coinUnlocked)
        .build();

The complete code of this tutorial can be found here.

To run the tutorial, please follow these instructions:

$>git clone https://github.com/j-easy/easy-states.git
$>cd easy-states
$>mvn install
$>mvn exec:java -P runTurnstileTutorial

You will be able to fire events interactively from the console and check the evolution of the machine's state.

License

Easy States is released under the terms of the MIT License:

The MIT License

   Copyright (c) 2020, Mahmoud Ben Hassine ([email protected])

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.

easy-states's People

Contributors

dependabot[bot] avatar fmbenhassine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

easy-states's Issues

Improve JUL log format

The default log format for JUL is not the best one (it spans two lines, the default date format is not compact, it does not show milliseconds, etc)

The JUL default log format should be changed to: %1$tF %tT.%1$tL %4$s [%2$s] - %5$s %6$s%n which is known to be better.

Event should be an interface

As of v1.0.1, org.jeasy.states.api.Event is an abstract class. It is better to change it into an interface and rename the current abstract class to AbstractEvent.

How to have transitions with duration?

Hi, by looking at the code and the example, it seems to me like transitions are instant (so the name feels slightly misleading). But maybe I didn't grasp the details...

I'm thinking of two cases: animated transitions of variable duration and synchronous calls (for instance download a file from the web, and when the file is downloaded, the transition is complete).

Could you suggest how to implement such cases?

Thank you! Also for sharing your code :)

Make EventHandler generic

As of v1.0.1, the EventHandler interface is not generic. This requires a cast when using custom events:

public class MyEvent extends Event {
    
}

public class MyEventHandler implements EventHandler {
	
	@Override
	public void handleEvent(Event event) throws Exception {
		if (event instanceof MyEvent) {
			MyEvent myEvent = (MyEvent) event;
			// do something with myEvent
		}
	}
}

The EventHandler interface should be something like:

public interface EventHandler<E extends Event> {
    void handleEvent(E event) throws Exception;
}

to eliminate the need to do the cast.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.