KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > service > ServiceManager


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2004 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id: ServiceManager.java,v 1.31 2005/05/09 15:00:44 danesa Exp $
23  * --------------------------------------------------------------------------
24  */

25
26
27 package org.objectweb.jonas.service;
28
29 import java.util.ArrayList JavaDoc;
30 import java.util.Enumeration JavaDoc;
31 import java.util.Hashtable JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34
35 import javax.naming.Context JavaDoc;
36 import javax.naming.NamingException JavaDoc;
37
38 import org.objectweb.jonas.common.JProp;
39 import org.objectweb.jonas.common.Log;
40 import org.objectweb.jonas.naming.CompNamingContext;
41
42 import org.objectweb.util.monolog.api.BasicLevel;
43 import org.objectweb.util.monolog.api.Logger;
44
45 /**
46  * This class implements a manager of org.objectweb.jonas.service.Service for JOnAS.
47  *
48  * The services are defined in the jonas.properties files
49  * - 'jonas.services' property defines the list of the services,
50  * - for each service
51  * - 'jonas.service.<service-name>.class' property defines the class of the
52  * implementation of the service,
53  * - 'jonas.service.<service-name>.XXXX' properties define the configuration
54  * of the service
55  *
56  * @author Helene Joanin
57  * Contributor(s):
58  * 01/06/15: Regis Le Brettevillois - Libelis
59  * 02/06 : Florent Benoit & Ludovic Bert : Ear service/Web Container service
60  * Philippe Durieux
61  * 03/01/14 Adriana Danes : pass the entire property name (jonas.service.<service-name>.XXXX)
62  * in the configuration context at service creation time
63  */

