KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > event > AdminEventMulticaster


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.admin.event;
24
25 import java.io.PrintWriter JavaDoc;
26 import java.io.StringWriter JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.concurrent.CopyOnWriteArrayList JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.logging.Level JavaDoc;
33 import java.util.logging.Logger JavaDoc;
34 import javax.management.NotificationListener JavaDoc;
35 import com.sun.enterprise.admin.common.constant.AdminConstants;
36 import com.sun.enterprise.admin.server.core.AdminService;
37 import com.sun.enterprise.admin.server.core.channel.AdminChannel;
38 import com.sun.enterprise.admin.server.core.channel.ReconfigHelper;
39 import com.sun.enterprise.admin.server.core.channel.RMIClient;
40 import com.sun.enterprise.config.ConfigException;
41 import com.sun.enterprise.config.ConfigChange;
42 import com.sun.enterprise.config.ConfigContext;
43 import com.sun.enterprise.config.ConfigUpdate;
44 import com.sun.enterprise.config.ConfigSet;
45 import com.sun.enterprise.config.ConfigAdd;
46 import com.sun.enterprise.config.ConfigDelete;
47 import com.sun.enterprise.config.ConfigFactory;
48 import com.sun.enterprise.config.ConfigChangeFactory;
49 import com.sun.enterprise.config.ConfigBeansFactory;
50 import com.sun.enterprise.config.serverbeans.ServerHelper;
51 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
52 import com.sun.enterprise.config.serverbeans.ConnectorResource;
53 import com.sun.enterprise.config.serverbeans.Resources;
54 import com.sun.enterprise.config.serverbeans.JdbcResource;
55 import com.sun.enterprise.config.serverbeans.ResourceAdapterConfig;
56 import com.sun.enterprise.config.ConfigBean;
57 import com.sun.enterprise.server.ServerContext;
58 import com.sun.enterprise.server.ServerContextImpl;
59 import com.sun.enterprise.admin.event.pluggable.PERestartEventHelper;
60
61 //i18n import
62
import com.sun.enterprise.util.i18n.StringManager;
63
64 //HERCULES:add
65
import java.util.HashSet JavaDoc;
66 import java.util.Set JavaDoc;
67 //end HERCULES:add
68

69 import java.lang.reflect.Method JavaDoc;
70
71 // distributed notification
72
import com.sun.enterprise.server.pluggable.PluggableFeatureFactory;
73 import com.sun.enterprise.server.ApplicationServer;
74 import com.sun.enterprise.admin.event.pluggable.NotificationFactory;
75
76 import com.sun.enterprise.admin.common.MBeanServerFactory;
77
78 import javax.management.MBeanServer JavaDoc;
79 import javax.management.ObjectInstance JavaDoc;
80 import javax.management.ObjectName JavaDoc;
81
82 /**
83  * This class multicasts all received events to appropriate event listeners.
84  */

