KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > management > BaseStandardMBean


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.jbi.management;
18
19 import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService;
20
21 import org.apache.commons.beanutils.MethodUtils;
22 import org.apache.commons.beanutils.PropertyUtilsBean;
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25
26 import javax.management.Attribute JavaDoc;
27 import javax.management.AttributeChangeNotification JavaDoc;
28 import javax.management.AttributeChangeNotificationFilter JavaDoc;
29 import javax.management.AttributeList JavaDoc;
30 import javax.management.AttributeNotFoundException JavaDoc;
31 import javax.management.Descriptor JavaDoc;
32 import javax.management.InvalidAttributeValueException JavaDoc;
33 import javax.management.ListenerNotFoundException JavaDoc;
34 import javax.management.MBeanAttributeInfo JavaDoc;
35 import javax.management.MBeanException JavaDoc;
36 import javax.management.MBeanInfo JavaDoc;
37 import javax.management.MBeanNotificationInfo JavaDoc;
38 import javax.management.MBeanOperationInfo JavaDoc;
39 import javax.management.MBeanRegistration JavaDoc;
40 import javax.management.MBeanServer JavaDoc;
41 import javax.management.NotCompliantMBeanException JavaDoc;
42 import javax.management.Notification JavaDoc;
43 import javax.management.NotificationBroadcasterSupport JavaDoc;
44 import javax.management.NotificationFilter JavaDoc;
45 import javax.management.NotificationListener JavaDoc;
46 import javax.management.ObjectName JavaDoc;
47 import javax.management.ReflectionException JavaDoc;
48 import javax.management.RuntimeOperationsException JavaDoc;
49 import javax.management.StandardMBean JavaDoc;
50 import javax.management.modelmbean.DescriptorSupport JavaDoc;
51 import javax.management.modelmbean.ModelMBeanNotificationBroadcaster JavaDoc;
52 import javax.management.modelmbean.ModelMBeanNotificationInfo JavaDoc;
53
54 import java.beans.PropertyChangeEvent JavaDoc;
55 import java.beans.PropertyChangeListener JavaDoc;
56 import java.beans.PropertyDescriptor JavaDoc;
57 import java.lang.reflect.InvocationTargetException JavaDoc;
58 import java.util.Date JavaDoc;
59 import java.util.Hashtable JavaDoc;
60 import java.util.Iterator JavaDoc;
61 import java.util.LinkedHashMap JavaDoc;
62 import java.util.Map JavaDoc;
63
64 /**
65  * An MBean wrapper for an Existing Object
66  *
67  * @version $Revision: 426415 $
68  */

