package org.jboss.util.state;
import java.util.HashSet;
import java.util.Set;
import java.util.Iterator;
import org.jboss.logging.Logger;
public class StateMachine implements Cloneable
{
private static Logger log = Logger.getLogger(StateMachine.class);
private String description;
private HashSet states;
private State startState;
private State currentState;
public StateMachine(Set states, State startState)
{
this(states, startState, null);
}
public StateMachine(Set states, State startState, String description)
{
this.states = new HashSet(states);
this.startState = startState;
this.currentState = startState;
this.description = description;
}
public Object clone()
{
StateMachine clone = new StateMachine(states, startState, description);
clone.currentState = currentState;
return clone;
}
public String getDescription()
{
return description;
}
public State getCurrentState()
{
return currentState;
}
public State getStartState()
{
return startState;
}
public Set getStates()
{
return states;
}
public State nextState(String actionName)
throws IllegalTransitionException
{
Transition t = currentState.getTransition(actionName);
if( t == null )
{
String msg = "No transition for action: " + actionName
+ " from state:" + currentState.getName();
throw new IllegalTransitionException(msg);
}
State nextState = t.getTarget();
log.trace("nextState("+actionName+") = "+nextState);
currentState = nextState;
return currentState;
}
public State reset()
{
this.currentState = startState;
return currentState;
}
public String toString()
{
StringBuffer tmp = new StringBuffer("StateMachine[:\n");
tmp.append("\tCurrentState: "+currentState.getName());
tmp.append('\n');
Iterator i = states.iterator();
while( i.hasNext() )
{
tmp.append(i.next());
}
tmp.append(']');
return tmp.toString();
}
}