KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > server > ApplicationServer


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.server;
24
25 import java.io.File JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.io.IOException JavaDoc;
28
29 import com.sun.enterprise.Switch;
30 import com.sun.enterprise.server.J2EEServer;
31 import com.sun.enterprise.security.audit.AuditModuleEventListenerImpl;
32 import com.sun.enterprise.security.audit.SecurityServiceEventListenerImpl;
33 import com.sun.enterprise.security.auth.realm.AuthRealmEventListenerImpl;
34 import com.sun.enterprise.security.auth.realm.UserMgmtEventListenerImpl;
35
36 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
37 import com.sun.enterprise.config.serverbeans.TransactionService;
38 import com.sun.enterprise.config.serverbeans.Applications;
39 import com.sun.enterprise.config.serverbeans.ServerXPathHelper;
40 import com.sun.enterprise.config.ConfigBeansFactory;
41 import com.sun.enterprise.config.ConfigContext;
42 import com.sun.enterprise.config.ConfigException;
43
44 import com.sun.enterprise.instance.InstanceFactory;
45 import com.sun.enterprise.instance.InstanceEnvironment;
46 import com.sun.enterprise.instance.AppsManager;
47 import com.sun.enterprise.instance.EjbModulesManager;
48 import com.sun.enterprise.instance.ConnectorModulesManager;
49 import com.sun.enterprise.loader.ClassLoaderUtils;
50 import com.sun.enterprise.util.logging.Debug;
51
52 import com.sun.enterprise.util.ConnectorClassLoader;
53 import com.sun.enterprise.resource.ResourceInstaller;
54
55 import com.sun.appserv.server.ServerLifecycle;
56 import com.sun.appserv.server.ServerLifecycleException;
57
58 import com.sun.enterprise.server.pluggable.InternalServicesList;
59
60 import com.sun.enterprise.admin.event.AdminEventListenerRegistry;
61 import com.sun.enterprise.admin.event.jms.JmsServiceEvent;
62 import com.sun.enterprise.admin.event.jms.JmsHostEvent;
63 import com.sun.enterprise.admin.alert.AlertConfigurator;
64 //import com.sun.enterprise.admin.event.EventTester;
65

66 //IASRI 4717059 BEGIN
67
//import com.sun.ejb.containers.ReadOnlyBeanNotifierImpl;
68
//IASRI 4717059 END
69

70 import java.util.logging.Level JavaDoc;
71 import java.util.logging.Logger JavaDoc;
72 import com.sun.logging.LogDomains;
73 import com.sun.enterprise.server.logging.ServerLogManager;
74
75 /**
76  * ApplicationServer is the main entry point for iAS 7.0 J2EE server instance.
77  * This code implements the server lifecycle state transitions and it relies on
78  * various iAS 7.0 subsystems such as Web/EJB containers throught its lifecycle.
79  * com.sun.enterprise.J2EEServer is the RI counerpart of this code; the evolving
80  * iAS server implementation replaces functionality of RI J2EEServer.
81  */