69 public class BaseStandardMBean extends StandardMBean JavaDoc
70         implements
71             ModelMBeanNotificationBroadcaster JavaDoc,
72             MBeanRegistration JavaDoc,
73             PropertyChangeListener JavaDoc {
74     private final static Log log = LogFactory.getLog(BaseStandardMBean.class);
75     private Map JavaDoc cachedAttributes = new LinkedHashMap JavaDoc();// used to maintain insertion ordering
76
private PropertyUtilsBean beanUtil = new PropertyUtilsBean();
77     private NotificationBroadcasterSupport JavaDoc broadcasterSupport = new NotificationBroadcasterSupport JavaDoc();
78     protected ExecutorService executorService;
79     private MBeanAttributeInfo JavaDoc[] attributeInfos;
80     private MBeanInfo JavaDoc beanInfo;
81     // this values are set after registering with the MBeanServer//
82
private ObjectName JavaDoc objectName;
83     private MBeanServer JavaDoc beanServer;
84
85     /**
86      * Constructor
87      *
88      * @param object
89      * @param interfaceMBean
90      * @param description
91      * @param attrs
92      * @param ops
93      * @param executorService2
94      * @throws ReflectionException
95      * @throws NotCompliantMBeanException
96      */

97     public BaseStandardMBean(Object JavaDoc object, Class JavaDoc interfaceMBean, String JavaDoc description, MBeanAttributeInfo JavaDoc[] attrs,
98             MBeanOperationInfo JavaDoc[] ops, ExecutorService executorService) throws ReflectionException JavaDoc, NotCompliantMBeanException JavaDoc {
99         super(object, interfaceMBean);
100         this.attributeInfos = attrs;
101         buildAttributes(object, this.attributeInfos);
102         this.beanInfo = new MBeanInfo JavaDoc(object.getClass().getName(), description, attrs, null, ops, getNotificationInfo());
103         this.executorService = executorService;
104     }
105
106     /**
107      * @return the MBeanINfo for this MBean
108      */

109     public MBeanInfo JavaDoc getMBeanInfo() {
110         return beanInfo;
111     }
112
113     /**
114      * Retrieve ObjectName of the MBean - set after registration
115      *
116      * @return the ObjectName of the MBean
117      */

118     public ObjectName JavaDoc getObjectName() {
119         return objectName;
120     }
121
122     /**
123      * Retrieve the MBeanServer - set after registration
124      *
125      * @return the beanServer
126      */

127     public MBeanServer JavaDoc getBeanServer() {
128         return beanServer;
129     }
130
131     /**
132      * Get the Value of an Attribute
133      *
134      * @param name
135      * @return the value of the Attribute
136      * @throws AttributeNotFoundException
137      * @throws MBeanException
138      * @throws ReflectionException
139      */

140     public Object JavaDoc getAttribute(String JavaDoc name) throws AttributeNotFoundException JavaDoc, MBeanException JavaDoc, ReflectionException JavaDoc {
141         Object JavaDoc result = null;
142         CachedAttribute ca = (CachedAttribute) cachedAttributes.get(name);
143         if (ca == null) {
144             // the use of proxies in MX4J has a bug - in which the caps can be changed on
145
// an attribute
146
for (Iterator JavaDoc i = cachedAttributes.entrySet().iterator();i.hasNext();) {
147                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
148                 String JavaDoc key = entry.getKey().toString();
149                 if (key.equalsIgnoreCase(name)) {
150                     ca = (CachedAttribute) entry.getValue();
151                     break;
152                 }
153             }
154         }
155         if (ca != null) {
156             result = getCurrentValue(ca);
157         }
158         else {
159             throw new AttributeNotFoundException JavaDoc("Could not locate " + name);
160         }
161         return result;
162     }
163
164     /**
165      * Set the Attribute
166      *
167      * @param attr
168      * @throws AttributeNotFoundException
169      * @throws InvalidAttributeValueException
170      * @throws MBeanException
171      * @throws ReflectionException
172      */

173     public void setAttribute(Attribute JavaDoc attr) throws AttributeNotFoundException JavaDoc, InvalidAttributeValueException JavaDoc,
174             MBeanException JavaDoc, ReflectionException JavaDoc {
175         String JavaDoc name = attr.getName();
176         CachedAttribute ca = (CachedAttribute) cachedAttributes.get(name);
177         if (ca != null) {
178             Attribute JavaDoc old = ca.getAttribute();
179             try {
180                 ca.updateAttribute(beanUtil, attr);
181                 sendAttributeChangeNotification(old, attr);
182             }
183             catch (NoSuchMethodException JavaDoc e) {
184                 throw new ReflectionException JavaDoc(e);
185             }
186             catch (IllegalAccessException JavaDoc e) {
187                 throw new ReflectionException JavaDoc(e);
188             }
189             catch (InvocationTargetException JavaDoc e) {
190                 Throwable JavaDoc t = e.getTargetException();
191                 if (t instanceof Exception JavaDoc) {
192                     throw new MBeanException JavaDoc(e);
193                 }
194                 throw new MBeanException JavaDoc(e);
195             }
196         }
197         else {
198             throw new AttributeNotFoundException JavaDoc("Could not locate " + name);
199         }
200     }
201
202     /**
203      * Update a named attribute
204      *
205      * @param name
206      * @param value
207      */

208     public void updateAttribute(String JavaDoc name, Object JavaDoc value) {
209         CachedAttribute ca = (CachedAttribute) cachedAttributes.get(name);
210         if (ca != null) {
211             Attribute JavaDoc old = ca.getAttribute();
212             ca.updateAttributeValue(value);
213             try {
214                 sendAttributeChangeNotification(old, ca.getAttribute());
215             }
216             catch (RuntimeOperationsException JavaDoc e) {
217                 log.error("Failed to update attribute: " + name + " to new value: " + value, e);
218             }
219             catch (MBeanException JavaDoc e) {
220                 log.error("Failed to update attribute: " + name + " to new value: " + value, e);
221             }
222         }
223     }
224
225     /**
226      * Attribute change - fire notification
227      *
228      * @param event
229      */

230     public void propertyChange(PropertyChangeEvent JavaDoc event) {
231         updateAttribute(event.getPropertyName(), event.getNewValue());
232     }
233
234     /**
235      * @param attributes - array of Attribute names
236      * @return AttributeList of matching Attributes
237      */

238     public AttributeList JavaDoc getAttributes(String JavaDoc[] attributes) {
239         AttributeList JavaDoc result = null;
240         try {
241             if (attributes != null) {
242                 result = new AttributeList JavaDoc();
243                 for (int i = 0;i < attributes.length;i++) {
244                     CachedAttribute ca = (CachedAttribute) cachedAttributes.get(attributes[i]);
245                     ca.updateValue(beanUtil);
246                     result.add(ca.getAttribute());
247                 }
248             }
249             else {
250                 // Do this to maintain insertion ordering
251
for (Iterator JavaDoc i = cachedAttributes.entrySet().iterator();i.hasNext();) {
252                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
253                     CachedAttribute ca = (CachedAttribute) entry.getValue();
254                     ca.updateValue(beanUtil);
255                     result.add(ca.getAttribute());
256                 }
257             }
258         }
259         catch (MBeanException JavaDoc e) {
260             log.error("Caught excdeption building attributes", e);
261         }
262         return result;
263     }
264
265     /**
266      * Set values of Attributes
267      *
268      * @param attributes
269      * @return the list of Attributes set with their new values
270      */

271     public AttributeList JavaDoc setAttributes(AttributeList JavaDoc attributes) {
272         AttributeList JavaDoc result = new AttributeList JavaDoc();
273         if (attributes != null) {
274             for (int i = 0;i < attributes.size();i++) {
275                 Attribute JavaDoc attribute = (Attribute JavaDoc) attributes.get(i);
276                 try {
277                     setAttribute(attribute);
278                 }
279                 catch (AttributeNotFoundException JavaDoc e) {
280                     log.warn("Failed to setAttribute(" + attribute + ")", e);
281                 }
282                 catch (InvalidAttributeValueException JavaDoc e) {
283                     log.warn("Failed to setAttribute(" + attribute + ")", e);
284                 }
285                 catch (MBeanException JavaDoc e) {
286                     log.warn("Failed to setAttribute(" + attribute + ")", e);
287                 }
288                 catch (ReflectionException JavaDoc e) {
289                     log.warn("Failed to setAttribute(" + attribute + ")", e);
290                 }
291                 result.add(attribute);
292             }
293         }
294         return result;
295     }
296
297     /**
298      * Invoke an operation
299      *
300      * @param name
301      * @param params
302      * @param signature
303      * @return result of invoking an operation
304      * @throws MBeanException
305      * @throws ReflectionException
306      */

307     public Object JavaDoc invoke(String JavaDoc name, Object JavaDoc[] params, String JavaDoc[] signature) throws MBeanException JavaDoc, ReflectionException JavaDoc {
308         try {
309             Class JavaDoc[] parameterTypes = new Class JavaDoc[signature.length];
310             for (int i = 0; i < parameterTypes.length; i++) {
311                 parameterTypes[i] = (Class JavaDoc) primitiveClasses.get(signature[i]);
312                 if (parameterTypes[i] == null) {
313                     parameterTypes[i] = Class.forName(signature[i]);
314                 }
315             }
316             return MethodUtils.invokeMethod(getImplementation(), name, params, parameterTypes);
317         }
318         catch (ClassNotFoundException JavaDoc e) {
319             throw new ReflectionException JavaDoc(e);
320         }
321         catch (NoSuchMethodException JavaDoc e) {
322             throw new ReflectionException JavaDoc(e);
323         }
324         catch (IllegalAccessException JavaDoc e) {
325             throw new ReflectionException JavaDoc(e);
326         }
327         catch (InvocationTargetException JavaDoc e) {
328             Throwable JavaDoc t = e.getTargetException();
329             if (t instanceof Exception JavaDoc) {
330                 throw new MBeanException JavaDoc((Exception JavaDoc)t);
331             } else {
332                 throw new MBeanException JavaDoc(e);
333             }
334         }
335     }
336
337     private final static Hashtable JavaDoc primitiveClasses = new Hashtable JavaDoc(8);
338     {
339         primitiveClasses.put(Boolean.TYPE.toString(), Boolean.TYPE);
340         primitiveClasses.put(Character.TYPE.toString(), Character.TYPE);
341         primitiveClasses.put(Byte.TYPE.toString(), Byte.TYPE);
342         primitiveClasses.put(Short.TYPE.toString(), Short.TYPE);
343         primitiveClasses.put(Integer.TYPE.toString(), Integer.TYPE);
344         primitiveClasses.put(Long.TYPE.toString(), Long.TYPE);
345         primitiveClasses.put(Float.TYPE.toString(), Float.TYPE);
346         primitiveClasses.put(Double.TYPE.toString(), Double.TYPE);
347      }
348     
349     /**
350      * Called at registration
351      *
352      * @param mbs
353      * @param on
354      * @return the ObjectName
355      * @throws Exception
356      */

357     public ObjectName JavaDoc preRegister(MBeanServer JavaDoc mbs,ObjectName JavaDoc on) throws Exception JavaDoc{
358         if(mbs != null){
359             this.beanServer = mbs;
360         }
361         if(on != null){
362             this.objectName = on;
363         }
364         return on;
365     }
366
367     /**
368      * Caled post registration
369      *
370      * @param done
371      */

372     public void postRegister(Boolean JavaDoc done) {
373     }
374
375     /**
376      * Called before removal from the MBeanServer
377      *
378      * @throws Exception
379      */

380     public void preDeregister() throws Exception JavaDoc {
381     }
382
383     /**
384      * Called after removal from the MBeanServer
385      */

386     public void postDeregister() {
387     }
388
389     /**
390      * @param notification
391      * @throws MBeanException
392      * @throws RuntimeOperationsException
393      */

394     public void sendNotification(final Notification JavaDoc notification) throws MBeanException JavaDoc, RuntimeOperationsException JavaDoc {
395         if (notification != null) {
396             if (!executorService.isShutdown()) {
397                 executorService.execute(new Runnable JavaDoc() {
398                     public void run() {
399                         broadcasterSupport.sendNotification(notification);
400                     }
401                 });
402             }
403         }
404     }
405
406     /**
407      * @param text
408      * @throws MBeanException
409      * @throws RuntimeOperationsException
410      */

411     public void sendNotification(String JavaDoc text) throws MBeanException JavaDoc, RuntimeOperationsException JavaDoc {
412         if (text != null) {
413             Notification JavaDoc myNtfyObj = new Notification JavaDoc("jmx.modelmbean.generic", this, 1, text);
414             sendNotification(myNtfyObj);
415         }
416     }
417
418     /**
419      * @param l
420      * @param attrName
421      * @param handback
422      * @throws MBeanException
423      * @throws RuntimeOperationsException
424      * @throws IllegalArgumentException
425      */

426     public void addAttributeChangeNotificationListener(NotificationListener JavaDoc l, String JavaDoc attrName, Object JavaDoc handback)
427             throws MBeanException JavaDoc, RuntimeOperationsException JavaDoc, IllegalArgumentException JavaDoc {
428         AttributeChangeNotificationFilter JavaDoc currFilter = new AttributeChangeNotificationFilter JavaDoc();
429         currFilter.enableAttribute(attrName);
430         broadcasterSupport.addNotificationListener(l, currFilter, handback);
431     }
432
433     /**
434      * @param l
435      * @param attrName
436      * @throws MBeanException
437      * @throws RuntimeOperationsException
438      * @throws ListenerNotFoundException
439      */

440     public void removeAttributeChangeNotificationListener(NotificationListener JavaDoc l, String JavaDoc attrName)
441             throws MBeanException JavaDoc, RuntimeOperationsException JavaDoc, ListenerNotFoundException JavaDoc {
442         broadcasterSupport.removeNotificationListener(l);
443     }
444
445     /**
446      * @param notification
447      * @throws MBeanException
448      * @throws RuntimeOperationsException
449      */

450     public void sendAttributeChangeNotification(AttributeChangeNotification JavaDoc notification) throws MBeanException JavaDoc,
451             RuntimeOperationsException JavaDoc {
452         sendNotification(notification);
453     }
454
455     /**
456      * @param oldAttr
457      * @param newAttr
458      * @throws MBeanException
459      * @throws RuntimeOperationsException
460      */

461     public void sendAttributeChangeNotification(Attribute JavaDoc oldAttr, Attribute JavaDoc newAttr) throws MBeanException JavaDoc,
462             RuntimeOperationsException JavaDoc {
463         if (!oldAttr.equals(newAttr)) {
464             AttributeChangeNotification JavaDoc notification = new AttributeChangeNotification JavaDoc(objectName, 1, ((new Date JavaDoc())
465                     .getTime()), "AttributeChange", oldAttr.getName(), (((newAttr.getValue()).getClass()).toString()),
466                     oldAttr.getValue(), newAttr.getValue());
467             sendAttributeChangeNotification(notification);
468         }
469     }
470
471     /**
472      * @return notificationInfo
473      */

474     public MBeanNotificationInfo JavaDoc[] getNotificationInfo() {
475         MBeanNotificationInfo JavaDoc[] result = new MBeanNotificationInfo JavaDoc[2];
476         Descriptor JavaDoc genericDescriptor = new DescriptorSupport JavaDoc(new String JavaDoc[]{"name=GENERIC",
477                 "descriptorType=notification", "log=T", "severity=5", "displayName=jmx.modelmbean.generic"});
478         result[0] = new ModelMBeanNotificationInfo JavaDoc(new String JavaDoc[]{"jmx.modelmbean.generic"}, "GENERIC",
479                 "A text notification has been issued by the managed resource", genericDescriptor);
480         Descriptor JavaDoc attributeDescriptor = new DescriptorSupport JavaDoc(new String JavaDoc[]{"name=ATTRIBUTE_CHANGE",
481                 "descriptorType=notification", "log=T", "severity=5", "displayName=jmx.attribute.change"});
482         result[1] = new ModelMBeanNotificationInfo JavaDoc(new String JavaDoc[]{"jmx.attribute.change"}, "ATTRIBUTE_CHANGE",
483                 "Signifies that an observed MBean attribute value has changed", attributeDescriptor);
484         return result;
485     }
486
487     /**
488      * @param l
489      * @param filter
490      * @param handle
491      * @throws IllegalArgumentException
492      */

493     public void addNotificationListener(NotificationListener JavaDoc l, NotificationFilter JavaDoc filter, Object JavaDoc handle)
494             throws IllegalArgumentException JavaDoc {
495         broadcasterSupport.addNotificationListener(l, filter, handle);
496     }
497
498     /**
499      * @param l
500      * @throws ListenerNotFoundException
501      */

502     public void removeNotificationListener(NotificationListener JavaDoc l) throws ListenerNotFoundException JavaDoc {
503         broadcasterSupport.removeNotificationListener(l);
504     }
505
506     private Object JavaDoc getCurrentValue(CachedAttribute ca) throws MBeanException JavaDoc {
507         Object JavaDoc result = null;
508         if (ca != null) {
509             try {
510                 result = beanUtil.getProperty(ca.getBean(), ca.getName());
511             }
512             catch (IllegalAccessException JavaDoc e) {
513                 throw new MBeanException JavaDoc(e);
514             }
515             catch (InvocationTargetException JavaDoc e) {
516                 throw new MBeanException JavaDoc(e);
517             }
518             catch (NoSuchMethodException JavaDoc e) {
519                 throw new MBeanException JavaDoc(e);
520             }
521         }
522         return result;
523     }
524
525     /**
526      * build internal Map of CachedAttributes
527      *
528      * @param obj
529      * @param attrs
530      * @throws ReflectionException
531      */

532     private void buildAttributes(Object JavaDoc obj, MBeanAttributeInfo JavaDoc[] attrs) throws ReflectionException JavaDoc {
533         if (attrs != null) {
534             for (int i = 0;i < attrs.length;i++) {
535                 try {
536                     String JavaDoc name = attrs[i].getName();
537                     PropertyDescriptor JavaDoc pd = beanUtil.getPropertyDescriptor(obj, name);
538                     Object JavaDoc value = beanUtil.getProperty(obj, name);
539                     Attribute JavaDoc attribute = new Attribute JavaDoc(name, value);
540                     CachedAttribute ca = new CachedAttribute(attribute);
541                     ca.setBean(obj);
542                     ca.setPropertyDescriptor(pd);
543                     cachedAttributes.put(name, ca);
544                 }
545                 catch (NoSuchMethodException JavaDoc e) {
546                     throw new ReflectionException JavaDoc(e);
547                 }
548                 catch (IllegalAccessException JavaDoc e) {
549                     throw new ReflectionException JavaDoc(e);
550                 }
551                 catch (InvocationTargetException JavaDoc e) {
552                     throw new ReflectionException JavaDoc(e);
553                 }
554             }
555         }
556     }
557 }
Popular Tags