01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tctest.restart;
05:
06: import java.util.HashMap;
07: import java.util.HashSet;
08: import java.util.Iterator;
09: import java.util.Map;
10: import java.util.Set;
11:
12: public class AppStateSnapshot {
13:
14: private final RestartTestApp[] apps;
15: private final Set inits = new HashSet();
16: private final Set starts = new HashSet();
17: final Set holders = new HashSet();
18: final Set waiters = new HashSet();
19: private final Set ends = new HashSet();
20: private final Map sets = new HashMap();
21:
22: public AppStateSnapshot(RestartTestApp[] apps) {
23: this .apps = apps;
24: sets.put(TestAppState.INIT, inits);
25: sets.put(TestAppState.START, starts);
26: sets.put(TestAppState.HOLDER, holders);
27: sets.put(TestAppState.WAITER, waiters);
28: sets.put(TestAppState.END, ends);
29: takeSnapshot();
30: }
31:
32: public synchronized RestartTestApp getHolder() {
33: while (true) {
34: takeSnapshot();
35: if (allEnded())
36: return null;
37: RestartTestApp[] h = getHolders();
38: if (h.length == 1)
39: return h[0];
40: }
41: }
42:
43: public String toString() {
44: StringBuffer buf = new StringBuffer();
45: for (Iterator i = sets.keySet().iterator(); i.hasNext();) {
46: Object key = i.next();
47: buf.append(key + ":" + ((Set) sets.get(key)).size() + " ");
48: }
49: return buf.toString();
50: }
51:
52: private void clear() {
53: for (Iterator i = sets.values().iterator(); i.hasNext();) {
54: Set s = (Set) i.next();
55: s.clear();
56: }
57: }
58:
59: public synchronized AppStateSnapshot takeSnapshot() {
60: clear();
61: for (int i = 0; i < apps.length; i++) {
62: ((Set) sets.get(apps[i].getStateName())).add(apps[i]);
63: }
64: return this ;
65: }
66:
67: public synchronized RestartTestApp[] getHolders() {
68: takeSnapshot();
69: return toArray(holders);
70: }
71:
72: public synchronized RestartTestApp[] getWaiters() {
73: takeSnapshot();
74: return toArray(waiters);
75: }
76:
77: private RestartTestApp[] toArray(Set s) {
78: RestartTestApp[] rv = new RestartTestApp[s.size()];
79: return (RestartTestApp[]) s.toArray(rv);
80: }
81:
82: public synchronized boolean allStarted() {
83: takeSnapshot();
84: return inits.size() == 0;
85: }
86:
87: public boolean allWaiters() {
88: takeSnapshot();
89: return waiters.size() == apps.length;
90: }
91:
92: public synchronized boolean allEnded() {
93: takeSnapshot();
94: return ends.size() == apps.length;
95: }
96: }
|