KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > alert > AlertConfigurator


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.alert;
24
25 import javax.management.NotificationListener JavaDoc;
26 import javax.management.NotificationFilter JavaDoc;
27 import javax.management.MBeanServer JavaDoc;
28 import javax.management.ObjectName JavaDoc;
29
30 import java.lang.reflect.Method JavaDoc;
31 import java.lang.reflect.Field JavaDoc;
32 import java.security.AccessController JavaDoc;
33 import java.security.PrivilegedAction JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.ArrayList JavaDoc;
36 import java.util.StringTokenizer JavaDoc;
37 import java.util.logging.ErrorManager JavaDoc;
38 import java.util.logging.Logger JavaDoc;
39 import java.util.logging.Level JavaDoc;
40
41 import com.sun.enterprise.admin.server.core.AdminService;
42 import com.sun.enterprise.server.ServerContext;
43 import com.sun.enterprise.server.ApplicationServer;
44 import com.sun.enterprise.config.serverbeans.ElementProperty;
45 import com.sun.enterprise.config.serverbeans.AlertService;
46 import com.sun.enterprise.config.serverbeans.AlertSubscription;
47 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
48 import com.sun.enterprise.config.serverbeans.ListenerConfig;
49 import com.sun.enterprise.config.serverbeans.FilterConfig;
50
51 import com.sun.enterprise.server.logging.LogMBean;
52 import com.sun.appserv.management.alert.LogDomains;
53
54
55 /**
56  * AlertConfigurator reads the domain.xml entries and configures the
57  * NotificationListeners and NotificationFilters and keeps it ready to
58  * subscribe (add) to the Target MBeans(Monitors) to recieve alerts.
59  *
60  * @AUTHOR: Hemanth Puttaswamy
61  */

