1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.maven.plugin.logging.Log;
23
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.Set;
29
30
31
32
33
34
35
36
37
38 public final class EmbeddedRegistry
39 {
40 private static EmbeddedRegistry instance;
41
42 private Set<Object> containers = new HashSet<Object>( 1 );
43
44
45
46
47 private EmbeddedRegistry()
48 {
49
50 }
51
52
53
54
55
56
57 public static EmbeddedRegistry getInstance()
58 {
59 if ( instance == null )
60 {
61 instance = new EmbeddedRegistry();
62 Runtime.getRuntime().addShutdownHook( new Thread()
63 {
64 @Override
65 public void run()
66 {
67 try
68 {
69 getInstance().shutdownAll( null );
70 }
71 catch ( Exception e )
72 {
73
74 }
75 }
76 } );
77 }
78 return instance;
79 }
80
81
82
83
84
85
86
87
88 public synchronized boolean register( final Object container )
89 {
90 return containers.add( container );
91 }
92
93
94
95
96
97
98
99
100 public synchronized void shutdownAll( final Log log )
101 throws Exception
102 {
103 Exception firstException = null;
104 for ( Iterator<Object> iterator = containers.iterator(); iterator.hasNext(); )
105 {
106 Object embedded = iterator.next();
107 try
108 {
109 Method method = embedded.getClass().getMethod( "stop", null );
110 method.invoke( embedded, null );
111 iterator.remove();
112 }
113 catch ( NoSuchMethodException e )
114 {
115 if ( firstException == null )
116 {
117 firstException = e;
118 error( log, e, "no stop method in class " + embedded.getClass().getName() );
119 }
120 else
121 {
122 error( log, e, "Error while shutting down embedded Tomcat." );
123 }
124 }
125 catch ( IllegalAccessException e )
126 {
127 if ( firstException == null )
128 {
129 firstException = e;
130 error( log, e, "IllegalAccessException for stop method in class " + embedded.getClass().getName() );
131 }
132 else
133 {
134 error( log, e, "Error while shutting down embedded Tomcat." );
135 }
136 }
137 catch ( InvocationTargetException e )
138 {
139
140 if ( firstException == null )
141 {
142 firstException = e;
143 error( log, e, "IllegalAccessException for stop method in class " + embedded.getClass().getName() );
144 }
145 else
146 {
147 error( log, e, "Error while shutting down embedded Tomcat." );
148 }
149 }
150 }
151 if ( firstException != null )
152 {
153 throw firstException;
154 }
155 }
156
157
158
159
160
161
162
163
164
165 private void error( final Log log, final Exception e, final String message )
166 {
167 if ( log == null )
168 {
169 System.err.println( "ERROR: " + message );
170 e.printStackTrace();
171 }
172 else
173 {
174 log.error( message, e );
175 }
176 }
177
178 }