KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openejb > server > ServiceManager


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "OpenEJB" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of The OpenEJB Group. For written permission,
18  * please contact dev@openejb.org.
19  *
20  * 4. Products derived from this Software may not be called "OpenEJB"
21  * nor may "OpenEJB" appear in their names without prior written
22  * permission of The OpenEJB Group. OpenEJB is a registered
23  * trademark of The OpenEJB Group.
24  *
25  * 5. Due credit should be given to the OpenEJB Project
26  * (http://www.openejb.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE OPENEJB GROUP AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * THE OPENEJB GROUP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2001 (C) The OpenEJB Group. All Rights Reserved.
42  *
43  * $Id: ServiceManager.java 2506 2006-02-25 07:10:56Z dblevins $
44  */

45 package org.openejb.server;
46
47 import org.openejb.loader.SystemInstance;
48 import org.openejb.util.Logger;
49 import org.openejb.util.Messages;
50 import org.openejb.util.FileUtils;
51 import org.openejb.util.ResourceFinder;
52
53 import java.io.File JavaDoc;
54 import java.io.FileInputStream JavaDoc;
55 import java.io.FileOutputStream JavaDoc;
56 import java.io.IOException JavaDoc;
57 import java.net.InetAddress JavaDoc;
58 import java.util.HashMap JavaDoc;
59 import java.util.Properties JavaDoc;
60 import java.util.Map JavaDoc;
61 import java.util.Iterator JavaDoc;
62 import java.util.List JavaDoc;
63 import java.util.ArrayList JavaDoc;
64
65
66 /**
67  * This is the base class for orcistrating the other daemons
68  * which actually accept and react to calls coming in from
69  * different protocols or channels.
70  * <p/>
71  * To perform this task, this class will
72  * newInstance()
73  * init( port, properties)
74  * start()
75  * stop()
76  *
77  * @author <a HREF="mailto:david.blevins@visi.com">David Blevins</a>
78  */

79 public class ServiceManager {
80
81     static Messages messages = new Messages("org.openejb.server.util.resources");
82     static Logger logger = Logger.getInstance("OpenEJB.server.remote", "org.openejb.server.util.resources");
83
84     private static ServiceManager manager;
85
86     private static HashMap JavaDoc propsByFile = new HashMap JavaDoc();
87     private static HashMap JavaDoc fileByProps = new HashMap JavaDoc();
88
89     private static ServerService[] daemons;
90
91     private boolean stop = false;
92     private final ResourceFinder resourceFinder;
93
94     private ServiceManager() {
95         resourceFinder = new ResourceFinder("META-INF/");
96     }
97
98     public static ServiceManager getManager() {
99         if (manager == null) {
100             manager = new ServiceManager();
101         }
102
103         return manager;
104     }
105
106     // Have properties files (like xinet.d) that specifies what daemons to
107
// Look into the xinet.d file structure again
108
// conf/server.d/
109
// admin.properties
110
// ejbd.properties
111
// webadmin.properties
112
// telnet.properties
113
// corba.properties
114
// soap.properties
115
// xmlrpc.properties
116
// httpejb.properties
117
// webejb.properties
118
// xmlejb.properties
119
// Each contains the class name of the daemon implamentation
120
// The port to use
121
// whether it's turned on
122

123
124     // May be reusable elsewhere, move if another use occurs
125
public static class ServiceFinder {
126         private final ResourceFinder resourceFinder;
127         private ClassLoader JavaDoc classLoader;
128
129         public ServiceFinder(String JavaDoc basePath) {
130             this(basePath, Thread.currentThread().getContextClassLoader());
131         }
132
133         public ServiceFinder(String JavaDoc basePath, ClassLoader JavaDoc classLoader) {
134             this.resourceFinder = new ResourceFinder(basePath, classLoader);
135             this.classLoader = classLoader;
136         }
137
138         public Map JavaDoc mapAvailableServices(Class JavaDoc interfase) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
139             Map JavaDoc services = resourceFinder.mapAvailableProperties(ServerService.class.getName());
140
141             for (Iterator JavaDoc iterator = services.entrySet().iterator(); iterator.hasNext();) {
142                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
143                 String JavaDoc name = (String JavaDoc) entry.getKey();
144                 Properties JavaDoc properties = (Properties JavaDoc) entry.getValue();
145
146                 String JavaDoc className = properties.getProperty("className");
147                 if (className == null) {
148                     className = properties.getProperty("classname");
149                     if (className == null) {
150                         className = properties.getProperty("server");
151                     }
152                 }
153
154                 Class JavaDoc impl = classLoader.loadClass(className);
155
156                 if (!interfase.isAssignableFrom(impl)) {
157                     services.remove(name);
158                     continue;
159                 }
160
161                 properties.put(interfase, impl);
162                 String JavaDoc rawProperties = resourceFinder.findString(interfase.getName() + "/" + name);
163                 properties.put(Properties JavaDoc.class, rawProperties);
164
165             }
166             return services;
167         }
168     }
169
170     public void init() throws Exception JavaDoc {
171         try {
172             org.apache.log4j.MDC.put("SERVER", "main");
173             InetAddress JavaDoc localhost = InetAddress.getLocalHost();
174             org.apache.log4j.MDC.put("HOST", localhost.getHostName());
175         } catch (Exception JavaDoc e) {
176         }
177
178         ServiceFinder serviceFinder = new ServiceFinder("META-INF/");
179
180         Map JavaDoc availableServices = serviceFinder.mapAvailableServices(ServerService.class);
181         List JavaDoc enabledServers = new ArrayList JavaDoc();
182
183         for (Iterator JavaDoc iterator = availableServices.entrySet().iterator(); iterator.hasNext();) {
184             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
185             String JavaDoc serviceName = (String JavaDoc) entry.getKey();
186             Properties JavaDoc serviceProperties = (Properties JavaDoc) entry.getValue();
187
188             overrideProperties(serviceName, serviceProperties);
189             serviceProperties.setProperty("name", serviceName);
190
191             if (isEnabled(serviceProperties)) {
192
193                 // Create Service
194
ServerService service = null;
195
196                 Class JavaDoc serviceClass = (Class JavaDoc) serviceProperties.get(ServerService.class);
197
198                 try {
199                     service = (ServerService) serviceClass.newInstance();
200                 } catch (Throwable JavaDoc t) {
201                     String JavaDoc msg1 = messages.format("service.instantiation.err", serviceClass.getName(), t.getClass().getName(), t.getMessage());
202                     throw new ServiceException(msg1, t);
203                 }
204
205                 // Wrap Service
206
service = new ServiceLogger(service);
207                 service = new ServiceAccessController(service);
208                 service = new ServiceDaemon(service);
209
210                 // Initialize it
211
service.init(serviceProperties);
212                 enabledServers.add(service);
213             }
214
215         }
216
217         daemons = (ServerService[]) enabledServers.toArray(new ServerService[]{});
218     }
219
220     private void overrideProperties(String JavaDoc serviceName, Properties JavaDoc serviceProperties) throws IOException JavaDoc {
221         FileUtils base = SystemInstance.get().getBase();
222
223         // Override with file from conf dir
224
File JavaDoc conf = base.getDirectory("conf");
225         if (conf.exists()) {
226             File JavaDoc serviceConfig = new File JavaDoc(conf, serviceName + ".properties");
227             if (serviceConfig.exists()){
228                 FileInputStream JavaDoc in = new FileInputStream JavaDoc(serviceConfig);
229                 try {
230                     serviceProperties.load(in);
231                 } finally {
232                     in.close();
233                 }
234             } else {
235                 FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(serviceConfig);
236                 try {
237                     String JavaDoc rawPropsContent = (String JavaDoc) serviceProperties.get(Properties JavaDoc.class);
238                     out.write(rawPropsContent.getBytes());
239                 } finally {
240                     out.close();
241                 }
242             }
243         }
244
245         // Override with system properties
246
String JavaDoc prefix = serviceName + ".";
247         Properties JavaDoc sysProps = System.getProperties();
248         for (Iterator JavaDoc iterator1 = sysProps.entrySet().iterator(); iterator1.hasNext();) {
249             Map.Entry JavaDoc entry1 = (Map.Entry JavaDoc) iterator1.next();
250             String JavaDoc key = (String JavaDoc) entry1.getKey();
251             String JavaDoc value = (String JavaDoc) entry1.getValue();
252             if (key.startsWith(prefix)){
253                 key = key.replaceFirst(prefix, "");
254                 serviceProperties.setProperty(key, value);
255             }
256         }
257
258     }
259
260     private boolean isEnabled(Properties JavaDoc props) throws ServiceException {
261         // if it should be started, continue
262
String JavaDoc disabled = props.getProperty("disabled", "");
263
264         if (disabled.equalsIgnoreCase("yes") || disabled.equalsIgnoreCase("true")) {
265             return false;
266         } else {
267             return true;
268         }
269     }
270
271     public synchronized void start() throws ServiceException {
272         boolean display = System.getProperty("openejb.nobanner") == null;
273
274
275         if (display) {
276             System.out.println(" ** Starting Services **");
277             printRow("NAME", "IP", "PORT");
278         }
279
280         for (int i = 0; i < daemons.length; i++) {
281             ServerService d = daemons[i];
282             try {
283                 d.start();
284                 if (display) {
285                     printRow(d.getName(), d.getIP(), d.getPort() + "");
286                 }
287             } catch (Exception JavaDoc e) {
288                 logger.error(d.getName() + " " + d.getIP() + " " + d.getPort() + ": " + e.getMessage());
289                 if (display) {
290                     printRow(d.getName(), "----", "FAILED");
291                 }
292             }
293         }
294         if (display) {
295             System.out.println("-------");
296             System.out.println("Ready!");
297         }
298         /*
299          * This will cause the user thread (the thread that keeps the
300          * vm alive) to go into a state of constant waiting.
301          * Each time the thread is woken up, it checks to see if
302          * it should continue waiting.
303          *
304          * To stop the thread (and the VM), just call the stop method
305          * which will set 'stop' to true and notify the user thread.
306          */

307         try {
308             while (!stop) {
309                 //System.out.println("[] waiting to stop \t["+Thread.currentThread().getName()+"]");
310
this.wait(Long.MAX_VALUE);
311             }
312         } catch (Throwable JavaDoc t) {
313             logger.fatal("Unable to keep the server thread alive. Received exception: " + t.getClass().getName() + " : " + t.getMessage());
314         }
315         System.out.println("[] exiting vm");
316         logger.info("Stopping Remote Server");
317
318     }
319
320     public synchronized void stop() throws ServiceException {
321         System.out.println("[] received stop signal");
322         stop = true;
323         for (int i = 0; i < daemons.length; i++) {
324             daemons[i].stop();
325         }
326         notifyAll();
327     }
328
329     private void printRow(String JavaDoc col1, String JavaDoc col2, String JavaDoc col3) {
330
331         // column 1 is 20 chars long
332
col1 += " ";
333         col1 = col1.substring(0, 20);
334
335         // column 2 is 15 chars long
336
col2 += " ";
337         col2 = col2.substring(0, 15);
338
339         // column 3 is 6 chars long
340
col3 += " ";
341         col3 = col3.substring(0, 6);
342
343         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(50);
344         sb.append(" ").append(col1);
345         sb.append(" ").append(col2);
346         sb.append(" ").append(col3);
347
348         System.out.println(sb.toString());
349     }
350 }
351
Popular Tags