1 22 package org.jboss.util.state; 23 24 import java.util.HashSet ; 25 import java.util.Set ; 26 import java.util.Iterator ; 27 import org.jboss.logging.Logger; 28 29 34 public class StateMachine implements Cloneable 35 { 36 private static Logger log = Logger.getLogger(StateMachine.class); 37 38 private String description; 39 40 private HashSet states; 41 42 private State startState; 43 44 private State currentState; 45 46 51 public StateMachine(Set states, State startState) 52 { 53 this(states, startState, null); 54 } 55 61 public StateMachine(Set states, State startState, String description) 62 { 63 this.states = new HashSet (states); 64 this.startState = startState; 65 this.currentState = startState; 66 this.description = description; 67 } 68 69 73 public Object clone() 74 { 75 StateMachine clone = new StateMachine(states, startState, description); 76 clone.currentState = currentState; 77 return clone; 78 } 79 80 83 public String getDescription() 84 { 85 return description; 86 } 87 88 91 public State getCurrentState() 92 { 93 return currentState; 94 } 95 96 99 public State getStartState() 100 { 101 return startState; 102 } 103 104 107 public Set getStates() 108 { 109 return states; 110 } 111 112 118 public State nextState(String actionName) 119 throws IllegalTransitionException 120 { 121 Transition t = currentState.getTransition(actionName); 122 if( t == null ) 123 { 124 String msg = "No transition for action: '" + actionName 125 + "' from state: '" + currentState.getName() + "'"; 126 throw new IllegalTransitionException(msg); 127 } 128 State nextState = t.getTarget(); 129 log.trace("nextState("+actionName+") = "+nextState); 130 currentState = nextState; 131 return currentState; 132 } 133 134 138 public State reset() 139 { 140 this.currentState = startState; 141 return currentState; 142 } 143 144 public String toString() 145 { 146 StringBuffer tmp = new StringBuffer ("StateMachine[:\n"); 147 tmp.append("\tCurrentState: "+currentState.getName()); 148 Iterator i = states.iterator(); 149 while( i.hasNext() ) 150 { 151 tmp.append('\n').append(i.next()); 152 } 153 tmp.append(']'); 154 return tmp.toString(); 155 } 156 } 157 | Popular Tags |