82 public class ApplicationServer {
83
84     /** server logger */
85     static Logger JavaDoc _logger = LogDomains.getLogger(LogDomains.CORE_LOGGER);
86
87     public static java.io.PrintStream JavaDoc ostream = System.out;
88     public static java.io.PrintStream JavaDoc estream = System.err;
89
90     private static final String JavaDoc USER_TX = "java:comp/UserTransaction";
91     private static final String JavaDoc CODEBASE_PROP = "java.rmi.server.codebase";
92
93     /**
94      * Default services implementing lifecycle interface for orderly startup/
95      * shutdown and hot deployment.
96      * Each service entry is of the form {name, className}.
97      * Note: Make sure LifecycleModuleService is the last subsystem in this list.
98      */

99     static String JavaDoc[][]servicesByName;
100
101
102     /** ServerContext -- server-wide runtime environment context **/
103     private static ServerContext context = null;
104
105     /** services -- standard runtime service objects **/
106     private ArrayList JavaDoc services = new ArrayList JavaDoc();
107
108     /** common class loader for the server */
109     private ClassLoader JavaDoc commonClassLoader;
110
111     /** share class loader for the server */
112     private ClassLoader JavaDoc connectorClassLoader;
113
114     /**
115      * Default constructor.
116      */

117     public ApplicationServer() {}
118
119     /**
120      * Server is initializing subsystems and setting up the runtime environment.
121      * Prepare for the beginning of active use of the public methods of this
122      * subsystem. This method is called before any of the public methods of
123      * this subsystem are utilized.
124      *
125      * @param context ServerContext the server runtime context.
126      *
127      * @exception IllegalStateException if this subsystem has already been
128      * started
129      * @exception ServerLifecycleException if this subsystem detects a fatal
130      * error that prevents this subsystem from being used
131      */

132     public void onInitialization(ServerContext context)
133                 throws ServerLifecycleException
134     {
135         // sets the server context
136
this.context = context;
137
138         // initialize all server loggers that were not initialized
139
// Note: reInitializeServerLoggers should be called after
140
// setting the server context and before performing any
141
// other server startup activities that needs a logger
142

143         ServerLogManager.reInitializeServerLoggers();
144         
145         // print jvm info
146
printStartupInfo();
147
148         // system class loader
149
ClassLoader JavaDoc parentOfCommonCL = this.getClass().getClassLoader();
150         //Shared CL
151
//In the new CL hierarchy the parent of common classloader
152
//is the shared chain.
153
if(Boolean.getBoolean(com.sun.enterprise.server.PELaunch.USE_NEW_CLASSLOADER_PROPERTY))
154             parentOfCommonCL = PELaunch.getSharedChain();
155
156         InstanceEnvironment env = this.context.getInstanceEnvironment();
157
158         try {
159
160             String JavaDoc dir = env.getLibClassesPath();
161             String JavaDoc jarDir = env.getLibPath();
162
163             // constructs the common class loader. System class loader
164
// is the parent of common class loader. Common class loader
165
// includes <instance>/lib/classes dir, <instance>/lib/*.jar
166
// and <instance>/lib/*.zip
167
commonClassLoader =
168                 ClassLoaderUtils.getClassLoader(new File JavaDoc[] {new File JavaDoc(dir)},
169                                                 new File JavaDoc[] {new File JavaDoc(jarDir)},
170                                                 parentOfCommonCL
171                                                 );
172
173             // ignore if null
174
if (commonClassLoader == null) {
175                 commonClassLoader = parentOfCommonCL;
176             }
177         } catch (IOException JavaDoc ioe) {
178             _logger.log(Level.WARNING, "server.ioexception", ioe);
179             commonClassLoader = parentOfCommonCL;
180         } catch (Throwable JavaDoc th) {
181             _logger.log(Level.WARNING, "server.exception", th);
182             commonClassLoader = parentOfCommonCL;
183         }
184
185         // Create the connector class loader. This will be the parent class
186
// loader for all j2ee components!! Common class loader is the
187
// parent of connector class loader.
188
connectorClassLoader =
189             ConnectorClassLoader.getInstance(commonClassLoader);
190         
191         // sets the class loaders in the server context
192
if (this.context instanceof ServerContextImpl) {
193             ServerContextImpl contextImpl = (ServerContextImpl) this.context;
194
195             // set the common classloader in the server context
196
contextImpl.setCommonClassLoader(commonClassLoader);
197
198             // sets the shared class loader
199
contextImpl.setSharedClassLoader(connectorClassLoader);
200
201             // sets the life cycle parent class loader
202
contextImpl.setLifecycleParentClassLoader(connectorClassLoader);
203         }
204
205         // final common class loader for the anonymous inner class
206
final ClassLoader JavaDoc commonCL = commonClassLoader;
207
208         // set the common class loader as the thread context class loader
209
java.security.AccessController.doPrivileged(
210                     new java.security.PrivilegedAction JavaDoc() {
211                 public Object JavaDoc run() {
212                     Thread.currentThread().setContextClassLoader(commonCL);
213                     return null;
214                 }
215             }
216             );
217
218     //added the pluggable interface way of getting the list of services
219
InternalServicesList servicesList =
220         context.getPluggableFeatureFactory().getInternalServicesList();
221
222     servicesByName = servicesList.getServicesByName();
223     if (servicesByName == null) {
224           _logger.log(Level.SEVERE, "services.null");
225           throw new ServerLifecycleException();
226     }
227
228         // security manager is set inside SecurityLifecycle
229

230     // Instantiate the built-in runtime services
231
services = instantiateRuntimeServices();
232             
233         // Initialize the built-in runtime services
234
for (int i = 0; i < services.size(); i++) {
235             Object JavaDoc service = services.get(i);
236             if (service instanceof ServerLifecycle) {
237             try {
238                     ((ServerLifecycle) service).onInitialization(context);
239         } catch (ServerLifecycleException e) {
240             _logger.log(Level.SEVERE, "service.notinit",
241                 new Object JavaDoc[] {service, e.toString()});
242             throw e;
243         }
244             }
245         }
246
247         //add listeners for security dynamic reconfiguration
248
AdminEventListenerRegistry.addAuditModuleEventListener(
249                 new AuditModuleEventListenerImpl());
250         AdminEventListenerRegistry.addAuthRealmEventListener(
251                 new AuthRealmEventListenerImpl());
252         AdminEventListenerRegistry.addSecurityServiceEventListener(
253                 new SecurityServiceEventListenerImpl());
254         AdminEventListenerRegistry.addUserMgmtEventListener(
255                 new UserMgmtEventListenerImpl());
256
257         // Call RI J2EEServer initialization code. Note that all resources
258
// specified in server.xml will be loaded by the common class loader.
259
try {
260         J2EEServer.main(context);
261     } catch (Exception JavaDoc e) {
262         throw new ServerLifecycleException(e);
263     }
264
265         // final connector class loader for the anonymous inner class
266
final ClassLoader JavaDoc connCL = connectorClassLoader;
267
268         // set the connector class loader as the thread context class loader
269
java.security.AccessController.doPrivileged(
270             new java.security.PrivilegedAction JavaDoc() {
271                 public Object JavaDoc run() {
272                     Thread.currentThread().
273                         setContextClassLoader(connCL);
274                         return null;
275                     }
276                 }
277         );
278
279     }
280
281     /**
282      * Go through the list of built-in runtime services and instantiate them.
283      */

284     protected ArrayList JavaDoc instantiateRuntimeServices() throws ServerLifecycleException{
285
286         ArrayList JavaDoc serviceList = new ArrayList JavaDoc();
287
288         // Instantiate service objects
289
for (int i=0; i < servicesByName.length; i++) {
290             try {
291                 String JavaDoc[] def = servicesByName[i];
292                 Class JavaDoc c = Class.forName(def[1]);
293                 Object JavaDoc o = c.newInstance();
294
295                 serviceList.add(o);
296             } catch (Exception JavaDoc ex) {
297             _logger.log(Level.SEVERE, "server.exception", ex);
298         throw new ServerLifecycleException(ex.getMessage());
299         }
300
301         }
302         return serviceList;
303     }
304
305     /**
306      * Server is starting up applications
307      *
308      * @param context ServerContext the server runtime context.
309      *
310      * @exception ServerLifecycleException if this subsystem detects a fatal
311      * error that prevents this subsystem from being used
312      *
313      * Note: Currently, with the J2EEServer code handles initialization and
314      * applications startup in one place <code> J2EEServer.run() </code>.
315      *
316      * XXX: This separation needs to be worked on to make it cleaner.
317      */

318     public void onStartup() throws ServerLifecycleException
319     {
320         // startup the built-in runtime services
321
for (int i = 0; i < services.size(); i++) {
322             Object JavaDoc service = services.get(i);
323
324             if (service instanceof ServerLifecycle) {
325             try {
326                     ((ServerLifecycle) service).onStartup(context);
327         } catch (ServerLifecycleException e) {
328             _logger.log(Level.SEVERE, "service.notstarted",
329                 new Object JavaDoc[] {service, e.toString()});
330             throw e;
331         }
332             }
333         }
334         // _REVISIT_: Mover AlertConfigurator to configure after onReady()
335
AlertConfigurator.getAlertConfigurator( ).configure( );
336     }
337
338     /**
339      * Server has complted loading the applications and is ready to
340      * serve requests.
341      *
342      * @exception ServerLifecycleException if this subsystem detects a fatal
343      * error that prevents this subsystem from being used
344      */

345     public void onReady() throws ServerLifecycleException {
346
347         try {
348             // registers the resource manager as a listener for the
349
// resource deploy events
350
AdminEventListenerRegistry.addResourceDeployEventListener(
351                                               new ResourceManager(context));
352             // registers listeners for JmsService and JmsHost changes.
353
AdminEventListenerRegistry.addEventListener(JmsServiceEvent.eventType,
354                                        new JmsServiceEventListener());
355             AdminEventListenerRegistry.addEventListener(JmsHostEvent.eventType,
356                                        new JmsHostEventListener());
357
358             // Since onReady is called by a new thread, we have to again set
359
// the common class loader as the thread context class loader
360
java.security.AccessController.doPrivileged(
361                 new java.security.PrivilegedAction JavaDoc() {
362                     public Object JavaDoc run() {
363                         Thread.currentThread().setContextClassLoader
364                             (commonClassLoader);
365                         return null;
366                     }
367                 }
368             );
369             
370             /*
371              * com.sun.enterprise.server.startupHook is an internal
372              * undocumented property that can be used by iplanet developers
373              * to invoke some custom code just after server startup happens.
374              * Currently it is used by the ORB to easily benchmark and profile
375              * the local invocation path of remote interfaces in the EJB
376              * without having to deal with servlets or client/server processes
377              *
378              * If the property com.sun.enterprise.server.startupHook is
379              * defined then "main" in that class is executed
380              * Note: This should always be the last piece of code executed
381              * in this method
382              */

383             String JavaDoc startupHook = null;
384
385             startupHook = System.getProperty(
386                               "com.sun.enterprise.server.startupHook");
387             if (startupHook != null) {
388                 try {
389                     // Call the custom startup hook specified
390
Class JavaDoc hookClass = Class.forName(startupHook);
391                     java.lang.reflect.Method JavaDoc hookMethod =
392                         hookClass.getMethod("main",
393                                     new Class JavaDoc[] { ServerContext.class });
394                     hookMethod.invoke(null, new Object JavaDoc[] { context });
395                 }
396                 catch (Exception JavaDoc ex) {
397                     if (Debug.enabled) {
398                           _logger.log(Level.FINE, "server.exception", ex);
399                     }
400                 }
401             }
402
403         } catch (Exception JavaDoc ee) {
404             throw new ServerLifecycleException(ee);
405         }
406
407
408         // notify the built-in runtime services that we are ready
409
for (int i = 0; i < services.size(); i++) {
410             Object JavaDoc service = services.get(i);
411
412             if (service instanceof ServerLifecycle) {
413             try {
414                     ((ServerLifecycle) service).onReady(context);
415         } catch (ServerLifecycleException e) {
416           _logger.log(Level.SEVERE, "service.notready",
417                   new Object JavaDoc[] {service, e.toString()});
418         }
419             }
420         }
421     }
422
423     /**
424      * Server is shutting down applications
425      *
426      * @exception ServerLifecycleException if this subsystem detects a fatal
427      * error that prevents this subsystem from being used
428      */

429     public void onShutdown() throws ServerLifecycleException
430     {
431     
432         // shutdown the built-in runtime services (in the reverse order).
433
for (int i = services.size(); i > 0; i--) {
434             Object JavaDoc service = services.get(i-1);
435
436         _logger.log(Level.FINE,"service.shutdown",
437                     services.get(i-1));
438         try {
439                 if (service instanceof ServerLifecycle) {
440                     ((ServerLifecycle) service).onShutdown();
441         }
442         } catch (Exception JavaDoc e) {
443         //do nothing since we want to continue shutting down other LFC
444
//modules
445
_logger.log(Level.WARNING, "server.exception", e);
446         }
447         }
448     }
449
450     /**
451      * Server is terminating the subsystems and the runtime environment.
452      * Gracefully terminate the active use of the public methods of this
453      * subsystem. This method should be the last one called on a given
454      * instance of this subsystem.
455      *
456      * @exception ServerLifecycleException if this subsystem detects a fatal
457      * error that prevents this subsystem from being used
458      */

459     public void onTermination() throws ServerLifecycleException
460     {
461         //Kill all connections in the appserver's connection pools
462
if (_logger.isLoggable( Level.FINE ) ) {
463         _logger.log(Level.FINE, "Killing all pools in the appserver");
464     }
465     try {
466         Switch.getSwitch().getPoolManager().killAllPools();
467     } catch( Throwable JavaDoc t ) {
468         if (_logger.isLoggable( Level.FINE ) ) {
469             _logger.log(Level.FINE, "exception : " +t);
470         }
471     }
472  // terminate the built-in runtime services (in the reverse order)
473
for (int i = services.size(); i > 0; i--) {
474             Object JavaDoc service = services.get(i-1);
475
476         _logger.log(Level.FINE,"service.shutdown",
477                     services.get(i-1));
478         try {
479                 if (service instanceof ServerLifecycle) {
480                     ((ServerLifecycle) service).onTermination();
481                 }
482         } catch (Exception JavaDoc e) {
483         //do nothing since we want to continue shutting down other LFC
484
//modules
485
_logger.log(Level.WARNING, "server.exception", e);
486         }
487         }
488
489         services = null;
490     }
491
492     /**
493      * Get the server runtime context; returns a valid context only
494      * after initialization; a null otherwise.
495      *
496      * @return a server runtime context or null if not initialized
497      */

498     public static ServerContext getServerContext() {
499         return context;
500     }
501
502     // Called by PE Main
503
protected void setServerContext(ServerContext context) {
504         this.context = context;
505     }
506
507     private void printStartupInfo() {
508         _logger.log(Level.INFO, "j2eerunner.printstartinfo",
509                         new Object JavaDoc[] {
510                            System.getProperty("java.vm.name"),
511                            System.getProperty("java.version"),
512                            System.getProperty("java.vm.vendor") });
513     }
514 }
515
Popular Tags