85 public class AdminEventMulticaster {
86
87     /**
88      * Logger for admin service
89      */

90     static Logger JavaDoc logger = Logger.getLogger(AdminConstants.kLoggerName);
91
92     private static AdminEventMulticaster adminEventMulticaster = null;
93
94     /**
95      * Hashmap of listeners, the keys are event names.
96      */

97     private HashMap JavaDoc listeners;
98
99     /**
100      * Hashmap of config categories, the keys are ConfigChangeEventListeners
101      */

102     private HashMap JavaDoc configCategoryList;
103
104     // i18n StringManager
105
private static StringManager localStrings =
106         StringManager.getManager( AdminEventMulticaster.class );
107
108     /**
109      * Private constructor
110      */

111     private AdminEventMulticaster() {
112         listeners = new HashMap JavaDoc();
113         listeners.put(AdminEvent.eventType, new CopyOnWriteArrayList JavaDoc());
114         listeners.put(ConfigChangeEvent.eventType, new CopyOnWriteArrayList JavaDoc());
115         listeners.put(MonitoringEvent.eventType, new CopyOnWriteArrayList JavaDoc());
116         listeners.put(ShutdownEvent.eventType, new CopyOnWriteArrayList JavaDoc());
117         listeners.put(BaseDeployEvent.eventType, new CopyOnWriteArrayList JavaDoc());
118         listeners.put(ApplicationDeployEvent.eventType, new CopyOnWriteArrayList JavaDoc());
119         listeners.put(ModuleDeployEvent.eventType, new CopyOnWriteArrayList JavaDoc());
120         listeners.put(ResourceDeployEvent.eventType, new CopyOnWriteArrayList JavaDoc());
121         listeners.put(LogLevelChangeEvent.eventType, new CopyOnWriteArrayList JavaDoc());
122         listeners.put(MonitoringLevelChangeEvent.eventType, new CopyOnWriteArrayList JavaDoc());
123         listeners.put(AdminEventListenerRegistry.notificationEventType,
124                 new CopyOnWriteArrayList JavaDoc());
125         listeners.put(AuthRealmEvent.eventType, new CopyOnWriteArrayList JavaDoc());
126         listeners.put(AuditModuleEvent.eventType, new CopyOnWriteArrayList JavaDoc());
127         listeners.put(SecurityServiceEvent.eventType, new CopyOnWriteArrayList JavaDoc());
128         listeners.put(ElementChangeEvent.eventType, new CopyOnWriteArrayList JavaDoc());
129         listeners.put(UserMgmtEvent.eventType, new CopyOnWriteArrayList JavaDoc());
130         listeners.put(EjbTimerEvent.eventType, new CopyOnWriteArrayList JavaDoc());
131         configCategoryList = new HashMap JavaDoc();
132     }
133
134     /**
135      * Get AdminEventMulticaster.
136      */

137     public static AdminEventMulticaster getInstance() {
138         if (adminEventMulticaster == null) {
139             adminEventMulticaster = create();
140         }
141         return adminEventMulticaster;
142     }
143
144     private static synchronized AdminEventMulticaster create() {
145         return new AdminEventMulticaster();
146     }
147
148     /**
149      * Multicast specified event to all registered listeners.
150      */

151     public static AdminEventResult multicastEvent(AdminEvent event) {
152         AdminEventResult result = null;
153         AdminEventMulticaster aem = getInstance();
154
155         if ((AdminService.getAdminService() == null)
156                 || isLocal(event) || isLocalOld(event)) {
157
158             event = deferredEventResolution(event);
159             sendPreNotifyReconfigSignal(event);
160             aem.processEvent(event);
161             sendPostNotifyReconfigSignal(event);
162
163             if (AdminService.getAdminService() != null) {
164                 // it send events to local JMX listeners
165
getInstance().sendNotification(event);
166             }
167
168             result = AdminEventResult.getAdminEventResult(event);
169
170             // The following code sets restart required to true, in case of
171
// event processing error
172
RRPersistenceHelper helper = new RRPersistenceHelper();
173             helper.setRestartRequiredForServer(event, result);
174
175             AdminEventResult.clearAdminEventResultFromCache(event);
176
177         } else {
178             PluggableFeatureFactory featureFactory =
179               ApplicationServer.getServerContext().getPluggableFeatureFactory();
180
181             NotificationFactory nFactory =
182                 featureFactory.getNotificationFactory();
183             EventDispatcher eDispatcher = nFactory.createEventDispatcher();
184
185             result = eDispatcher.dispatch(event);
186         } /*else {
187             String currInstance = AdminService.getAdminService().getInstanceName();
188             logger.log(Level.INFO, MULTICAST_NOT_SUPPORTED,
189                      new String[] {currInstance, event.getInstanceName()});
190             String msg = localStrings.getString( "admin.event.unable_to_multicast_events" );
191             throw new UnsupportedOperationException( msg );
192         }*/

193         return result;
194     }
195
196     /**
197      * Check whether the event is for this instance.
198      * FIXME: remove this after moving to new code
199      */

200     private static boolean isLocalOld(AdminEvent event) {
201         String JavaDoc source = event.getInstanceName();
202         String JavaDoc instName = AdminService.getAdminService().getInstanceName();
203         String JavaDoc tDest = event.getTargetDestination();
204
205         // target destination is populated only in the new version
206
if ((instName != null)
207                 && instName.equals(source)
208                 && (tDest == null || tDest.length()==0)) {
209
210             return true;
211         } else {
212             return false;
213         }
214     }
215
216     private static boolean isLocal(AdminEvent event) {
217         String JavaDoc source = event.getTargetDestination();
218         String JavaDoc instName =
219             ApplicationServer.getServerContext().getInstanceName();
220
221         String JavaDoc effective = event.getEffectiveDestination();
222         
223         // XXX FIXME: multiple destinations
224
// if target destination is same as the current server instance
225
// then broadcast the event locally.
226
if (instName != null && instName.equals(source)) {
227             return true;
228         } else if (instName != null && instName.equals(effective)) {
229             return true;
230         } else {
231             return false;
232         }
233     }
234
235     /**
236      * Send a notification to non-java code prior to sending java notification.
237      * This is required while sending a ConfigChangeEvent to another instance.
238      */

239     private static void sendPreNotifyReconfigSignal(AdminEvent event) {
240         if (event instanceof ConfigChangeEvent) {
241             ConfigChangeEvent cce = (ConfigChangeEvent)event;
242             if (cce.isWebCoreReconfigNeeded()) {
243                 ReconfigHelper.sendReconfigMessage(event.getInstanceName());
244             }
245         }
246     }
247
248     /**
249      * Send a notification to non-java code after sending java notification.
250      * This is required while sending, a ApplicationDeployEvent or a
251      * ModuleDeployEvent for web modules, to another instance.
252      */

253     private static void sendPostNotifyReconfigSignal(AdminEvent event) {
254         if (event instanceof ApplicationDeployEvent
255                 || (event instanceof ModuleDeployEvent
256                         && ((ModuleDeployEvent)event).getModuleType().equals(
257                                 ModuleDeployEvent.TYPE_WEBMODULE))) {
258             ReconfigHelper.sendReconfigMessage(event.getInstanceName());
259         }
260     }
261
262     /**
263      * Notify failure in event handling. This method will typically be called
264      * by admin event handling components, in case it gets exceptions or
265      * errors from the listeners. However, in one case the listeners can call
266      * it directly and that is when they want to notify the event handling
267      * system that the event can not be handled and the user should restart
268      * the application server to see the effects of the event. The event
269      * framework will only handle error codes specified in AdminEventResult.
270      * @param event the event that could not be processed
271      * @param failureCode one of AdminEventResult.RESTART_NEEDED,
272      * AdminEventResult.RUNTIME_EXCEPTION, AdminEventResult.RUNTIME_ERROR,
273      * AdminEventResult.MBEAN_NOT_FOUND
274      */

275     public static void notifyFailure(AdminEvent event, String JavaDoc failureCode) {
276         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
277         result.setResultCode(failureCode);
278     }
279
280     /**
281      * Add specified attribute to result of specified event, The listeners for
282      * admin events can use this method to add attributes to the event result
283      * sent back to the admin server. The admin server can then process these
284      * attributes and take appropriate action. Since the result is sent back
285      * to admin server over RMI, all attributes added must be serializable.
286      * @param event the event that is being processed.
287      * @param name name of the attribute
288      * @param value value of the attribute
289      * @throws IllegalArgumentException if attribute name is null or attribute
290      * value is not Serializable.
291      */

292     public static void addEventResultAttribute(AdminEvent event, String JavaDoc name,
293             Object JavaDoc value) {
294         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
295         result.addAttribute(event.getEffectiveDestination(),name, value);
296     }
297
298     /**
299      * Get value of specified attribute name from the results for specified
300      * event. The method may return null if the attribute was never added or
301      * a null value was associated explicitly to the specified name,
302      * @param event the event that is being processed.
303      * @param name name of the attribute
304      * @throws IllegalArgumentException if attribute name is null.
305      * @return value of the specified attribute.
306      */

307     public static Object JavaDoc getEventResultAttribute(AdminEvent event, String JavaDoc name) {
308         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
309         return result.getAttribute(event.getEffectiveDestination(),name);
310     }
311
312     /**
313      * Remove specified attribute from results of the specified event.
314      * @param event the event that is being processed.
315      * @param name name of the attribute
316      * @throws IllegalArgumentException if attribute name is null.
317      */

318     public static void removeEventResultAttribute(AdminEvent event, String JavaDoc name) {
319         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
320         result.removeAttribute(event.getEffectiveDestination(),name);
321     }
322
323     /**
324      * This method has been added for JMX compatibility and is not yet
325      * implemented.
326      */

327     public static void addNotificationListener(NotificationListener JavaDoc listener) {
328     }
329
330     /**
331      * This method has been added for JMX compatibility and is not yet
332      * implemented.
333      */

334     public static void removeNotificationListener(NotificationListener JavaDoc listener) {
335     }
336
337     /**
338      * Add a listener of specified type.
339      */

340     static void addListener(String JavaDoc type, AdminEventListener listener) {
341         AdminEventMulticaster aem = getInstance();
342         List JavaDoc list = (List JavaDoc)aem.listeners.get(type);
343         synchronized ( aem.listeners) {
344             // If this impls array for event type does not exist.
345
// Following creates it dynamically for this event type.
346
if ( list == null ) {
347                 list = new CopyOnWriteArrayList JavaDoc();
348                 aem.listeners.put(type, list);
349             }
350         }
351         synchronized (list) {
352             list.add(listener);
353         }
354     }
355
356     /**
357      * Add a listener for ConfigChangeEvent that will be ivoked only when
358      * the config changes match the specified config change category.
359      */

360     static void addListener(String JavaDoc type, ConfigChangeCategory category,
361             ConfigChangeEventListener listener) {
362         addListener(type, listener);
363         AdminEventMulticaster aem = getInstance();
364         synchronized (aem.configCategoryList) {
365             aem.configCategoryList.put(listener, category);
366         }
367     }
368
369     /**
370      * Remove specified listener
371      * HERCULES:mod
372      * Fixed version takes into account that the same listener
373      * may be registered for multiple event types
374      */

375     static void removeListener(AdminEventListener listener) {
376         AdminEventMulticaster aem = getInstance();
377         //String type = aem.getEventTypeFromListener(listener);
378
String JavaDoc[] types = aem.getEventTypesFromListener(listener);
379         //if (type != null) {
380
for (int i=0; i<types.length; i++) {
381             String JavaDoc type = (String JavaDoc)types[i];
382             List JavaDoc list = (List JavaDoc)aem.listeners.get(type);
383             if (list.contains(listener)) {
384                 synchronized (list) {
385                     list.remove(listener);
386                 }
387                 if (type.equals(ConfigChangeEvent.eventType)) {
388                     if (aem.configCategoryList.containsKey(listener)) {
389                         synchronized (aem.configCategoryList) {
390                             aem.configCategoryList.remove(listener);
391                         }
392                     }
393                 }
394             }
395         }
396     }
397
398     /**
399      * Utility method to determine event type(s) from an event listener.
400      * HERCULES:add really part of fix for removeListener
401      */

402     private static String JavaDoc[] getEventTypesFromListener(AdminEventListener listener) {
403         Class JavaDoc[] interfaces = listener.getClass().getInterfaces();
404         Set typesSet = new HashSet JavaDoc();
405
406         for (int i = 0; i < interfaces.length; i++) {
407             String JavaDoc className = interfaces[i].getName();
408             if (className.startsWith(ApplicationDeployEvent.eventType)) {
409                 typesSet.add(ApplicationDeployEvent.eventType);
410             } else if (className.startsWith(ModuleDeployEvent.eventType)) {
411                 typesSet.add(ModuleDeployEvent.eventType);
412             } else if (className.startsWith(ResourceDeployEvent.eventType)) {
413                 typesSet.add(ResourceDeployEvent.eventType);
414             } else if (className.startsWith(BaseDeployEvent.eventType)) {
415                 typesSet.add(BaseDeployEvent.eventType);
416             } else if (className.startsWith(ConfigChangeEvent.eventType)) {
417                 typesSet.add(ConfigChangeEvent.eventType);
418             } else if (className.startsWith(MonitoringEvent.eventType)) {
419                 typesSet.add(MonitoringEvent.eventType);
420             } else if (className.startsWith(ShutdownEvent.eventType)) {
421                 typesSet.add(ShutdownEvent.eventType);
422             } else if (className.startsWith(AdminEvent.eventType)) {
423                 typesSet.add(AdminEvent.eventType);
424             }
425         }
426
427         String JavaDoc[] template = new String JavaDoc[typesSet.size()];
428         String JavaDoc[] types = (String JavaDoc[]) typesSet.toArray(template);
429         return types;
430     }
431
432     /**
433      * Process event by invoking appropriate listener(s)
434      */

435     void processEvent(AdminEvent event) {
436         String JavaDoc eventType = event.getType();
437         boolean inited = initEventHandler(event);
438         if (!inited) {
439             // Do not process event if initialization failed, because listeners
440
// are dependent on successful initlization of context in event
441
return;
442         }
443         int lstnrCnt = 0;
444         if (eventType.equals(ApplicationDeployEvent.eventType)) {
445             lstnrCnt += handleApplicationDeployEvent(event);
446             lstnrCnt += handleBaseDeployEvent(event);
447         } else if (eventType.equals(ModuleDeployEvent.eventType)) {
448             lstnrCnt += handleModuleDeployEvent(event);
449             lstnrCnt += handleBaseDeployEvent(event);
450         } else if (eventType.equals(ResourceDeployEvent.eventType)) {
451             lstnrCnt += handleResourceDeployEvent(event);
452             lstnrCnt += handleBaseDeployEvent(event);
453         } else if (eventType.equals(BaseDeployEvent.eventType)) {
454             lstnrCnt += handleBaseDeployEvent(event);
455         } else if (eventType.equals(ConfigChangeEvent.eventType)) {
456             lstnrCnt += handleConfigChangeEvent(event);
457         } else if (eventType.equals(MonitoringEvent.eventType)) {
458             lstnrCnt += handleMonitoringEvent(event);
459         } else if (eventType.equals(MonitoringLevelChangeEvent.eventType)) {
460             lstnrCnt += handleMonitoringLevelChangeEvent(event);
461         } else if (eventType.equals(LogLevelChangeEvent.eventType)) {
462             lstnrCnt += handleLogLevelChangeEvent(event);
463         } else if (eventType.equals(ShutdownEvent.eventType)) {
464             lstnrCnt += handleShutdownEvent(event);
465         } else if (eventType.equals(AuthRealmEvent.eventType)) {
466             lstnrCnt += handleAuthRealmEvent(event);
467         } else if (eventType.equals(AuditModuleEvent.eventType)) {
468             lstnrCnt += handleAuditModuleEvent(event);
469         } else if (eventType.equals(SecurityServiceEvent.eventType)) {
470             lstnrCnt += handleSecurityServiceEvent(event);
471         } else if (eventType.equals(ElementChangeEvent.eventType)) {
472             lstnrCnt += handleElementChangeEvent(event);
473         } else if (eventType.equals(UserMgmtEvent.eventType)) {
474             lstnrCnt += handleUserMgmtEvent(event);
475         } else if (eventType.equals(EjbTimerEvent.eventType)) {
476             lstnrCnt += handleEjbTimerEvent(event);
477         } else {
478             BaseAdminEventHandler handler = new BaseAdminEventHandler(event);
479             lstnrCnt += handler.processEvent();
480         }
481         if (lstnrCnt == 0) {
482             handleNoListeners(event);
483         }
484         destroyEventHandler(event);
485     }
486
487     /**
488      * Initialize event handler. Invoked just before event processing starts.
489      * @return true if initialization is successful, false otherwise
490      */

491     private boolean initEventHandler(AdminEvent event) {
492         //Begin EE: 4921345 Remove dependency on AdminService
493
if (AdminService.getAdminService() == null) {
494             return true;
495         }
496         //End EE: 4921345 Remove dependency on AdminService
497
boolean success = true;
498         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
499         ConfigContext global =
500                 AdminService.getAdminService().getContext().getConfigContext();
501         ConfigContext local = null;
502         if (event.configChangeList != null) {
503             try {
504                 local = (ConfigContext)global.clone();
505
506                 // if dependent changes fails, it will be ignored
507
applyDependentChangesToContext(local,event.dependentChangeList);
508
509                 applyChangesToContext(local, event.configChangeList);
510             } catch (ConfigException ce) {
511                 result.setResultCode(AdminEventResult.CONFIG_SNAPSHOT_ERROR);
512                 result.addException(event.getEffectiveDestination(),ce);
513                 logger.log(Level.FINE, HANDLER_INIT_ERROR, ce.getMessage());
514                 debug(getStackTraceFromThrowable(ce));
515                 success = false;
516             } catch (Throwable JavaDoc t) {
517                 handleError(event, t, result, HANDLER_INIT_ERROR);
518                 success = false;
519             }
520         } else {
521             local = global;
522         }
523         event.setOldContext(global);
524         event.setContext(local);
525         return success;
526     }
527
528     /**
529      * Sets the type of resource or application. Adds dependent
530      * config change objects.
531      * <p>
532      * Note: This method is called when event reaches the remote server
533      *
534      * @param event event that is about to be forwarded to the listener
535      * @return updated event
536      */

537     private static AdminEvent deferredEventResolution(AdminEvent event) {
538
539         if (AdminService.getAdminService() == null) {
540             return event;
541         }
542
543         ConfigContext ctx =
544                 AdminService.getAdminService().getContext().getConfigContext();
545
546         // some event adjustmenets with effective context
547
if (event instanceof ResourceDeployEvent) {
548
549             // possibly event needs "deffered" type resoluion
550
ResourceDeployEvent res = (ResourceDeployEvent) event;
551
552             String JavaDoc type = res.getResourceType();
553             if (type==null) {
554                 try {
555                     type = EventBuilder.getResourceTypeByName(ctx,
556                             res.getResourceName(), res.getTargetDestination());
557                     res.setResourceType(type);
558                 } catch (Exception JavaDoc e) { }
559             }
560
561             // get rid of the resource from domain level for undeploy event
562
try {
563                 String JavaDoc action = res.getAction();
564                 if (BaseDeployEvent.REMOVE_REFERENCE.equals(action)
565                         || BaseDeployEvent.UNDEPLOY.equals(action)) {
566                         
567                     String JavaDoc effective = res.getEffectiveDestination();
568                     String JavaDoc resName = res.getResourceName();
569                     DependencyResolver dr =
570                             new DependencyResolver(ctx, effective);
571                     List JavaDoc list = dr.getConfigDeleteForResource(resName, type);
572                     res.addDependentConfigChange(list);
573
574                     // adds dependencies for pools if pool is not referenced
575

576                     if ((type != null) && type.equals(res.RES_TYPE_JDBC)) {
577
578                         ConfigBean jRes = dr.findResource(resName, type);
579
580                         if (jRes instanceof JdbcResource) {
581                             String JavaDoc pool = ((JdbcResource) jRes).getPoolName();
582                             String JavaDoc server = AdminService.
583                                 getAdminService().getInstanceName();
584
585                             if (!isJdbcPoolReferenced(ctx, pool, server,
586                                                       resName)) {
587
588                                 res.addDependentConfigChange(
589                                     dr.getConfigDeleteForResource(pool,
590                                         ResourceDeployEvent.RES_TYPE_JCP) );
591                             }
592                         }
593
594                     // connector connection pool
595
} else if ((type != null) && type.equals(res.RES_TYPE_CR)) {
596
597                         ConfigBean cRes = dr.findResource(resName, type);
598
599                         if (cRes instanceof ConnectorResource) {
600                             String JavaDoc pool =
601                                 ((ConnectorResource) cRes).getPoolName();
602                             String JavaDoc server = AdminService.
603                                 getAdminService().getInstanceName();
604
605                             if (!isConnectorPoolReferenced(ctx, pool, server,
606                                                            resName)) {
607
608                                 res.addDependentConfigChange(
609                                     dr.getConfigDeleteForResource(pool,
610                                         ResourceDeployEvent.RES_TYPE_CCP) );
611                             }
612                         }
613                     }
614                 }
615             } catch (Exception JavaDoc e) { }
616
617         } else if (event instanceof BaseDeployEvent) {
618
619             // possibly event needs "deffered" type resoluion
620
BaseDeployEvent app = (BaseDeployEvent) event;
621             String JavaDoc type = app.getJ2EEComponentType();
622             if (type==null) {
623                 try {
624                     event = EventBuilder.resolveModAppDeployEventType(app, ctx);
625                 } catch (Exception JavaDoc e) { }
626             }
627
628             // removes the application from the doman level for undeploy
629
try {
630                 String JavaDoc action = app.getAction();
631                 if (BaseDeployEvent.REMOVE_REFERENCE.equals(action)
632                         || BaseDeployEvent.UNDEPLOY.equals(action)) {
633                         
634                     String JavaDoc effective = app.getEffectiveDestination();
635                     String JavaDoc appName = app.getJ2EEComponentName();
636                     DependencyResolver dr =
637                             new DependencyResolver(ctx, effective);
638                     List JavaDoc list = dr.getConfigDeleteForApplication(appName);
639                     app.addDependentConfigChange(list);
640
641                     // remove resource adapter config if found
642
ResourceAdapterConfig raConfig =
643                         dr.findResourceAdapterConfigByName(appName);
644
645                     if (raConfig != null) {
646                         app.addDependentConfigChange(
647                             dr.getConfigDeleteForResource(raConfig) );
648                     }
649                 }
650             } catch (Exception JavaDoc e) { }
651         }
652
653         return event;
654     }
655
656     /**
657      * Returns true if the named pool has a reference from a jdbc resource
658      * that is used by the given server instance.
659      *
660      * @param ctx config context
661      * @param poolName jdbc resource pool name
662      * @param serverName name of the server instance
663      * @param eResName name of excluded resource
664      *
665      * @return true if the pool is used by the server instance
666      *
667      * @throw ConfigException if an error while parsing domain.xml
668      */

669     private static boolean isJdbcPoolReferenced(ConfigContext ctx,
670             String JavaDoc poolName, String JavaDoc serverName, String JavaDoc eResName)
671             throws ConfigException {
672
673         if (ctx==null || poolName==null || serverName==null || eResName==null) {
674             return false;
675         }
676
677         Resources rBean = ServerBeansFactory.getDomainBean(ctx).getResources();
678
679         JdbcResource[] jdbcBeans = rBean.getJdbcResource();
680
681         // no jdbc resource in the domain, so it is not possible
682
// for the jdbc pool to be in use by a server in this domain
683
if (jdbcBeans == null) {
684             return false;
685         }
686
687         for (int i = 0; i <jdbcBeans.length; i++) {
688
689             // jdbc resource is not referenced by the server instance
690
if ( !ServerHelper.serverReferencesResource(
691                     ctx, serverName, jdbcBeans[i].getJndiName()) ) {
692
693                 continue;
694             } else {
695                 String JavaDoc pool = jdbcBeans[i].getPoolName();
696                 String JavaDoc rName = jdbcBeans[i].getJndiName();
697
698                 // pool is used by another resource
699
if ( (pool != null) && pool.equals(poolName)
700                         && (!eResName.equals(rName)) ) {
701
702                     // jdbc pool is referenced by server (server->res->pool)
703
return true;
704                 }
705             }
706         }
707
708         // no jdbc resource referred by this server is using this pool
709
return false;
710     }
711
712     /**
713      * Returns true if the named pool has a reference from a connector resource
714      * that is used by the given server instance.
715      *
716      * @param ctx config context
717      * @param poolName connector pool name
718      * @param serverName name of the server instance
719      * @param eResName name of excluded resource name
720      *
721      * @return true if the pool is used by the server instance
722      *
723      * @throw ConfigException if an error while parsing domain.xml
724      */

725     private static boolean isConnectorPoolReferenced(ConfigContext ctx,
726             String JavaDoc poolName, String JavaDoc serverName, String JavaDoc eResName)
727             throws ConfigException {
728
729         if (ctx==null || poolName==null || serverName==null || eResName==null) {
730             return false;
731         }
732
733         Resources rBean = ServerBeansFactory.getDomainBean(ctx).getResources();
734
735         ConnectorResource[] conBeans = rBean.getConnectorResource();
736
737         // no connector resource in the domain, so it is not possible
738
// for the connector pool to be in use by a server in this domain
739
if (conBeans == null) {
740             return false;
741         }
742
743         for (int i = 0; i <conBeans.length; i++) {
744
745             // connector resource is not referenced by the server instance
746
if ( !ServerHelper.serverReferencesResource(
747                     ctx, serverName, conBeans[i].getJndiName()) ) {
748
749                 continue;
750             } else {
751                 String JavaDoc pool = conBeans[i].getPoolName();
752                 String JavaDoc rName = conBeans[i].getJndiName();
753
754                 // pool is used by another resource
755
if ( (pool != null) && pool.equals(poolName)
756                         && (!eResName.equals(rName))) {
757
758                     return true;
759                 }
760             }
761         }
762         return false;
763     }
764
765     /**
766      * Applies dependent config changes if necessary.
767      */

768     private void applyDependentChangesToContext(ConfigContext ctx, List JavaDoc list) {
769         try {
770             if (list != null) {
771                 applyChangesToContext(ctx, (List JavaDoc)list);
772             }
773         } catch (Exception JavaDoc e) {
774             // ignore
775
}
776     }
777
778     /**
779      * Apply changes to the config context. Changes from the even are applied
780      * to the specified context.
781      * @deprecated <code>ConfigContext</code> is now refreshed using <code>
782      * ConfigChange</code> objects in the event.
783      */

784     private void applyChangesToContext(ConfigContext configContext,
785             List JavaDoc changeList) throws ConfigException {
786         Iterator JavaDoc iter = changeList.iterator();
787         ArrayList JavaDoc updates = new ArrayList JavaDoc();
788         while (iter.hasNext()) {
789             ConfigChange change = (ConfigChange)iter.next();
790             if (change instanceof ConfigUpdate) {
791                 updates.add(change);
792             } else {
793                 if((change instanceof ConfigAdd) || (change instanceof ConfigSet))
794                 {
795                     // here we are trying to avoid config elements duplication
796
// especially for applying of "dependent" changes
797
// this temporary solution should be removed after Toby will implement
798
// config-level validator rejecting such changes
799
try
800                     {
801                         if(ConfigBeansFactory.getConfigBeanByXPath(configContext, change.getXPath())!=null)
802                         {
803                             try
804                             {
805                                 // we delete existing bean to get fresh copy (it is esp. significant for deployedModules)
806
ConfigDelete delete_prior = ConfigChangeFactory.createConfigDelete(change.getXPath());
807                                 configContext.updateFromConfigChange(delete_prior);
808                             } catch(Exception JavaDoc e) {
809                             }
810                             //check one more time to be sure
811
if(ConfigBeansFactory.getConfigBeanByXPath(configContext, change.getXPath())==null)
812                                 configContext.updateFromConfigChange(change);
813                         }
814                         else
815                         {
816                             configContext.updateFromConfigChange(change);
817                         }
818                     }
819                     catch(Exception JavaDoc e) {
820                     }
821                    
822                 }
823                 else
824                     configContext.updateFromConfigChange(change);
825             }
826         }
827         iter = updates.iterator();
828         while (iter.hasNext()) {
829             ConfigUpdate update = (ConfigUpdate)iter.next();
830             configContext.updateFromConfigChange(update);
831         }
832     }
833
834     /**
835      * Destroy event handler. Invoked after event processing is completed
836      */

837     private void destroyEventHandler(AdminEvent event) {
838         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
839         if (AdminEventResult.SUCCESS.equals(result.getResultCode())) {
840             ServerContext ctx = AdminService.getAdminService().getContext();
841
842             if (ctx instanceof ServerContextImpl) {
843                 ConfigContext oldCtx = ctx.getConfigContext();
844                 ConfigContext newCtx = event.getConfigContext();
845                 
846                 ((ServerContextImpl) ctx).setConfigContext(newCtx);
847                 
848                 // replace the old config context with the new one from
849
// ConfigFactory cache
850
try {
851                     ConfigFactory.replaceConfigContext(oldCtx, newCtx);
852                 } catch(Exception JavaDoc e) {
853                     //ignore for now
854
logger.log(Level.WARNING, "event.replace_ctx_failed", e);
855                 }
856                 
857             if (!AdminService.getAdminService().isDas()) {
858                 try {
859                      AdminService.getAdminService().getContext().
860                         getConfigContext().flush();
861                 } catch (Exception JavaDoc e) {
862                     logger.log(Level.WARNING, "event.flush_failed");
863                 }
864             }
865
866             } else {
867                 logger.log(Level.SEVERE, "event.unknown_serverctx_type",
868                            ctx.getClass().getName());
869             }
870         }
871     }
872
873     /**
874      * Get listeners for specified event type
875      */

876     List JavaDoc getListeners(String JavaDoc type) {
877         return (List JavaDoc)listeners.get(type);
878     }
879
880     /**
881      * Handle application deployment event.
882      * @return number of listeners invoked
883      */

884     private int handleApplicationDeployEvent(AdminEvent event) {
885         ApplicationDeployEvent ade = (ApplicationDeployEvent)event;
886         List JavaDoc list = getListeners(ApplicationDeployEvent.eventType);
887         if (list != null && !list.isEmpty()) {
888             Iterator JavaDoc iter = list.iterator();
889             while (iter.hasNext()) {
890                 ApplicationDeployEventListener listener =
891                         (ApplicationDeployEventListener)iter.next();
892                 invokeApplicationDeployEventListener(listener, ade);
893             }
894         }
895         return ((list != null) ? list.size() : 0);
896     }
897
898     /**
899      * Invoke specified application deployment event listener
900      */

901     private void invokeApplicationDeployEventListener(
902             ApplicationDeployEventListener listener,
903             ApplicationDeployEvent event) {
904         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
905         try {
906             String JavaDoc action = event.getAction();
907             if (BaseDeployEvent.DEPLOY.equals(action)) {
908                 listener.applicationDeployed(event);
909             } else if (BaseDeployEvent.UNDEPLOY.equals(action)) {
910                 listener.applicationUndeployed(event);
911             } else if (BaseDeployEvent.REDEPLOY.equals(action)) {
912                 listener.applicationRedeployed(event);
913             } else if (BaseDeployEvent.ENABLE.equals(action)) {
914                 listener.applicationEnabled(event);
915             } else if (BaseDeployEvent.DISABLE.equals(action)) {
916                 listener.applicationDisabled(event);
917             }
918          
919             else if (BaseDeployEvent.ADD_REFERENCE.equals(action)) {
920                 listener.applicationReferenceAdded(event);
921             } else if (BaseDeployEvent.REMOVE_REFERENCE.equals(action)) {
922                 listener.applicationReferenceRemoved(event);
923             }
924         } catch (Throwable JavaDoc t) {
925             handleListenerError(event,t, result);
926         }
927     }
928
929     /**
930      * Handle module deployment event.
931      * @return number of listeners invoked
932      */

933     private int handleModuleDeployEvent(AdminEvent event) {
934         ModuleDeployEvent mde = (ModuleDeployEvent)event;
935         List JavaDoc list = getListeners(ModuleDeployEvent.eventType);
936         if (list != null && !list.isEmpty()) {
937             Iterator JavaDoc iter = list.iterator();
938             while (iter.hasNext()) {
939                 ModuleDeployEventListener listener =
940                         (ModuleDeployEventListener)iter.next();
941                 invokeModuleDeployEventListener(listener, mde);
942             }
943         }
944         return ((list != null) ? list.size() : 0);
945     }
946
947     private void invokeModuleDeployEventListener(
948             ModuleDeployEventListener listener,
949             ModuleDeployEvent event) {
950         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
951         try {
952             String JavaDoc action = event.getAction();
953             if (BaseDeployEvent.DEPLOY.equals(action)) {
954                 listener.moduleDeployed(event);
955             } else if (BaseDeployEvent.UNDEPLOY.equals(action)) {
956                 listener.moduleUndeployed(event);
957             } else if (BaseDeployEvent.REDEPLOY.equals(action)) {
958                 listener.moduleRedeployed(event);
959             } else if (BaseDeployEvent.ENABLE.equals(action)) {
960                 listener.moduleEnabled(event);
961             } else if (BaseDeployEvent.DISABLE.equals(action)) {
962                 listener.moduleDisabled(event);
963             }
964             
965             else if (BaseDeployEvent.ADD_REFERENCE.equals(action)) {
966                 listener.moduleReferenceAdded(event);
967             } else if (BaseDeployEvent.REMOVE_REFERENCE.equals(action)) {
968                 listener.moduleReferenceRemoved(event);
969             }
970         } catch (Throwable JavaDoc t) {
971             handleListenerError(event,t, result);
972         }
973     }
974
975     /**
976      * Handle resource deployment event.
977      * @return number of listeners invoked
978      */

979     private int handleResourceDeployEvent(AdminEvent event) {
980
981         ResourceDeployEvent rde = (ResourceDeployEvent)event;
982         List JavaDoc list = getListeners(ResourceDeployEvent.eventType);
983         if (list != null && !list.isEmpty()) {
984             Iterator JavaDoc iter = list.iterator();
985             while (iter.hasNext()) {
986                 ResourceDeployEventListener listener =
987                         (ResourceDeployEventListener)iter.next();
988                 invokeResourceDeployEventListener(listener, rde);
989             }
990         }
991         return ((list != null) ? list.size() : 0);
992     }
993
994     private void invokeResourceDeployEventListener(
995             ResourceDeployEventListener listener,
996             ResourceDeployEvent event) {
997         AdminEventResult result = AdminEventResult.getAdminEventResult(event);
998         try {
999             String JavaDoc action = event.getAction();
1000            if (BaseDeployEvent.DEPLOY.equals(action)) {
1001                listener.resourceDeployed(event);
1002            } else if (BaseDeployEvent.UNDEPLOY.equals(action)) {
1003                listener.resourceUndeployed(event);
1004            } else if (BaseDeployEvent.REDEPLOY.equals(action)) {
1005                listener.resourceRedeployed(event);
1006            } else if (BaseDeployEvent.ENABLE.equals(action)) {
1007                listener.resourceEnabled(event);
1008            } else if (BaseDeployEvent.DISABLE.equals(action)) {
1009                listener.resourceDisabled(event);
1010            } else if (BaseDeployEvent.ADD_REFERENCE.equals(action)) {
1011                listener.resourceReferenceAdded(event);
1012            } else if (BaseDeployEvent.REMOVE_REFERENCE.equals(action)) {
1013                listener.resourceReferenceRemoved(event);
1014            }
1015        } catch (Throwable JavaDoc t) {
1016            handleListenerError(event,t, result);
1017        }
1018    }
1019
1020    /**
1021     * Handle application deployment event.
1022     * @return number of listeners invoked
1023     */

1024    private int handleBaseDeployEvent(AdminEvent event) {
1025        BaseDeployEvent bde = (BaseDeployEvent)event;
1026        List JavaDoc list = getListeners(BaseDeployEvent.eventType);
1027        if (list != null && !list.isEmpty()) {
1028            Iterator JavaDoc iter = list.iterator();
1029            while (iter.hasNext()) {
1030                BaseDeployEventListener listener =
1031                        (BaseDeployEventListener)iter.next();
1032                invokeBaseDeployEventListener(listener, bde);
1033            }
1034        }
1035        return ((list != null) ? list.size() : 0);
1036    }
1037
1038    private void invokeBaseDeployEventListener(
1039            BaseDeployEventListener listener, BaseDeployEvent event) {
1040        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1041        try {
1042            String JavaDoc componentType = event.getJ2EEComponentType();
1043            String JavaDoc action = event.getAction();
1044            if (BaseDeployEvent.APPLICATION.equals(componentType)) {
1045                if (BaseDeployEvent.DEPLOY.equals(action)) {
1046                    listener.applicationDeployed(event);
1047                } else if (BaseDeployEvent.UNDEPLOY.equals(action)) {
1048                    listener.applicationUndeployed(event);
1049                } else if (BaseDeployEvent.REDEPLOY.equals(action)) {
1050                    listener.applicationRedeployed(event);
1051                } else if (BaseDeployEvent.ENABLE.equals(action)) {
1052                    listener.applicationEnabled(event);
1053                } else if (BaseDeployEvent.DISABLE.equals(action)) {
1054                    listener.applicationDisabled(event);
1055                }
1056                else if (BaseDeployEvent.ADD_REFERENCE.equals(action)) {
1057                    listener.applicationReferenceAdded(event);
1058                } else if (BaseDeployEvent.REMOVE_REFERENCE.equals(action)) {
1059                    listener.applicationReferenceRemoved(event);
1060                }
1061            } else if (BaseDeployEvent.MODULE.equals(componentType)) {
1062                if (BaseDeployEvent.DEPLOY.equals(action)) {
1063                    listener.moduleDeployed(event);
1064                } else if (BaseDeployEvent.UNDEPLOY.equals(action)) {
1065                    listener.moduleUndeployed(event);
1066                } else if (BaseDeployEvent.REDEPLOY.equals(action)) {
1067                    listener.moduleRedeployed(event);
1068                } else if (BaseDeployEvent.ENABLE.equals(action)) {
1069                    listener.moduleEnabled(event);
1070                } else if (BaseDeployEvent.DISABLE.equals(action)) {
1071                    listener.moduleDisabled(event);
1072                }
1073                
1074                else if (BaseDeployEvent.ADD_REFERENCE.equals(action)) {
1075                    listener.moduleReferenceAdded(event);
1076                } else if (BaseDeployEvent.REMOVE_REFERENCE.equals(action)) {
1077                    listener.moduleReferenceRemoved(event);
1078                }
1079            } else if (BaseDeployEvent.RESOURCE.equals(componentType)) {
1080                if (BaseDeployEvent.DEPLOY.equals(action)) {
1081                    listener.resourceDeployed(event);
1082                } else if (BaseDeployEvent.UNDEPLOY.equals(action)) {
1083                    listener.resourceUndeployed(event);
1084                } else if (BaseDeployEvent.REDEPLOY.equals(action)) {
1085                    listener.resourceRedeployed(event);
1086                } else if (BaseDeployEvent.ENABLE.equals(action)) {
1087                    listener.resourceEnabled(event);
1088                } else if (BaseDeployEvent.DISABLE.equals(action)) {
1089                    listener.resourceDisabled(event);
1090                }
1091                
1092                else if (BaseDeployEvent.ADD_REFERENCE.equals(action)) {
1093                    listener.resourceReferenceAdded(event);
1094                } else if (BaseDeployEvent.REMOVE_REFERENCE.equals(action)) {
1095                    listener.resourceReferenceRemoved(event);
1096                }
1097            }
1098        } catch (Throwable JavaDoc t) {
1099            handleListenerError(event,t, result);
1100        }
1101    }
1102
1103    /**
1104     * Handle config change event.
1105     * @return number of listeners invoked
1106     */

1107    private int handleConfigChangeEvent(AdminEvent event) {
1108        int listenersInvoked = 0;
1109        ConfigChangeEvent cce = (ConfigChangeEvent)event;
1110        List JavaDoc list = getListeners(ConfigChangeEvent.eventType);
1111        if (list != null && !list.isEmpty()) {
1112            Iterator JavaDoc iter = list.iterator();
1113            while (iter.hasNext()) {
1114                ConfigChangeEventListener listener =
1115                        (ConfigChangeEventListener)iter.next();
1116                ConfigChangeCategory category = (ConfigChangeCategory)
1117                        configCategoryList.get(listener);
1118                boolean match = true;
1119                if (category != null) {
1120                    match = cce.matchXPathToPattern(
1121                            category.getConfigXPathPattern());
1122                }
1123                if (match) {
1124                    invokeConfigChangeEventListener(listener, cce);
1125                    ++listenersInvoked;
1126                }
1127            }
1128        }
1129        if (!cce.isAllXPathMatched()) {
1130            AdminEventResult result = AdminEventResult.getAdminEventResult(cce);
1131            //result.setResultCode(AdminEventResult.RESTART_NEEDED);
1132
}
1133        return listenersInvoked;
1134    }
1135
1136    private void invokeConfigChangeEventListener(
1137            ConfigChangeEventListener listener, ConfigChangeEvent event) {
1138        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1139        try {
1140            listener.configChanged(event);
1141        } catch (Throwable JavaDoc t) {
1142            handleListenerError(event,t, result);
1143        }
1144    }
1145
1146    /**
1147     * Handle monitoring event
1148     * @return number of listeners invoked
1149     */

1150    private int handleMonitoringEvent(AdminEvent event) {
1151        MonitoringEvent me = (MonitoringEvent)event;
1152        List JavaDoc list = getListeners(MonitoringEvent.eventType);
1153        if (list != null && !list.isEmpty()) {
1154            Iterator JavaDoc iter = list.iterator();
1155            while (iter.hasNext()) {
1156                MonitoringEventListener listener =
1157                        (MonitoringEventListener)iter.next();
1158                invokeMonitoringEventListener(listener, me);
1159            }
1160        }
1161        return ((list != null) ? list.size() : 0);
1162    }
1163
1164    private void invokeMonitoringEventListener(
1165            MonitoringEventListener listener,
1166            MonitoringEvent event) {
1167        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1168        try {
1169            String JavaDoc action = event.getActionCode();
1170            if (MonitoringEvent.START_MONITORING.equals(action)) {
1171                listener.startMonitoring(event);
1172            } else if (MonitoringEvent.STOP_MONITORING.equals(action)) {
1173                listener.stopMonitoring(event);
1174            } else if (MonitoringEvent.GET_MONITOR_DATA.equals(action)) {
1175                listener.getMonitoringData(event);
1176            } else if (MonitoringEvent.LIST_MONITORABLE.equals(action)) {
1177                listener.listMonitorable(event);
1178            } else if (MonitoringEvent.SET_MONITOR_DATA.equals(action)) {
1179                listener.setMonitoringData(event);
1180            }
1181        } catch (Throwable JavaDoc t) {
1182            handleListenerError(event,t, result);
1183        }
1184    }
1185
1186    //********************************************************
1187
/**
1188     * Handle ElementChange event
1189     * @return number of listeners invoked
1190     */

1191    private int handleElementChangeEvent(AdminEvent event) {
1192        ElementChangeEvent me = (ElementChangeEvent)event;
1193        List JavaDoc list = getListeners(ElementChangeEvent.eventType);
1194        if (list != null && !list.isEmpty()) {
1195            Iterator JavaDoc iter = list.iterator();
1196            while (iter.hasNext()) {
1197                ElementChangeEventListener listener =
1198                        (ElementChangeEventListener)iter.next();
1199                invokeElementChangeEventListener(listener, me);
1200            }
1201        }
1202        return ((list != null) ? list.size() : 0);
1203    }
1204
1205    private void invokeElementChangeEventListener(
1206            ElementChangeEventListener listener,
1207            ElementChangeEvent event) {
1208        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1209        try {
1210            listener.processEvent(event);
1211        } catch (Throwable JavaDoc t) {
1212            handleListenerError(event,t, result);
1213        }
1214    }
1215
1216
1217    //********************************************************
1218
/**
1219     * Handle UserMgmt event
1220     * @return number of listeners invoked
1221     */

1222    private int handleUserMgmtEvent(AdminEvent event) {
1223        UserMgmtEvent me = (UserMgmtEvent)event;
1224        List JavaDoc list = getListeners(UserMgmtEvent.eventType);
1225        if (list != null && !list.isEmpty()) {
1226            Iterator JavaDoc iter = list.iterator();
1227            while (iter.hasNext()) {
1228                UserMgmtEventListener listener =
1229                        (UserMgmtEventListener)iter.next();
1230                invokeUserMgmtEventListener(listener, me);
1231            }
1232        }
1233        return ((list != null) ? list.size() : 0);
1234    }
1235
1236    private void invokeUserMgmtEventListener(
1237            UserMgmtEventListener listener,
1238            UserMgmtEvent event) {
1239        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1240        try {
1241            int action = event.getActionType();
1242            if(action==event.ACTION_USERADD){
1243                listener.userAdded(event);
1244            } else if(action==event.ACTION_USERUPDATE) {
1245                listener.userUpdated(event);
1246            } else if(action==event.ACTION_USERREMOVE) {
1247                listener.userRemoved(event);
1248            }
1249        } catch (Throwable JavaDoc t) {
1250            handleListenerError(event,t, result);
1251        }
1252    }
1253    //********************************************************
1254
/**
1255     * Handle EjbTimer event
1256     * @return number of listeners invoked
1257     */

1258    private int handleEjbTimerEvent(AdminEvent event) {
1259        EjbTimerEvent me = (EjbTimerEvent)event;
1260        List JavaDoc list = getListeners(EjbTimerEvent.eventType);
1261        if (list != null && !list.isEmpty()) {
1262            Iterator JavaDoc iter = list.iterator();
1263            while (iter.hasNext()) {
1264                EjbTimerEventListener listener =
1265                        (EjbTimerEventListener)iter.next();
1266                invokeEjbTimerEventListener(listener, me);
1267            }
1268        }
1269        return ((list != null) ? list.size() : 0);
1270    }
1271
1272    private void invokeEjbTimerEventListener(
1273            EjbTimerEventListener listener,
1274            EjbTimerEvent event) {
1275        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1276        try {
1277            int action = event.getActionType();
1278            if(action==event.ACTION_MIGRATETIMER){
1279                int iCount = listener.migrateTimer(event, event.getFromServerName());
1280                result.addAttribute(event.getEffectiveDestination(),
1281                    event.EJB_TIMER_CALL_RESULT_ATTRNAME, new Integer JavaDoc(iCount));
1282            } else if(action==event.ACTION_LISTTIMERS) {
1283                String JavaDoc[] strs = listener.listTimers(event, event.getServerNames());
1284                result.addAttribute(event.getEffectiveDestination(),
1285                    event.EJB_TIMER_CALL_RESULT_ATTRNAME, strs);
1286            }
1287        } catch (Throwable JavaDoc t) {
1288            handleListenerError(event,t, result);
1289        }
1290    }
1291    //********************************************************
1292
/**
1293     * Handle AuthRealm event
1294     * @return number of listeners invoked
1295     */

1296    private int handleAuthRealmEvent(AdminEvent event) {
1297        AuthRealmEvent me = (AuthRealmEvent)event;
1298        List JavaDoc list = getListeners(AuthRealmEvent.eventType);
1299        if (list != null && !list.isEmpty()) {
1300            Iterator JavaDoc iter = list.iterator();
1301            while (iter.hasNext()) {
1302                AuthRealmEventListener listener =
1303                        (AuthRealmEventListener)iter.next();
1304                invokeAuthRealmEventListener(listener, me);
1305            }
1306        }
1307        return ((list != null) ? list.size() : 0);
1308    }
1309
1310    private void invokeAuthRealmEventListener(
1311            AuthRealmEventListener listener,
1312            AuthRealmEvent event) {
1313        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1314        try {
1315            int action = event.getActionType();
1316            if(action==event.ACTION_CREATE){
1317                listener.authRealmCreated(event);
1318            } else if(action==event.ACTION_UPDATE) {
1319                listener.authRealmUpdated(event);
1320            } else if(action==event.ACTION_DELETE) {
1321                listener.authRealmDeleted(event);
1322            }
1323        } catch (Throwable JavaDoc t) {
1324            handleListenerError(event,t, result);
1325        }
1326    }
1327    //********************************************************
1328
/**
1329     * Handle AuditModule event
1330     * @return number of listeners invoked
1331     */

1332    private int handleAuditModuleEvent(AdminEvent event) {
1333        AuditModuleEvent me = (AuditModuleEvent)event;
1334        List JavaDoc list = getListeners(AuditModuleEvent.eventType);
1335        if (list != null && !list.isEmpty()) {
1336            Iterator JavaDoc iter = list.iterator();
1337            while (iter.hasNext()) {
1338                AuditModuleEventListener listener =
1339                        (AuditModuleEventListener)iter.next();
1340                invokeAuditModuleEventListener(listener, me);
1341            }
1342        }
1343        return ((list != null) ? list.size() : 0);
1344    }
1345
1346    private void invokeAuditModuleEventListener(
1347            AuditModuleEventListener listener,
1348            AuditModuleEvent event) {
1349        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1350        try {
1351            int action = event.getActionType();
1352            if(action==event.ACTION_CREATE){
1353                listener.auditModuleCreated(event);
1354            } else if(action==event.ACTION_UPDATE) {
1355                listener.auditModuleUpdated(event);
1356            } else if(action==event.ACTION_DELETE) {
1357                listener.auditModuleDeleted(event);
1358            }
1359        } catch (Throwable JavaDoc t) {
1360            handleListenerError(event,t, result);
1361        }
1362    }
1363    //********************************************************
1364
/**
1365     * Handle SecurityService event
1366     * @return number of listeners invoked
1367     */

1368    private int handleSecurityServiceEvent(AdminEvent event) {
1369        SecurityServiceEvent me = (SecurityServiceEvent)event;
1370        List JavaDoc list = getListeners(SecurityServiceEvent.eventType);
1371        if (list != null && !list.isEmpty()) {
1372            Iterator JavaDoc iter = list.iterator();
1373            while (iter.hasNext()) {
1374                SecurityServiceEventListener listener =
1375                        (SecurityServiceEventListener)iter.next();
1376                invokeSecurityServiceEventListener(listener, me);
1377            }
1378        }
1379        return ((list != null) ? list.size() : 0);
1380    }
1381
1382    private void invokeSecurityServiceEventListener(
1383            SecurityServiceEventListener listener,
1384            SecurityServiceEvent event) {
1385        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1386        try {
1387            int action = event.getActionType();
1388            if(action==event.ACTION_CREATE){
1389                listener.securityServiceCreated(event);
1390            } else if(action==event.ACTION_UPDATE) {
1391                listener.securityServiceUpdated(event);
1392            } else if(action==event.ACTION_DELETE) {
1393                listener.securityServiceDeleted(event);
1394            }
1395        } catch (Throwable JavaDoc t) {
1396            handleListenerError(event,t, result);
1397        }
1398    }
1399    //********************************************************
1400

1401
1402    
1403    
1404    /**
1405     * Handle monitoring level change event
1406     * @return number of listeners invoked
1407     */

1408    private int handleLogLevelChangeEvent(AdminEvent event) {
1409        LogLevelChangeEvent llce = (LogLevelChangeEvent)event;
1410        List JavaDoc list = getListeners(LogLevelChangeEvent.eventType);
1411        if (list != null && !list.isEmpty()) {
1412            Iterator JavaDoc iter = list.iterator();
1413            while (iter.hasNext()) {
1414                LogLevelChangeEventListener listener =
1415                        (LogLevelChangeEventListener)iter.next();
1416                invokeLogLevelChangeEventListener(listener, llce);
1417            }
1418        }
1419        return ((list != null) ? list.size() : 0);
1420    }
1421
1422    private void invokeLogLevelChangeEventListener(
1423            LogLevelChangeEventListener listener,
1424            LogLevelChangeEvent event) {
1425        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1426        try {
1427            listener.logLevelChanged(event);
1428        } catch (Throwable JavaDoc t) {
1429            handleListenerError(event,t, result);
1430        }
1431    }
1432
1433    /**
1434     * Handle monitoring level change event
1435     * @return number of listeners invoked
1436     */

1437    private int handleMonitoringLevelChangeEvent(AdminEvent event) {
1438        MonitoringLevelChangeEvent mlce = (MonitoringLevelChangeEvent)event;
1439        List JavaDoc list = getListeners(MonitoringLevelChangeEvent.eventType);
1440        if (list != null && !list.isEmpty()) {
1441            Iterator JavaDoc iter = list.iterator();
1442            while (iter.hasNext()) {
1443                MonitoringLevelChangeEventListener listener =
1444                        (MonitoringLevelChangeEventListener)iter.next();
1445                invokeMonitoringLevelChangeEventListener(listener, mlce);
1446            }
1447        }
1448        return ((list != null) ? list.size() : 0);
1449    }
1450
1451    private void invokeMonitoringLevelChangeEventListener(
1452            MonitoringLevelChangeEventListener listener,
1453            MonitoringLevelChangeEvent event) {
1454        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1455        try {
1456            listener.monitoringLevelChanged(event);
1457        } catch (Throwable JavaDoc t) {
1458            handleListenerError(event,t, result);
1459        }
1460    }
1461
1462    private int handleShutdownEvent(AdminEvent event) {
1463    ShutdownEvent se = (ShutdownEvent)event;
1464        List JavaDoc list = getListeners(ShutdownEvent.eventType);
1465        if (list != null && !list.isEmpty()) {
1466            Iterator JavaDoc iter = list.iterator();
1467            while (iter.hasNext()) {
1468                ShutdownEventListener listener =
1469                        (ShutdownEventListener)iter.next();
1470                invokeShutdownEventListener(listener, se);
1471            }
1472        }
1473        return ((list != null) ? list.size() : 0);
1474    }
1475
1476    private void invokeShutdownEventListener(
1477    ShutdownEventListener listener,
1478        ShutdownEvent event) {
1479        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1480        try {
1481            listener.startShutdown(event);
1482        } catch (Throwable JavaDoc t) {
1483            handleListenerError(event,t, result);
1484        }
1485    }
1486
1487    /**
1488     * Utility method to determine event type from an event listener.
1489     */

1490    private static String JavaDoc getEventTypeFromListener(AdminEventListener listener) {
1491        Class JavaDoc[] interfaces = listener.getClass().getInterfaces();
1492        String JavaDoc type = null;
1493        for (int i = 0; i < interfaces.length; i++) {
1494            String JavaDoc className = interfaces[i].getName();
1495            if (className.startsWith(ApplicationDeployEvent.eventType)) {
1496                type = ApplicationDeployEvent.eventType;
1497            } else if (className.startsWith(ModuleDeployEvent.eventType)) {
1498        //HERCULES: fix
1499
type = ModuleDeployEvent.eventType;
1500            } else if (className.startsWith(ResourceDeployEvent.eventType)) {
1501                type = ResourceDeployEvent.eventType;
1502            } else if (className.startsWith(BaseDeployEvent.eventType)) {
1503                type = BaseDeployEvent.eventType;
1504            } else if (className.startsWith(ConfigChangeEvent.eventType)) {
1505                type = ConfigChangeEvent.eventType;
1506            } else if (className.startsWith(MonitoringEvent.eventType)) {
1507                type = MonitoringEvent.eventType;
1508            } else if (className.startsWith(ShutdownEvent.eventType)) {
1509                type = ShutdownEvent.eventType;
1510            } else if (className.startsWith(AdminEvent.eventType)) {
1511                type = AdminEvent.eventType;
1512            }
1513            if (type != null) {
1514                break;
1515            }
1516        }
1517        return type;
1518    }
1519
1520    /**
1521     * Refresh global config context. This is invoked after event processing is
1522     * successfully completed.
1523     */

1524    private void refreshConfigContext() {
1525        try {
1526            AdminService.getAdminService().getContext().getConfigContext().refresh(true);
1527        } catch (ConfigException ce) {
1528            warn("Unable to refresh ConfigContext upon receiving ConfigChangeEvent.");
1529            debug(ce);
1530        }
1531    }
1532
1533    /**
1534     * Processing for the case when no listeners are available for a event.
1535     * When there are no listeners, assume that change can not be handled
1536     * without restart and set the status appropriately. This may not be
1537     * right thing to do because reconfig command executed directly from admin
1538     * server may have handled all the changes successfully even when there
1539     * are no listeners.
1540     */

1541    private void handleNoListeners(AdminEvent event) {
1542        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1543        result.setResultCode(AdminEventResult.RESTART_NEEDED);
1544    }
1545
1546    /**
1547     * Handle error in event listeners.
1548     * @param t throwable thrown by event listeners
1549     * @param result result for the event that was being processed
1550     */

1551    void handleListenerError(AdminEvent event,
1552        Throwable JavaDoc t, AdminEventResult result) {
1553        t.printStackTrace();
1554        handleError(event, t, result, HANDLER_ERROR);
1555    }
1556
1557    /**
1558     * Handle error by setting appropriate result code.
1559     * @param t the exception (throwable) that was thrown. This should be
1560     * an object of type <code>AdminEventListenerException</code> or a
1561     * subclass of <code>java.lang.RuntimeException</code> or <code>
1562     * java.lang.Error</code>.
1563     * @param result the result for the event
1564     * @param msg warning message prefix
1565     */

1566     private void handleError(AdminEvent event, Throwable JavaDoc t,
1567     AdminEventResult result, String JavaDoc msg) {
1568        logger.log(Level.WARNING, msg, t.getMessage());
1569        String JavaDoc stackTrace = getStackTraceFromThrowable(t);
1570        debug(stackTrace);
1571        if (AdminEventResult.SUCCESS.equals(result.getResultCode())) {
1572            if (t instanceof AdminEventListenerException) {
1573                result.setResultCode(AdminEventResult.LISTENER_ERROR);
1574            } else if (t instanceof java.lang.RuntimeException JavaDoc) {
1575                result.setResultCode(AdminEventResult.RUNTIME_EXCEPTION);
1576            } else if (t instanceof java.lang.Error JavaDoc) {
1577                result.setResultCode(AdminEventResult.RUNTIME_ERROR);
1578            } else {
1579                // Treat this similar to RUNTIME_ERROR
1580
result.setResultCode(AdminEventResult.RUNTIME_ERROR);
1581            }
1582        }
1583        result.addException(event.getEffectiveDestination(),t);
1584
1585    }
1586
1587    private static String JavaDoc getStackTraceFromThrowable(Throwable JavaDoc t) {
1588        StringWriter JavaDoc sw = new StringWriter JavaDoc();
1589        PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
1590        t.printStackTrace(pw);
1591        return (sw.toString());
1592    }
1593
1594    static void warn(String JavaDoc s) {
1595        logger.warning(s);
1596    }
1597
1598    static void debug(String JavaDoc s) {
1599        logger.fine(s);
1600    }
1601
1602    static void debug(Throwable JavaDoc t) {
1603        logger.log(Level.FINE, t.getMessage(), t);
1604    }
1605
1606    public void sendNotification(AdminEvent event) {
1607
1608        AdminEventManager am = AdminEventManager.getAdminEventManager();
1609        MBeanLocator mbl = am.getMBeanLocator();
1610        Set objs =(Set) mbl.locate(event.getEventId());
1611
1612        AdminEventResult result = AdminEventResult.getAdminEventResult(event);
1613
1614        if (objs == null || objs.size() == 0) {
1615
1616            // FIXME: uncomment this when we migrate the
1617
// legacy listener implementation
1618
//handleNoListeners(event);
1619

1620            return;
1621        }
1622
1623        Iterator JavaDoc it = objs.iterator();
1624        while ( it.hasNext() ) {
1625             try {
1626                ObjectInstance JavaDoc oi = (ObjectInstance JavaDoc) it.next();
1627                MBeanServerFactory.getMBeanServer().invoke( oi.getObjectName(),
1628                   SEND_NOTIFICATION_METHOD,
1629                   new Object JavaDoc [] { event },
1630                   new String JavaDoc [] { SEND_NOTIFICATION_METHOD_SIG});
1631             } catch ( Throwable JavaDoc t) {
1632                 handleListenerError(event,t, result);
1633             }
1634         }
1635    }
1636
1637    // ---- INSTANCE VARIABLES - PRIVATE -------------------------------------
1638
static final String JavaDoc MULTICAST_NOT_SUPPORTED =
1639                            "event.multicast_not_supported";
1640    static final String JavaDoc HANDLER_INIT_ERROR = "event.handler_init_error";
1641    static final String JavaDoc HANDLER_ERROR = "event.handler_error";
1642    static final String JavaDoc SEND_NOTIFICATION_METHOD = "sendNotification";
1643    static final String JavaDoc SEND_NOTIFICATION_METHOD_SIG =
1644                            "javax.management.Notification";
1645
1646}
1647
Popular Tags