64
65 public class ServiceManager {
66
67     /**
68      * Services of JOnAS
69      */

70     static final String JavaDoc SERVICES_PROP_NAME = JProp.JONASPREFIX + ".services";
71
72     /**
73      * A JOnAS service
74      */

75     static final String JavaDoc PREFIX_SERVICE_PROP_NAME = JProp.JONASPREFIX + ".service";
76
77     /**
78      * The logger used.
79      */

80     private static Logger logger = null;
81
82     /**
83      * The ServerManager singleton value
84      */

85     private static ServiceManager unique = null;
86
87     /**
88      * JOnAS properties
89     */

90     private JProp props = null;
91
92     /**
93      * The list of the managed services
94      */

95     private static List JavaDoc services = null;
96
97     /**
98      * The managed services and their names
99      */

100     private Map JavaDoc servicesByName = null;
101
102     /**
103      * The Configuration context for each managed service
104      */

105     private Map JavaDoc contextsByService = null;
106
107     /**
108      * Private constructor to force only 1 instance.
109      * @throws Exception if the ServiceManager can't be built.
110      */

111     private ServiceManager() throws Exception JavaDoc {
112         logger = Log.getLogger(Log.JONAS_SERVER_PREFIX);
113         // read properties from the different jonas.properties files
114
props = JProp.getInstance();
115         // read all services from properties
116
readServices();
117     }
118
119     /**
120      * Get the unique instance.
121      * Create it at first call.
122      * @return ServiceManager the unique instance
123      * @throws Exception if the ServiceManager can't be built.
124      */

125     public static ServiceManager getInstance() throws Exception JavaDoc {
126         if (unique == null) {
127             unique = new ServiceManager();
128         }
129         return unique;
130     }
131
132     /**
133      * Get the service which have the given name
134      * @param name the given name
135      * @return the service which have the given name
136      * @throws ServiceException if the service can't be retrieved.
137      */

138     public Service getService(String JavaDoc name) throws ServiceException {
139         if (servicesByName == null) {
140             throw new ServiceException("No service has been initialized yet");
141         }
142         Service s = (Service) servicesByName.get(name);
143         if (s == null) {
144             throw new ServiceException("Unknown service '" + name + "'");
145         }
146         return s;
147     }
148
149     /**
150      * Return the EJB service (service's name: 'ejb')
151      * @return the EJB service.
152      * @throws ServiceException if can not get the ejb service.
153      */

154     public Service getEjbService() throws ServiceException {
155         return getService("ejb");
156     }
157
158     /**
159      * Return the Ear service (service's name: 'ear')
160      * @return the EAR service.
161      * @throws ServiceException if can not get the ear service.
162      */

163     public Service getEarService() throws ServiceException {
164         return getService("ear");
165     }
166
167     /**
168      * Return the Rar service (service's name: 'resource')
169      * @return the RAR service.
170      * @throws ServiceException if can not get the rar service.
171      */

172     public Service getRarService() throws ServiceException {
173         return getService("resource");
174     }
175
176     /**
177      * Return the web service (service's name: 'web').
178      * @return the web service.
179      * @throws ServiceException if can not get the web service.
180      */

181     public Service getWebContainerService() throws ServiceException {
182         return getService("web");
183     }
184
185     /**
186      * Return the WebServices service (service's name: 'ws').
187      * @return the WebServices service.
188      * @throws ServiceException if can not get the WebServices service.
189      */

190     public Service getWebServicesService() throws ServiceException {
191         return getService("ws");
192     }
193
194     /**
195      * Return the mail service (service's name: 'mail').
196      * @return the mail service.
197      * @throws ServiceException if can not get the mail service.
198      */

199     public Service getMailService() throws ServiceException {
200         return getService("mail");
201     }
202
203     /**
204      * Return the DataBase service (service's name: 'dbm')
205      * @return the DBM service.
206      * @throws ServiceException if can not get the dbm service.
207      */

208     public Service getDataBaseService() throws ServiceException {
209         return getService("dbm");
210     }
211
212     /**
213      * Return the Transaction service (service's name: 'jtm')
214      * @return the JTM service.
215      * @throws ServiceException if can not get the jtm service.
216      */

217     public Service getTransactionService() throws ServiceException {
218         return getService("jtm");
219     }
220
221     /**
222      * Return the JMS service (service's name: 'jms')
223      * @return the JMS service.
224      * @throws ServiceException if can not get the jms service.
225      */

226     public Service getJmsService() throws ServiceException {
227         return getService("jms");
228     }
229
230     /**
231      * Return the Security service (service's name: 'security')
232      * @return the Security service.
233      * @throws ServiceException if can not get the security service.
234      */

235     public Service getSecurityService() throws ServiceException {
236         return getService("security");
237     }
238
239     /**
240      * Return the JMX service (service's name: 'jmx')
241      * @return the JMX service.
242      * @throws ServiceException if can not get the jmx service.
243      */

244     public Service getJmxService() throws ServiceException {
245         return getService("jmx");
246     }
247
248     /**
249      * Return the discovery service (service's name: 'discovery')
250      * @return the discovery service.
251      * @throws ServiceException if can not get the discovery service.
252      */

253     public Service getDiscoveryService() throws ServiceException {
254         return getService("discovery");
255     }
256
257     /**
258      * Return the Registry service (service's name: 'registry')
259      * @return the Registry service.
260      * @throws ServiceException if can not get the registry service.
261      */

262     public Service getRegistryService() throws ServiceException {
263         return getService("registry");
264     }
265
266     /**
267      * Return the Resource service (service's name: 'resource')
268      * @return the Resource service.
269      * @throws ServiceException if can not get the resource service.
270      */

271     public Service getResourceService() throws ServiceException {
272         return getService("resource");
273     }
274
275     /**
276      * Start the mandatory "registry" service
277      * @throws ServiceException if the "registry" service can't be started.
278      */

279     public void startRegistry() throws ServiceException {
280         if (logger.isLoggable(BasicLevel.DEBUG)) {
281             logger.log(BasicLevel.DEBUG, "");
282         }
283         Service reg = getRegistryService();
284         try {
285             reg.init((Context JavaDoc) contextsByService.get(reg));
286             reg.start();
287             logger.log(BasicLevel.INFO, "registry service started");
288         } catch (ServiceException e) {
289             throw new ServiceException("Cannot init/start registry" + e);
290         }
291     }
292
293     /**
294      * Start the jmx service
295      * @throws ServiceException if the jmx service can't be started.
296      */

297     public void startJmx(String JavaDoc idMBeanServer) throws ServiceException {
298         if (logger.isLoggable(BasicLevel.DEBUG)) {
299             logger.log(BasicLevel.DEBUG, "");
300         }
301         Service jmxService = getJmxService();
302         try {
303             Context JavaDoc paramCtx = (Context JavaDoc) contextsByService.get(jmxService);
304             if (idMBeanServer != null) {
305                 try {
306                 paramCtx.bind("idMBeanServer", idMBeanServer);
307                 } catch (NamingException JavaDoc ne) {
308                     throw new ServiceException("Cannot bind idMBeanServer = '" + idMBeanServer + "' for JMX service.", ne);
309                 }
310             }
311             jmxService.init(paramCtx);
312             jmxService.start();
313             logger.log(BasicLevel.INFO, "jmx service started");
314         } catch (ServiceException e) {
315             throw e;
316         }
317     }
318
319     /**
320      * Starts the managed services.
321      * @throws ServiceException if the services can't be started.
322      */

323     public void startServices() throws ServiceException {
324         if (logger.isLoggable(BasicLevel.DEBUG)) {
325             logger.log(BasicLevel.DEBUG, "");
326         }
327         Service[] services = getServices();
328         Context JavaDoc serviceContext = null;
329         // registry = service 0, already started.
330
// jmx = service 1, already started
331
for (int i = 2; i < services.length; i++) {
332             Service service = services[i];
333             try {
334                 serviceContext = (Context JavaDoc) contextsByService.get(service);
335                 service.init(serviceContext);
336                 service.start();
337                 logger.log(BasicLevel.INFO, service.getName() + " service started");
338             } catch (ServiceException e) {
339                 throw new ServiceException("Cannot init/start service '" + service.getName() + "': " + e.getMessage(), e);
340             }
341         }
342     }
343
344     /**
345      * Returns the list of the managed services
346      * @return String[] the name of the managed services.
347      * @throws ServiceException if the list can't be retrieved.
348      */

349     public Service[] getServices() throws ServiceException {
350         Service[] ss = new Service[services.size()];
351         for (int i = 0; i < services.size(); i++) {
352             ss[i] = (Service) services.get(i);
353         }
354         return ss;
355     }
356
357     /**
358      * return the list of services + registry if needed.
359      * @return String[] the name of the services.
360      */

361     public String JavaDoc[] getServiceNames() {
362         if (logger.isLoggable(BasicLevel.DEBUG)) {
363             logger.log(BasicLevel.DEBUG, "");
364         }
365         String JavaDoc [] serviceNames;
366         serviceNames = props.getValueAsArray(SERVICES_PROP_NAME);
367         if (serviceNames == null) {
368             return null;
369         }
370         if (serviceNames[0].equals("registry") && serviceNames[1].equals("jmx")) {
371             return serviceNames;
372         }
373         ArrayList JavaDoc services = new ArrayList JavaDoc();
374         services.add(0, "registry");
375         services.add(1, "jmx");
376         int nbServices = 2;
377         for (int i = 0; i < serviceNames.length; i++) {
378             if (!serviceNames[i].equals("registry") && !serviceNames[i].equals("jmx")) {
379                 services.add(serviceNames[i]);
380                 nbServices++;
381             }
382         }
383         serviceNames = new String JavaDoc[nbServices];
384         if (logger.isLoggable(BasicLevel.DEBUG)) {
385             logger.log(BasicLevel.DEBUG, "Created new array of String of size " + services.size());
386         }
387         for (int i = 0; i < nbServices; i++) {
388             serviceNames[i] = (String JavaDoc) services.get(i);
389         }
390         return serviceNames;
391     }
392
393     /**
394      * For each service, create it and its associated configuration context.
395      * (creates services, contextsByService and servicesByName)
396      * @throws ServiceException if the services can't be read.
397      */

398     protected void readServices() throws ServiceException {
399         if (logger.isLoggable(BasicLevel.DEBUG)) {
400             logger.log(BasicLevel.DEBUG, "");
401         }
402         services = new ArrayList JavaDoc();
403         contextsByService = new Hashtable JavaDoc();
404         servicesByName = new Hashtable JavaDoc();
405         String JavaDoc [] serviceNames;
406         serviceNames = getServiceNames();
407         if (serviceNames == null) {
408             throw new ServiceException("Property '" + SERVICES_PROP_NAME + "' is missing in '"
409                                        + JProp.JONASPREFIX + "' properties file");
410         }
411         for (int i = 0; i < serviceNames.length; i++) {
412             String JavaDoc serviceName = serviceNames[i];
413             Service serviceObj = createServiceFrom(serviceName);
414             if (serviceObj != null) {
415                 try {
416                     Context JavaDoc ctx = createServiceContextFor(serviceName);
417                     services.add(serviceObj);
418                     contextsByService.put(serviceObj, ctx);
419                     servicesByName.put(serviceName, serviceObj);
420                 } catch (NamingException JavaDoc e) {
421                     throw new ServiceException("cannot create the context name of the service '"
422                                                + serviceName + "'",
423                                                e);
424                 }
425             }
426         }
427     }
428
429     /**
430      * Creates and returns the service which have the given name.
431      * (Uses the 'jonas.service.<serviceName>.class' property for that)
432      * @param serviceName the name of the service to instanciate.
433      * @return Service the instance of the service.
434      * @throws ServiceException if the service can't be created.
435      */

436     protected Service createServiceFrom(String JavaDoc serviceName) throws ServiceException {
437         if (logger.isLoggable(BasicLevel.DEBUG)) {
438             logger.log(BasicLevel.DEBUG, serviceName);
439         }
440         String JavaDoc prefixPropName = PREFIX_SERVICE_PROP_NAME + "." + serviceName;
441         String JavaDoc serviceClassName = props.getValue(prefixPropName + ".class");
442         if (serviceClassName == null) {
443             throw new ServiceException("Property '" + prefixPropName + ".class' missing in '"
444                                        + JProp.JONASPREFIX + "' properties file");
445         }
446         try {
447             ClassLoader JavaDoc classLoader = this.getClass().getClassLoader();
448             if (classLoader == null) {
449                 classLoader = Thread.currentThread().getContextClassLoader();
450             }
451             Class JavaDoc serviceClass = classLoader.loadClass(serviceClassName);
452             Service service = (Service) serviceClass.newInstance();
453             service.setName(serviceName);
454             if (logger.isLoggable(BasicLevel.DEBUG)) {
455                 logger.log(BasicLevel.DEBUG, "class used: " + serviceClassName);
456             }
457             return (service);
458         } catch (NoClassDefFoundError JavaDoc ncdfe) {
459             logger.log(BasicLevel.WARN, "WARNING : The service '" + serviceName
460                        + "' is disabled because a class for this service is missing."
461                        + " Check your services in jonas.properties file and your environment variables. Missing class : '"
462                        + ncdfe.getMessage() + "'", ncdfe);
463             // Return null so the service won't be added.
464
return null;
465         } catch (ClassNotFoundException JavaDoc cnfe) {
466             logger.log(BasicLevel.WARN, "WARNING : The service '" + serviceName
467                        + "' is disabled because a class for this service is missing."
468                        + " Check your services in jonas.properties file and your environment variables. Missing class : '"
469                        + cnfe.getMessage() + "'", cnfe);
470             // Return null so the service won't be added.
471
return null;
472         } catch (Exception JavaDoc e) {
473             throw new ServiceException("Error when creating the service '" + serviceName + "'", e);
474         }
475     }
476
477     /**
478      * Creates and returns the context for the configuration of the service
479      * which have the given name.
480      * (Uses the 'jonas.service.<serviceName>.XXXX' properties for that)
481      * @param serviceName the name of the service to obtain the configuration.
482      * @return Context the context for the service.
483      * @throws NamingException if the context can't be built.
484      */

485     protected Context JavaDoc createServiceContextFor(String JavaDoc serviceName) throws NamingException JavaDoc {
486         if (logger.isLoggable(BasicLevel.DEBUG)) {
487             logger.log(BasicLevel.DEBUG, serviceName);
488         }
489         String JavaDoc prefixPropName = PREFIX_SERVICE_PROP_NAME + "." + serviceName;
490         CompNamingContext ctx = new CompNamingContext(serviceName);
491         for (Enumeration JavaDoc e = props.getEnv().propertyNames(); e.hasMoreElements();) {
492             String JavaDoc propName = (String JavaDoc) e.nextElement();
493             if (propName.startsWith(prefixPropName + ".")) {
494                 ctx.rebind(propName, props.getValue(propName));
495             }
496         }
497         // set Jonas name properties to all ctx
498
ctx.rebind(JProp.JONAS_NAME, props.getValue(JProp.JONAS_NAME));
499         ctx.rebind(JProp.DOMAIN_NAME, props.getValue(JProp.DOMAIN_NAME));
500         // Test JMX Remote
501
// Get specific JMX props
502
if (serviceName.equals("jmx")) {
503             String JavaDoc prop = props.getValue("host.name");
504             if (prop != null) {
505                 ctx.rebind("host.name", prop);
506             }
507             prop = props.getValue("jmxconnector.port");
508             if (prop != null) {
509                 ctx.rebind("jmxconnector.port", prop);
510             }
511         }
512         return ctx;
513     }
514
515     /**
516      * Management Method: Stop all services.
517      * The services are stopped in the reverse order of their starting.
518      * (Continue the processing of stopping for the others services, even if there is a problem
519      * for one service.)
520      * @throws ServiceException if the service can't be stopped.
521      */

522     public void stopServices() throws ServiceException {
523         String JavaDoc msgError = new String JavaDoc();
524         String JavaDoc sepError = "";
525         Service[] services = getServices();
526         for (int i = services.length - 1; i >= 0; i--) {
527             Service service = services[i];
528             if (service.isStarted()) {
529                 try {
530                     service.stop();
531                     if (logger.isLoggable(BasicLevel.DEBUG)) {
532                         logger.log(BasicLevel.DEBUG, service.getName() + " service stopped");
533                     }
534                 } catch (ServiceException e) {
535                     msgError = msgError.concat(sepError + "Cannot stop the service '"
536                                                + service.getName() + "': " + e);
537                     sepError = "\n";
538                 }
539             }
540         }
541         if (msgError.length() != 0) {
542             throw new ServiceException(msgError);
543         }
544     }
545 }
546
Popular Tags