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
50 public class State {
51 private final String id;
52 private final State parent;
53 private List<TransitionHolder> transitionHolders = new ArrayList<TransitionHolder>();
54 private List<Transition> transitions = Collections.emptyList();
55
56
57
58
59
60
61 public State(String id) {
62 this(id, null);
63 }
64
65
66
67
68
69
70
71 public State(String id, State parent) {
72 this.id = id;
73 this.parent = parent;
74 }
75
76
77
78
79
80
81 public String getId() {
82 return id;
83 }
84
85
86
87
88
89
90
91 public State getParent() {
92 return parent;
93 }
94
95
96
97
98
99
100
101 public List<Transition> getTransitions() {
102 return Collections.unmodifiableList(transitions);
103 }
104
105 private void updateTransitions() {
106 transitions = new ArrayList<Transition>(transitionHolders.size());
107 for (TransitionHolder holder : transitionHolders) {
108 transitions.add(holder.transition);
109 }
110 }
111
112
113
114
115
116
117
118
119 public State addTransition(Transition transition) {
120 return addTransition(transition, 0);
121 }
122
123
124
125
126
127
128
129
130
131
132
133 public State addTransition(Transition transition, int weight) {
134 if (transition == null) {
135 throw new NullPointerException("transition");
136 }
137
138 transitionHolders.add(new TransitionHolder(transition, weight));
139 Collections.sort(transitionHolders);
140 updateTransitions();
141 return this;
142 }
143
144 @Override
145 public boolean equals(Object o) {
146 if (!(o instanceof State)) {
147 return false;
148 }
149 if (o == this) {
150 return true;
151 }
152 State that = (State) o;
153 return new EqualsBuilder().append(this.id, that.id).isEquals();
154 }
155
156 @Override
157 public int hashCode() {
158 return new HashCodeBuilder(13, 33).append(this.id).toHashCode();
159 }
160
161 @Override
162 public String toString() {
163 return new ToStringBuilder(this).append("id", this.id).toString();
164 }
165
166 private static class TransitionHolder implements Comparable<TransitionHolder> {
167 Transition transition;
168
169 int weight;
170
171 TransitionHolder(Transition transition, int weight) {
172 this.transition = transition;
173 this.weight = weight;
174 }
175
176 public int compareTo(TransitionHolder o) {
177 return (weight > o.weight) ? 1 : (weight < o.weight ? -1 : 0);
178 }
179 }
180 }