62 public class AlertConfigurator {
63
64     // A standard name for MBeanServerDelegate
65
private static final String JavaDoc MBEAN_SERVER_DELEGATE_OBJECT_NAME =
66         "JMImplementation:type=MBeanServerDelegate";
67
68     // A standard name for MBeanServerDelegate
69
private static final String JavaDoc DEFAULT_FILTER_CLASS_NAME =
70         "com.sun.appserv.management.alert.MailFilter";
71
72     // A standard name for MBeanServerDelegate
73
private static final String JavaDoc LOG_MBEAN_NAME = "LogMBean";
74
75     private static final AlertConfigurator instance = new AlertConfigurator( );
76
77     /**
78      * A Singleton Accessor method.
79      */

80     public static AlertConfigurator getAlertConfigurator( ) {
81         return instance;
82     }
83    
84     private AlertConfigurator( ) { }
85
86     /**
87      * Get AlertService config from domain.xml
88      */

89     private AlertService getAlertService( ) {
90         try {
91             ServerContext sc = ApplicationServer.getServerContext();
92             if( sc == null ) {
93                 return null;
94             }
95             return ServerBeansFactory.getConfigBean(
96                 sc.getConfigContext()).getAlertService( );
97         } catch( Exception JavaDoc e ) {
98             new ErrorManager JavaDoc().error( "Error In getAlertService ", e,
99                 ErrorManager.GENERIC_FAILURE );
100         }
101         return null;
102     }
103
104     /**
105      * Configure will be called only once to read the domain.xml entries
106      * and configure the Notification Listener and Filter. It will also
107      * create a list of AlertSubscription objects and creates
108      * MBeanServerRegistrationEventListener to listen to RegisterMBean events
109      * and add the Notification Listener if required.
110      */

111     public void configure( ) {
112         Logger JavaDoc logger = LogDomains.getAlertLogger( );
113         if( logger.isLoggable( Level.FINE ) ) {
114             logger.log( Level.FINE, "AlertConfigurator.configure called.." );
115         }
116         AlertService alertService = getAlertService( );
117         if( alertService != null ) {
118             int count = alertService.sizeAlertSubscription( );
119             if( count == 0 ) return;
120
121             List JavaDoc alertSubscriptionList = new ArrayList JavaDoc( );
122             for( int i = 0; i < count; i++ ) {
123                 AlertSubscription subscription =
124                     alertService.getAlertSubscription( i );
125                 NotificationListener JavaDoc listener = configureNotificationListener(
126                     subscription.getListenerConfig( ) );
127                 NotificationFilter JavaDoc filter = configureNotificationFilter(
128                     subscription.getFilterConfig( ) );
129                 alertSubscriptionList.add( new AlertSubscriptionInfo(
130                     subscription.getListenerConfig().getSubscribeListenerWith( ),
131                         listener, filter ));
132                 String JavaDoc monitorNames = subscription.getListenerConfig(
133                     ).getSubscribeListenerWith( );
134                 if( logger.isLoggable( Level.FINE ) ) {
135                     logger.log( Level.FINE,
136                         "AlertConfigurator.configure monitorNames.." +
137                              monitorNames );
138                 }
139                 StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc( monitorNames,
140                     "," );
141                 // If we are interested in listening to LogMBean event
142
// event as well. Subscribe it with an explicit call
143
// as LogMBean would've been registered already by now and
144
// will never recieve the LogMBean registered notification.
145
while( tokenizer.hasMoreTokens( ) ) {
146                     String JavaDoc token = tokenizer.nextToken().trim();
147                     if( token.equals( LOG_MBEAN_NAME ) ) {
148                         LogMBean.getInstance( ).addNotificationListener(
149                             listener, filter, null );
150                     }
151                 }
152             }
153             // Now, we have read all the domain.xml alert subscriptions.
154
// We can register a Notification Listener to listen to
155
// MBean registered event and then we can introspect the name
156
// to see if it matches to add the Listeners capable of
157
// emitting alerts.
158
MBeanRegistrationEventListener registrationListener =
159                  new MBeanRegistrationEventListener( alertSubscriptionList );
160             readyForMBeanRegistrationEvent( registrationListener );
161         }
162     }
163
164     /**
165      * Initializes the NotificationListener based on ListenerConfig in
166      * domain.xml .
167      */

168     private NotificationListener JavaDoc configureNotificationListener(
169         ListenerConfig listenerConfig )
170     {
171         Logger JavaDoc alertLogger = LogDomains.getAlertLogger( );
172         if( alertLogger.isLoggable( Level.FINE ) ) {
173             alertLogger.log( Level.FINE,
174              "ConfigureNotificationListener called with className ..." +
175              listenerConfig.getListenerClassName( ) );
176         }
177         NotificationListener JavaDoc listener = null;
178         try {
179             listener = (NotificationListener JavaDoc) instantiateAndConfigure(
180                 listenerConfig.getListenerClassName( ),
181                     listenerConfig.getElementProperty( ) );
182         } catch( Exception JavaDoc e ) {
183             new ErrorManager JavaDoc().error(
184                 "Error In Notification Listener Config ", e,
185                           ErrorManager.GENERIC_FAILURE );
186         }
187         return listener;
188     }
189
190     /**
191      * Initializes the NotificationFilter based on FilterConfig in domain.xml .
192      */

193     private NotificationFilter JavaDoc configureNotificationFilter(
194         FilterConfig filterConfig )
195     {
196         String JavaDoc filterClassName = DEFAULT_FILTER_CLASS_NAME;
197         ElementProperty[] properties = null;
198         if( filterConfig != null ) {
199             filterClassName = filterConfig.getFilterClassName();
200             properties = filterConfig.getElementProperty();
201         }
202         NotificationFilter JavaDoc filter = null;
203         try {
204             filter = (NotificationFilter JavaDoc) instantiateAndConfigure(
205                 filterClassName, properties );
206         } catch( Exception JavaDoc e ) {
207             new ErrorManager JavaDoc().error(
208                 "Error In Notification Filter Config ", e,
209                           ErrorManager.GENERIC_FAILURE );
210         }
211         return filter;
212     }
213
214
215     /**
216      * Utility method to set properties to the instantiated Object.
217      */

218     private void setProperties( Object JavaDoc o, ElementProperty[] properties ) {
219         if( properties == null ) return;
220         Method JavaDoc[] methods = null;
221         try {
222             methods = getDeclaredMethods( o.getClass( ) );
223             for( int i = 0; i < properties.length; i++ ) {
224                 ElementProperty property = properties[i];
225                 String JavaDoc propertyName = property.getName( ).toLowerCase( );
226                 String JavaDoc propertyValue = property.getValue( );
227                 for( int j = 0; j < methods.length; j++ ) {
228                     String JavaDoc methodName = methods[j].getName().toLowerCase();
229                     if ( ( methodName.startsWith( "set" ) )
230                        && ( methodName.endsWith( propertyName ) ) )
231                     {
232                         Class JavaDoc[] parameterTypes = methods[j].getParameterTypes( );
233                         if( parameterTypes.length != 1 ) {
234                             new ErrorManager JavaDoc().error(
235                                 "Only one Parameter is allowed for the setter " +
236                                 " Method: " + methodName +
237                                 " has invalid signature", new Exception JavaDoc(),
238                                 ErrorManager.GENERIC_FAILURE );
239                         }
240
241                         String JavaDoc parameterType = parameterTypes[0].getName();
242                         Object JavaDoc[] parameters = new Object JavaDoc[1];
243
244                         if( parameterType.equals( "java.lang.String") ) {
245                             parameters[0] = propertyValue;
246                         } else if( parameterType.equals( "byte" ) ) {
247                             parameters[0] =
248                                 new Byte JavaDoc( propertyValue.getBytes()[0]);
249                         } else if( parameterType.equals( "int" ) ) {
250                             parameters[0] = new Integer JavaDoc(propertyValue);
251                         } else if( parameterType.equals( "float" ) ) {
252                             parameters[0] = new Float JavaDoc(propertyValue);
253                         } else if( parameterType.equals( "double") ) {
254                             parameters[0] = new Double JavaDoc(propertyValue);
255                         } else if( parameterType.equals( "char" ) ) {
256                             parameters[0] =
257                                 new Character JavaDoc(propertyValue.charAt(0));
258                         } else if( parameterType.equals("boolean") ) {
259                             parameters[0] = new Boolean JavaDoc(propertyValue);
260                         } else if( parameterType.equals("long") ) {
261                             parameters[0] = new Long JavaDoc(propertyValue);
262                         } else if( parameterType.equals("short") ) {
263                             parameters[0] = new Short JavaDoc(propertyValue);
264                         } else {
265                             new ErrorManager JavaDoc().error(
266                                 "Only the basic primitive types can be set " +
267                                 "as properties to NotificationListener and " +
268                                 " NotificationFilter ", new Exception JavaDoc(),
269                                 ErrorManager.GENERIC_FAILURE );
270                             continue;
271                         }
272                         methods[j].invoke( o, parameters );
273                     }
274                 }
275             }
276         } catch( Exception JavaDoc e ) {
277             new ErrorManager JavaDoc().error(
278                 "Error While Setting properties to Notification Listener or " +
279                 " Filter ", e, ErrorManager.GENERIC_FAILURE );
280         }
281     }
282
283
284     /**
285      * A Utility method to instantiate a class and set the properties.
286      */

287     private Object JavaDoc instantiateAndConfigure( String JavaDoc className,
288         ElementProperty[] properties )
289     {
290          Logger JavaDoc alertLogger = LogDomains.getAlertLogger();
291          if( alertLogger.isLoggable( Level.FINE ) ) {
292              alertLogger.log( Level.FINE,
293                  "instantiateAndConfigure called with className.." +
294                  className );
295          }
296          Object JavaDoc o = getInstance( className );
297          if( ( o != null )
298            &&( properties != null ) )
299          {
300              if( alertLogger.isLoggable( Level.FINE ) ) {
301                  alertLogger.log( Level.FINE,
302                      "instantiateAndConfigure setting Properties.." );
303              }
304              setProperties( o, properties );
305          }
306          return o;
307     }
308
309     /**
310      * A Utility method to get an instance of the class.
311      * _REVISIT_: Check to see if there is a utility method to do this.
312      * If yes, this method can be taken out.
313      */

314     private Object JavaDoc getInstance( final String JavaDoc className ) {
315         if( className == null ) return null;
316         return AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
317                 public Object JavaDoc run() {
318                     try {
319                         ClassLoader JavaDoc cl =
320                             Thread.currentThread().getContextClassLoader();
321                         if (cl == null)
322                             cl = ClassLoader.getSystemClassLoader();
323                         return Class.forName( className, true, cl).newInstance(); } catch( Exception JavaDoc e ) {
324                         new ErrorManager JavaDoc().error(
325                             "Error In Instantiating Class " + className, e,
326                             ErrorManager.GENERIC_FAILURE );
327                     }
328                     return null;
329                }
330            }
331        );
332     }
333
334     /**
335      * Utility method to get the declared fields.
336      */

337     private final Method JavaDoc[] getDeclaredMethods(final Class JavaDoc clz) {
338         return (Method JavaDoc[]) AccessController.doPrivileged(new PrivilegedAction JavaDoc() { public Object JavaDoc run() {
339                 return clz.getDeclaredMethods();
340             }
341         });
342     }
343
344
345     /**
346      * Registers the MBeanRegistrationEventListener with MBean Server Delegate.
347      */

348     private void readyForMBeanRegistrationEvent(
349         NotificationListener JavaDoc registrationListener )
350     {
351         try {
352             MBeanServer JavaDoc mbeanServer =
353                 AdminService.getAdminService().getAdminContext(
354                     ).getMBeanServer();
355             mbeanServer.addNotificationListener(
356                 new ObjectName JavaDoc( MBEAN_SERVER_DELEGATE_OBJECT_NAME ),
357                 registrationListener, (NotificationFilter JavaDoc) null,(Object JavaDoc) null );
358         } catch( Exception JavaDoc e ) {
359             new ErrorManager JavaDoc().error(
360                 "Error In registerning MBeanServerNotificationListener ", e,
361                 ErrorManager.GENERIC_FAILURE );
362         }
363     }
364 }
365
Popular Tags