KickJava   Java API By Example, From Geeks To Geeks.

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


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
24 /*
25  * @(#) AbstractManager.java
26  *
27  * Copyright 2000-2001 by iPlanet/Sun Microsystems, Inc.,
28  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
29  * All rights reserved.
30  *
31  * This software is the confidential and proprietary information
32  * of iPlanet/Sun Microsystems, Inc. ("Confidential Information").
33  * You shall not disclose such Confidential Information and shall
34  * use it only in accordance with the terms of the license
35  * agreement you entered into with iPlanet/Sun Microsystems.
36  */

37 package com.sun.enterprise.server;
38
39 import com.sun.enterprise.admin.event.AdminEventListenerException;
40 import com.sun.enterprise.admin.event.AdminEventResult;
41 import com.sun.enterprise.admin.event.BaseDeployEvent;
42 import com.sun.enterprise.admin.server.core.AdminService;
43 import com.sun.enterprise.config.ConfigBean;
44 import com.sun.enterprise.config.ConfigContext;
45 import com.sun.enterprise.config.ConfigException;
46 import com.sun.enterprise.config.serverbeans.ApplicationHelper;
47 import com.sun.enterprise.config.serverbeans.ApplicationRef;
48 import com.sun.enterprise.config.serverbeans.Server;
49 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
50 import com.sun.enterprise.deployment.Application;
51 import com.sun.enterprise.deployment.backend.DeployableObjectType;
52 import com.sun.enterprise.instance.BaseManager;
53 import com.sun.enterprise.management.StateManageable;
54 import com.sun.logging.LogDomains;
55 import java.io.File JavaDoc;
56 import java.util.Hashtable JavaDoc;
57 import java.util.List JavaDoc;
58 import java.util.logging.Level JavaDoc;
59 import java.util.logging.Logger JavaDoc;
60 import java.util.Set JavaDoc;
61 import javax.management.MBeanException JavaDoc;
62 import javax.management.MBeanServer JavaDoc;
63 import javax.management.ObjectName JavaDoc;
64
65 /**
66  * Base manager class for J2ee applications. A manager manages all
67  * j2ee application and stand alone modules for a server instance.
68  * It also acts as a listener for the deployment events.
69  *
70  * <p> This manager object loads all the deployed applications
71  * or stand alone modules.
72  *
73  * <xmp>
74  * Code Example:
75  * AbstractManager mgr = new SubClassOfAbstractManager(loader, baseMgr);
76  *
77  * // loads the deployed apps returned by the base mgr
78  * mgr.load();
79  * </xmp>
80  *
81  * @author Mahesh Kannan
82  * @author Nazrul Islam
83  * @since JDK1.4
84  */

