1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.statemachine;
21
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
25
26 import org.apache.commons.lang.builder.EqualsBuilder;
27 import org.apache.commons.lang.builder.HashCodeBuilder;
28 import org.apache.commons.lang.builder.ToStringBuilder;
29 import org.apache.mina.statemachine.event.Event;
30 import org.apache.mina.statemachine.transition.Transition;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 public class State {
50 private final String id;
51 private final State parent;
52 private List<TransitionHolder> transitionHolders = new ArrayList<TransitionHolder>();
53 private List<Transition> transitions = Collections.emptyList();
54
55
56
57
58
59
60 public State(String id) {
61 this(id, null);
62 }
63
64
65
66
67
68
69
70 public State(String id, State parent) {
71 this.id = id;
72 this.parent = parent;
73 }
74
75
76
77
78
79
80 public String getId() {
81 return id;
82 }
83
84
85
86
87
88
89
90 public State getParent() {
91 return parent;
92 }
93
94
95
96
97
98
99
100 public List<Transition> getTransitions() {
101 return Collections.unmodifiableList(transitions);
102 }
103
104 private void updateTransitions() {
105 transitions = new ArrayList<Transition>(transitionHolders.size());
106 for (TransitionHolder holder : transitionHolders) {
107 transitions.add(holder.transition);
108 }
109 }
110
111
112
113
114
115
116
117
118 public State addTransition(Transition transition) {
119 return addTransition(transition, 0);
120 }
121
122
123
124
125
126
127
128
129
130
131
132 public State addTransition(Transition transition, int weight) {
133 if (transition == null) {
134 throw new NullPointerException("transition");
135 }
136
137 transitionHolders.add(new TransitionHolder(transition, weight));
138 Collections.sort(transitionHolders);
139 updateTransitions();
140 return this;
141 }
142
143 @Override
144 public boolean equals(Object o) {
145 if (!(o instanceof State)) {
146 return false;
147 }
148 if (o == this) {
149 return true;
150 }
151 State that = (State) o;
152 return new EqualsBuilder().append(this.id, that.id).isEquals();
153 }
154
155 @Override
156 public int hashCode() {
157 return new HashCodeBuilder(13, 33).append(this.id).toHashCode();
158 }
159
160 @Override
161 public String toString() {
162 return new ToStringBuilder(this).append("id", this.id).toString();
163 }
164
165 private static class TransitionHolder implements Comparable<TransitionHolder> {
166 Transition transition;
167
168 int weight;
169
170 TransitionHolder(Transition transition, int weight) {
171 this.transition = transition;
172 this.weight = weight;
173 }
174
175 public int compareTo(TransitionHolder o) {
176 return (weight > o.weight) ? 1 : (weight < o.weight ? -1 : 0);
177 }
178 }
179 }