1
2
3
4
5
6 package net.sf.tlc.kernel;
7
8 import java.util.Iterator;
9
10 import net.sf.tlc.core.LifecycleAware;
11 import net.sf.tlc.core.impl.DefaultServiceLocator;
12
13 /***
14 * TheLittleContainer micro kernel.
15 *
16 * @author aisrael
17 */
18 public final class TlcMicroKernel extends DefaultServiceLocator implements LifecycleAware {
19
20 private static final int STATE_UNKNOWN = 0;
21
22 private static final int STATE_INITIALIZING = 1;
23
24 private static final int STATE_RUNNING = 2;
25
26 private static final int STATE_CLEANUP = 3;
27
28 private static final int STATE_SHUTDOWN = 4;
29
30 private int state = STATE_UNKNOWN;
31
32 /***
33 * @param state
34 * int
35 */
36 private void setState(final int state) {
37 this.state = state;
38 }
39
40 /***
41 * @return the state
42 */
43 private int getState() {
44 return this.state;
45 }
46
47 /***
48 * (non-Javadoc)
49 *
50 * @see net.sf.tlc.core.LifecycleAware#start()
51 */
52 public void start() {
53 if (TlcMicroKernel.STATE_UNKNOWN != getState()) {
54 throw new IllegalStateException("Invalid state!");
55 }
56 setState(TlcMicroKernel.STATE_INITIALIZING);
57 startAllServices();
58 setState(TlcMicroKernel.STATE_RUNNING);
59 }
60
61 /***
62 *
63 */
64 private void startAllServices() {
65 final Iterator i = servicesSet().iterator();
66 while (i.hasNext()) {
67 final Object o = i.next();
68 if (o instanceof LifecycleAware) {
69 ((LifecycleAware) o).start();
70 }
71 }
72 }
73
74 /***
75 * (non-Javadoc)
76 *
77 * @see net.sf.tlc.core.LifecycleAware#isRunning()
78 */
79 public boolean isRunning() {
80 return (TlcMicroKernel.STATE_RUNNING == getState());
81 }
82
83 /***
84 * (non-Javadoc)
85 *
86 * @see net.sf.tlc.core.LifecycleAware#stop()
87 */
88 public void stop() {
89 if (TlcMicroKernel.STATE_RUNNING != getState()) {
90 throw new IllegalStateException("Invalid state!");
91 }
92 setState(TlcMicroKernel.STATE_CLEANUP);
93 stopAllServices();
94 waitForAllServices();
95 setState(TlcMicroKernel.STATE_SHUTDOWN);
96 }
97
98 /***
99 *
100 */
101 private void stopAllServices() {
102 final Iterator i = servicesSet().iterator();
103 while (i.hasNext()) {
104 final Object o = i.next();
105 if (o instanceof LifecycleAware) {
106 ((LifecycleAware) o).stop();
107 } else {
108 unregister(o);
109 }
110 }
111 }
112
113 /***
114 *
115 */
116 private void waitForAllServices() {
117 boolean stillRunning = true;
118 while (stillRunning) {
119 stillRunning = false;
120 final Iterator i = servicesSet().iterator();
121 while (i.hasNext()) {
122 final Object o = i.next();
123 if (o instanceof LifecycleAware) {
124 stillRunning |= ((LifecycleAware) o).isRunning();
125 }
126 }
127 }
128 }
129 }