85 public abstract class AbstractManager implements MonitorListener {
86
87     /** parent class loader for the j2ee applications */
88     protected ClassLoader JavaDoc parentClassLoader;
89
90     /** application registry */
91     protected ApplicationRegistry registry;
92
93     /** encapsulates all application related info */
94     protected BaseManager configManager;
95
96     /** application id vs application loaders */
97     protected Hashtable JavaDoc id2loader;
98
99     /** monitors the time stamp of the RELOAD_FILE */
100     protected ReloadMonitor reloadMonitor = null;
101
102     /** Indicates whether system apps of this manager are already loaded */
103     protected boolean systemAppsLoaded = false;
104     
105     /** logger to log core messages */
106     static Logger JavaDoc _logger = LogDomains.getLogger(LogDomains.CORE_LOGGER);
107
108     /**
109      * Inintializes the variables and constructs the application registry.
110      *
111      * @param parentClassLoader parent class loader for this manager
112      * @param configMgr encapsulates all application related info
113      */

114     AbstractManager(ClassLoader JavaDoc parentClassLoader, BaseManager configMgr)
115     {
116
117         this.id2loader = new Hashtable JavaDoc();
118         this.parentClassLoader = parentClassLoader;
119         this.configManager = configMgr;
120
121         // initializes the application registry
122
this.registry = ApplicationRegistry.getInstance();
123
124         // initializes the reload monitor if dynamic reload is enabled
125
boolean monitor = this.configManager.isDynamicReloadEnabled();
126         if (monitor) {
127             this.reloadMonitor = ReloadMonitor.getInstance(
128                             this.configManager.getReloadPollIntervalInMillis());
129         }
130     }
131
132     /**
133      * Loads the deployed and enabled applications and/or stand alone modules.
134      * The list and the type (application vs stand alone module) is determined
135      * from the associated config manager object.
136      */

137     void load() {
138         
139         // Set the thread context classloader
140
final ClassLoader JavaDoc connCL = this.parentClassLoader;
141         java.security.AccessController.doPrivileged(
142             new java.security.PrivilegedAction JavaDoc() {
143                 public Object JavaDoc run() {
144                     Thread.currentThread().setContextClassLoader(connCL);
145                     return null;
146                 }
147             }
148         );
149         
150         //loadSystem();
151

152         // deployed application list from config
153
List JavaDoc appList = null;
154         try {
155             appList = this.configManager.listIds();
156         } catch (ConfigException confEx) {
157             _logger.log(Level.WARNING,
158                         "core.error_while_getting_deployed_applist", confEx);
159             return;
160         }
161
162         // set jsr77 to true
163
boolean jsr77 = true;
164
165         // loads all the deployed applications
166
for (int i=0; i<appList.size(); i++) {
167
168             // registration name of this app
169
String JavaDoc id = (String JavaDoc) appList.get(i);
170
171             try {
172             if (this.configManager.isSystem(id)) {
173             continue;
174             }
175             } catch (ConfigException confEx) {
176                 _logger.log(Level.WARNING,
177                             "core.error_while_loading_app", confEx);
178         }
179
180             try {
181                 // loader for this app
182
AbstractLoader loader = getLoader(id);
183
184                 // create jsr77 root mBean
185
loader.createRootMBean();
186             
187                 // if app is enabled
188
ConfigContext ctx = configManager.getConfigContext();
189                 if (isEnabled(ctx, id)) {
190
191                     // set jsr77 root mBean state to STARTING
192
try {
193                         loader.setState(StateManageable.STARTING_STATE);
194                     } catch (MBeanException JavaDoc mbe) {
195                         _logger.log(Level.WARNING,
196                             "core.error_while_setting_jsr77_state",mbe);
197                     }
198
199                     /**
200                      *Add the loader to the map so it can be cleaned up later
201                      *even if the load fails.
202                      */

203                     id2loader.put(id, loader);
204                     
205                     // if loader was able to load successfully
206
if (loader.load(jsr77) == true) {
207                         // set jsr77 root mBean state to RUNNING
208
try {
209                             loader.setState(StateManageable.RUNNING_STATE);
210                         } catch (MBeanException JavaDoc mbe) {
211                             _logger.log(Level.WARNING,
212                             "core.error_while_setting_jsr77_state",mbe);
213                         }
214
215                     } else {
216                         // set jsr77 root mBean state to FAILED
217
try {
218                             loader.setState(StateManageable.FAILED_STATE);
219                         } catch (MBeanException JavaDoc mbe) {
220                             _logger.log(Level.WARNING,
221                             "core.error_while_setting_jsr77_state",mbe);
222                         }
223
224                         _logger.log(Level.WARNING,
225                                     "core.application_not_loaded", id);
226                     }
227                     // adds this app to be monitored if ON
228
addToReloadMonitor(id);
229                 } else if (! isEnabled(ctx, id)) {
230                     // if app is not enabled
231
// set jsr77 root mBean state to STOPPED
232
try {
233                         loader.setState(StateManageable.STOPPED_STATE);
234                         loader.createLeafMBeans();
235                     } catch (MBeanException JavaDoc mbe) {
236                         _logger.log(Level.WARNING,
237                             "core.error_while_setting_jsr77_state",mbe);
238                     }
239
240                 }
241             } catch (ConfigException confEx) {
242                 _logger.log(Level.WARNING,
243                             "core.error_while_loading_app", confEx);
244             } catch (Throwable JavaDoc t) {
245                 _logger.log(Level.WARNING,
246                     "core.unexpected_error_occured_while_loading_app", t);
247             }
248         }
249     }
250     /**
251      * Loads the deployed and enabled system applications and/or stand alone modules.
252      * The list and the type (application vs stand alone module) is determined
253      * from the associated config manager object.
254      */

255     void loadSystem() {
256         
257         // set jsr77 to true
258
boolean jsr77 = true;
259
260         if(systemAppsLoaded)
261             return;
262
263         // deployed application list from config
264
List JavaDoc appList = null;
265         try {
266             appList = this.configManager.listIds();
267         } catch (ConfigException confEx) {
268             _logger.log(Level.WARNING,
269                         "core.error_while_getting_deployed_applist", confEx);
270             return;
271         }
272
273         // loads all the deployed applications
274
for (int i=0; i<appList.size(); i++) {
275
276             // registration name of this app
277
String JavaDoc id = (String JavaDoc) appList.get(i);
278             loadOneSystemApp(id, jsr77);
279
280         }
281         systemAppsLoaded = true;
282     }
283
284
285     public void loadOneSystemApp(String JavaDoc id, boolean jsr77) {
286      // Set the thread context classloader
287
final ClassLoader JavaDoc connCL = this.parentClassLoader;
288         final ClassLoader JavaDoc cl = (ClassLoader JavaDoc)
289             java.security.AccessController.doPrivileged(
290             new java.security.PrivilegedAction JavaDoc() {
291                 public Object JavaDoc run() {
292                     ClassLoader JavaDoc cloader = Thread.currentThread().getContextClassLoader();
293                     Thread.currentThread().setContextClassLoader(connCL);
294                     return cloader;
295                 }
296             }
297         );
298
299         try {
300             // if app is enabled
301
ConfigContext ctx = configManager.getConfigContext();
302             if (ResourcesUtil.getInstance().belongToSystemRar(id) ||
303                     (this.configManager.isSystem(id)
304                      && isEnabled(ctx, id))) {
305
306                 // loader for this app
307
AbstractLoader loader = getLoader(id);
308
309                 // create jsr77 root mBean
310
loader.createRootMBean();
311                 
312                 /*
313                  *Add the loader to the map so it can be cleaned up later
314                  *even if the load fails.
315                  */

316                 id2loader.put(id, loader);
317                 
318                 // if loader was able to load successfully
319
if ( ! loader.load(jsr77) ) {
320                     _logger.log(Level.WARNING,
321                                 "core.application_not_loaded", id);
322                 }
323             }
324
325         } catch (ConfigException confEx) {
326             _logger.log(Level.SEVERE,
327                         "core.error_while_loading_system_app", confEx);
328         } catch (Throwable JavaDoc t) {
329             _logger.log(Level.SEVERE,
330                "core.unexpected_error_occured_while_loading_system_app", t);
331         }
332
333         if (cl != connCL) {
334             java.security.AccessController.doPrivileged(
335                 new java.security.PrivilegedAction JavaDoc() {
336                     public Object JavaDoc run() {
337                         Thread.currentThread().setContextClassLoader(cl);
338                         return null;
339                     }
340                }
341             );
342         }
343
344     }
345
346
347     /**
348      * Shutsdown the reload monitor. The bean container shutdown
349      * activity is handled from the ApplicationLifeCycle module.
350      */

351     void shutdown() {
352         
353         try {
354             // shuts down the dynamic reload monitor
355
if (this.reloadMonitor != null) {
356                 this.reloadMonitor.stop();
357             }
358         } catch (Throwable JavaDoc t) {
359             _logger.log(Level.WARNING,
360                 "core.unexpected_error_occured_while_app_shutdown", t);
361         }
362     }
363
364     /**
365      * Adds the given application or stand alone module to reload monitor.
366      *
367      * @param id registration name of the application
368      *
369      * @throws ConfigException if an error while parsing server configuration
370      */

371     protected void addToReloadMonitor(String JavaDoc id) throws ConfigException {
372
373         // adds the reload file to monitor the time stamp
374
if (this.reloadMonitor != null && !(this.configManager.isSystem(id))) {
375             String JavaDoc mPath = this.configManager.getLocation(id)
376                          + File.separator + ReloadMonitor.RELOAD_FILE;
377             MonitorableEntry entry =
378                 new MonitorableEntry(id, new File JavaDoc(mPath), this);
379             this.reloadMonitor.addMonitorableEntry(entry);
380         }
381     }
382
383     /**
384      * Removes the given application or stand alone module from reload monitor.
385      *
386      * @param id registration name of the application
387      */

388     protected void removeFromReloadMonitor(String JavaDoc id) {
389         // 4925582 bnevins 10-1-03
390
// If the user makes some tiny error and does a touch .reload -- they couldn't fix
391
// it and try again. Now -- we don't remove it from the monitor list. So they can try again and
392
// a regular first-time deployment will be attempted. They can keep trying until a server restart.
393
// After a restart, they'll have to deploy from scratch again.
394

395         /*
396          if (this.reloadMonitor != null) {
397             //this.reloadMonitor.removeMonitoredEntry(id);
398         }
399          */

400     }
401
402     // ---- START OF MonitorListener METHOD -----------------------------------
403

404     /**
405      * No-op. Subclasses should implement this methods if they want to handle
406      * the dynamic reload callbacks.
407      *
408      * @param entry monitored entry with a change in time stamp
409      *
410      * @return no-op; returns false
411      */

412     public boolean reload(MonitorableEntry entry) {
413         return false;
414     }
415
416     /**
417      * No-op. Subclasses should implement this methods if they want to handle
418      * the auto deploy callbacks.
419      *
420      * @param entry entry thats being monitored
421      * @param archive newly detected archive under the auto deploy directory
422      *
423      * @return no-op; returns false
424      */

425     public boolean deploy(MonitorableEntry entry, File JavaDoc archive) {
426         return false;
427     }
428
429     // ---- END OF MonitorListener METHOD -------------------------------------
430

431     /**
432      * Returns the loader for this type of manager and the given id.
433      *
434      * @param id registration name of an application or stand alone module
435      *
436      * @return the correct loader for this manager
437      */

438     protected abstract AbstractLoader getLoader(String JavaDoc id);
439
440     /**
441      * Returns the parent class loader (of ejb modules) used by this manager.
442      *
443      * @return the parent class loader used by this manager
444      */

445     ClassLoader JavaDoc getParentClassLoader() {
446         return this.parentClassLoader;
447     }
448
449     /**
450      * This method is used to determine if an app or a module is already
451      * registered.
452      * @return true if the app is registered
453      **/

454     public boolean isRegistered(String JavaDoc id) {
455         return this.configManager.isRegistered(id);
456     }
457
458     /**
459      * @return Whether the JSR77 MBean for a specific app exists
460      */

461     protected boolean loadJSR77(String JavaDoc appName, DeployableObjectType type) {
462     ObjectName JavaDoc jsr77mBeanObjectName = null;
463     try {
464             String JavaDoc domainName = null;
465             AdminService adminService = AdminService.getAdminService();
466             if (adminService != null) {
467                 domainName = adminService.getAdminContext().getDomainName();
468             } else {
469                 return false;
470             }
471
472             //We do not load JSR77 MBeans for web modules
473
//web modules are loaded by the Tomcat container
474
String JavaDoc j2eeType = null;
475             if (type.isAPP()) {
476                 j2eeType = "J2EEApplication";
477             } else if (type.isEJB()) {
478                 j2eeType = "EJBModule";
479             } else if (type.isCONN()) {
480                 j2eeType = "ResourceAdapterModule";
481             } else if (type.isCAR()) {
482                 j2eeType = "AppClientModule";
483             } else if (type.isWEB()) {
484                 return false;
485             }
486
487             String JavaDoc instanceName =
488                 ApplicationServer.getServerContext().getInstanceName();
489
490             //form query
491
StringBuffer JavaDoc sb = new StringBuffer JavaDoc("");
492             sb.append(domainName + ":");
493             sb.append("j2eeType=" + j2eeType + ",");
494             sb.append("name=" + appName + ",");
495             if (!type.isAPP()) {
496                 sb.append("J2EEApplication=null" + ",");
497             }
498             sb.append("J2EEServer=" + instanceName + "," + "*");
499
500             // perform query
501
MBeanServer JavaDoc mbs = adminService.getAdminContext().getMBeanServer();
502
503             ObjectName JavaDoc objNamePattern = new ObjectName JavaDoc(sb.toString());
504             java.util.Set JavaDoc s = mbs.queryNames(objNamePattern, null);
505             if (s != null && s.size()>0) {
506                 ObjectName JavaDoc [] objNameArr =
507                     (ObjectName JavaDoc[]) s.toArray( new ObjectName JavaDoc[s.size()]);
508                 if (objNameArr.length>0) {
509                     jsr77mBeanObjectName = objNameArr[0];
510                 }
511             }
512         } catch (Exception JavaDoc ex) {
513             //Ignore on purpose.
514
}
515
516     return jsr77mBeanObjectName == null;
517     }
518
519     /**
520      * Whether or not a component (either an application or a module) should be
521      * enabled is defined by the "enable" attribute on both the
522      * application/module element and the application-ref element.
523      *
524      * @param config The dynamic ConfigContext
525      * @param moduleName The name of the component (application or module)
526      * @return boolean
527      */

528     protected boolean isEnabled (ConfigContext config, String JavaDoc moduleName) {
529         try {
530             ConfigBean app = ApplicationHelper.findApplication(config, moduleName);
531
532             Server server = ServerBeansFactory.getServerBean(config);
533             ApplicationRef appRef = server.getApplicationRefByRef(moduleName);
534
535             return ((app != null && app.isEnabled()) &&
536                         (appRef != null && appRef.isEnabled()));
537         } catch (ConfigException e) {
538             AdminEventListenerException ex = new AdminEventListenerException();
539             ex.initCause(e);
540             _logger.log(Level.FINE, "Error in finding " + moduleName, e);
541
542             //If there is anything wrong, do not enable the module
543
return false;
544         }
545     }
546
547     protected void registerException(BaseDeployEvent event, String JavaDoc msg) {
548         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
549         result.setResultCode(AdminEventResult.SUCCESS);
550         result.addException(event.getEffectiveDestination(),
551                             new AdminEventListenerException(msg));
552     }
553 }
554
Popular Tags