KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmanage > core > modules > JMXServerConnection


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

16 package org.jmanage.core.modules;
17
18 import org.jmanage.core.management.*;
19 import org.jmanage.core.management.ObjectName;
20 import org.jmanage.core.management.MalformedObjectNameException;
21 import org.jmanage.core.util.Loggers;
22
23 import javax.management.*;
24 import javax.management.openmbean.CompositeData JavaDoc;
25 import javax.management.openmbean.TabularData JavaDoc;
26 import java.util.*;
27 import java.util.logging.Logger JavaDoc;
28 import java.util.logging.Level JavaDoc;
29 import java.lang.reflect.Method JavaDoc;
30 import java.lang.reflect.InvocationTargetException JavaDoc;
31 import java.io.IOException JavaDoc;
32
33 /**
34  * Date: Sep 3, 2004 11:19:06 PM
35  * @author Shashank Bellary
36  * @author Rakesh Kalra
37  */

38 public abstract class JMXServerConnection implements ServerConnection{
39
40     private static final Logger JavaDoc logger =
41             Loggers.getLogger(JMXServerConnection.class);
42
43     private Object JavaDoc mbeanServer;
44     // this is required as the mbeanServer object may be of a class
45
// which is private inner class (e.g. in JSR160)
46
private Class JavaDoc mbeanServerClass;
47
48     public JMXServerConnection(){}
49
50     public JMXServerConnection(Object JavaDoc mbeanServer, Class JavaDoc mbeanServerClass){
51         this.mbeanServer = mbeanServer;
52         this.mbeanServerClass = mbeanServerClass;
53     }
54
55     /**
56      * Queries the MBeanServer for the given object name pattern.
57      *
58      * @param objectName the ObjectName pattern
59      * @return Set of ObjectName objects
60      */

61     public Set queryNames(ObjectName objectName){
62
63         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class,
64                                            javax.management.QueryExp JavaDoc.class};
65         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName),
66                                            null};
67         Set mbeans = (Set)callMBeanServer("queryNames", methodSignature,
68                 methodArgs);
69         return toJmanageObjectNameInstance(mbeans);
70     }
71
72
73     /**
74      * Invokes the given "operationName" on the object identified by
75      * "objectName".
76      *
77      * @param objectName
78      * @param operationName
79      * @param params
80      * @param signature
81      * @return
82      */

83     public Object JavaDoc invoke(ObjectName objectName,
84                          String JavaDoc operationName,
85                          Object JavaDoc[] params,
86                          String JavaDoc[] signature) {
87
88         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class,
89                                            String JavaDoc.class,
90                                            new Object JavaDoc[0].getClass(),
91                                            new String JavaDoc[0].getClass()};
92         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName),
93                                            operationName,
94                                            params,
95                                            signature};
96         return callMBeanServer("invoke", methodSignature, methodArgs);
97     }
98
99     /**
100      * Returns the information about the given objectName.
101      *
102      * @param objectName
103      * @return
104      */

105     public ObjectInfo getObjectInfo(ObjectName objectName) {
106
107         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class};
108         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName)};
109         MBeanInfo mbeanInfo = (MBeanInfo)callMBeanServer("getMBeanInfo",
110                 methodSignature, methodArgs);
111         return toObjectInfo(objectName, mbeanInfo);
112     }
113
114     /**
115      * Gets the value for a single attribute.
116      *
117      * @param objectName
118      * @param attributeName
119      * @return attribute value
120      */

121     public Object JavaDoc getAttribute(ObjectName objectName, String JavaDoc attributeName){
122
123         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class,
124                                               String JavaDoc.class};
125         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName),
126                                            attributeName};
127         return callMBeanServer("getAttribute", methodSignature, methodArgs);
128     }
129
130     /**
131      * Returns a list of ObjectAttribute objects containing attribute names
132      * and values for the given attributeNames
133      *
134      * @param objectName
135      * @param attributeNames
136      * @return
137      */

138     public List getAttributes(ObjectName objectName, String JavaDoc[] attributeNames) {
139
140         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class,
141                                               new String JavaDoc[0].getClass()};
142         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName),
143                                            attributeNames};
144         AttributeList attrList = (AttributeList)callMBeanServer("getAttributes",
145                 methodSignature, methodArgs);
146         return toObjectAttributeList(attrList);
147     }
148
149     /**
150      * Saves the attribute values.
151      *
152      * @param objectName
153      * @param attributeList list of ObjectAttribute objects
154      */

155     public List setAttributes(ObjectName objectName, List attributeList) {
156
157         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class,
158                                               javax.management.AttributeList JavaDoc.class};
159         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName),
160                                            toJMXAttributeList(attributeList)};
161         AttributeList output = (AttributeList)callMBeanServer("setAttributes",
162                 methodSignature, methodArgs);
163         return toObjectAttributeList(output);
164     }
165
166     // maps for storing jmanage notification objects to jmx notification
167
// object relationships
168
protected Map notifications = new HashMap();
169     protected Map notifFilters = new HashMap();
170
171     public void addNotificationListener(ObjectName objectName,
172                                         ObjectNotificationListener listener,
173                                         ObjectNotificationFilter filter,
174                                         Object JavaDoc handback){
175
176         NotificationListener notifListener =
177                 toJMXNotificationListener(listener);
178         notifications.put(listener, notifListener);
179         NotificationFilter notifFilter =
180                 toJMXNotificationFilter(filter);
181         notifFilters.put(filter, notifFilter);
182
183         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class,
184                                            NotificationListener.class,
185                                            NotificationFilter.class,
186                                            Object JavaDoc.class};
187         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName),
188                                            notifListener,
189                                            notifFilter,
190                                            handback};
191         callMBeanServer("addNotificationListener", methodSignature, methodArgs);
192     }
193
194     public void removeNotificationListener(ObjectName objectName,
195                                            ObjectNotificationListener listener,
196                                            ObjectNotificationFilter filter,
197                                            Object JavaDoc handback){
198
199         NotificationListener notifListener =
200                 (NotificationListener)notifications.remove(listener);
201         NotificationFilter notifFilter =
202                 (NotificationFilter)notifFilters.remove(filter);
203         assert notifListener != null;
204         assert notifFilter != null;
205
206         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class,
207                                            NotificationListener.class,
208                                            NotificationFilter.class,
209                                            Object JavaDoc.class};
210         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName),
211                                            notifListener,
212                                            notifFilter,
213                                            handback};
214         callMBeanServer("removeNotificationListener", methodSignature, methodArgs);
215     }
216
217     // todo: this method will need to throw InstanceAlreadyExistsException
218
public void createMBean(String JavaDoc className,
219                             ObjectName name,
220                             Object JavaDoc[] params,
221                             String JavaDoc[] signature){
222         Class JavaDoc[] methodSignature = new Class JavaDoc[]{String JavaDoc.class,
223                                            javax.management.ObjectName JavaDoc.class,
224                                            new Object JavaDoc[0].getClass(),
225                                            new String JavaDoc[0].getClass()};
226         Object JavaDoc[] methodArgs = new Object JavaDoc[]{className, toJMXObjectName(name),
227                                            params, signature};
228         callMBeanServer("createMBean", methodSignature, methodArgs);
229     }
230
231     public void unregisterMBean(ObjectName objectName){
232
233         Class JavaDoc[] methodSignature = new Class JavaDoc[]{javax.management.ObjectName JavaDoc.class};
234         Object JavaDoc[] methodArgs = new Object JavaDoc[]{toJMXObjectName(objectName)};
235         callMBeanServer("unregisterMBean", methodSignature, methodArgs);
236     }
237
238     public Object JavaDoc buildObjectName(String JavaDoc objectName){
239         try {
240             return new javax.management.ObjectName JavaDoc(objectName);
241         } catch (javax.management.MalformedObjectNameException JavaDoc e) {
242             throw new RuntimeException JavaDoc(e);
243         }
244     }
245
246     /**
247      * checks if this connection is open.
248      * It simply calls getMBeanCount() method on MBeanServer Connection.
249      * If there is no errors, then the connection is assumed to be open.
250      *
251      * @return true if this connection is open
252      */

253     public boolean isOpen(){
254         try {
255             Class JavaDoc[] methodSignature = new Class JavaDoc[0];
256             Object JavaDoc[] methodArgs = new Object JavaDoc[0];
257             Integer JavaDoc count = (Integer JavaDoc)callMBeanServer("getMBeanCount",
258                     methodSignature, methodArgs);
259             return true;
260         } catch (Exception JavaDoc e) {
261             logger.log(Level.INFO, "Connection to the server is lost. " +
262                     "Error message: " + e.getMessage());
263             return false;
264         }
265     }
266
267     /**
268      * Closes the connection to the server
269      */

270     public void close() throws IOException JavaDoc{
271         logger.fine("Noop close operation.");
272     }
273
274     ///////////////////////////////////////////////////////////////////////////
275
// Utility methods
276

277     private Object JavaDoc callMBeanServer(String JavaDoc methodName,
278                                    Class JavaDoc[] params,
279                                    Object JavaDoc[] args){
280
281         try {
282             Method JavaDoc method = mbeanServerClass.getMethod(methodName, params);
283             return method.invoke(mbeanServer, args);
284         } catch (InvocationTargetException JavaDoc e) {
285             if(e.getCause() != null &&
286                     e.getCause() instanceof RuntimeException JavaDoc){
287                 throw (RuntimeException JavaDoc)e.getCause();
288             }
289             throw new RuntimeException JavaDoc(e.getCause());
290         } catch (Throwable JavaDoc e){
291             if(e instanceof RuntimeException JavaDoc){
292                 throw (RuntimeException JavaDoc)e;
293             }else{
294                 throw new RuntimeException JavaDoc(e);
295             }
296         }
297     }
298
299     protected static javax.management.ObjectName JavaDoc
300             toJMXObjectName(ObjectName objectName){
301         try {
302             return new javax.management.ObjectName JavaDoc(objectName.toString());
303         } catch (javax.management.MalformedObjectNameException JavaDoc e) {
304             throw new MalformedObjectNameException(e);
305         }
306     }
307
308     protected static ObjectName toJmanageObjectName(
309             javax.management.ObjectName JavaDoc objectName){
310         return new ObjectName(objectName.toString(),
311                 objectName.getCanonicalName());
312     }
313
314     /**
315      * Converts a Set of javax.management.ObjectName to
316      * org.jmanage.core.management.ObjectName
317      */

318     protected static Set toJmanageObjectNameInstance(Set mbeans){
319         final Set output = new HashSet(mbeans.size());
320         for(Iterator it=mbeans.iterator(); it.hasNext();){
321             javax.management.ObjectName JavaDoc objName =
322                     (javax.management.ObjectName JavaDoc)it.next();
323             output.add(toJmanageObjectName(objName));
324         }
325         return output;
326     }
327
328     protected static ObjectInfo toObjectInfo(ObjectName objectName,
329                                              MBeanInfo mbeanInfo){
330
331         ObjectAttributeInfo[] attributes =
332                 toObjectAttributes(mbeanInfo.getAttributes());
333         ObjectConstructorInfo[] constructors =
334                 toObjectConstructors(mbeanInfo.getConstructors());
335         ObjectOperationInfo[] operations =
336                 toObjectOperations(mbeanInfo.getOperations());
337         ObjectNotificationInfo[] notifications =
338                 toObjectNotifications(mbeanInfo.getNotifications());
339         return new ObjectInfo(objectName, mbeanInfo.getClassName(),
340                 mbeanInfo.getDescription(), attributes,
341                 constructors, operations, notifications);
342     }
343
344     protected static ObjectAttributeInfo[]
345             toObjectAttributes(MBeanAttributeInfo[] attributes){
346         ObjectAttributeInfo[] objAttributes =
347                 new ObjectAttributeInfo[attributes.length];
348         for(int i=0; i < attributes.length; i++) {
349             objAttributes[i] = toObjectAttributeInfo(attributes[i]);
350         }
351         return objAttributes;
352     }
353
354     protected static ObjectAttributeInfo
355             toObjectAttributeInfo(MBeanAttributeInfo attribute){
356
357         return new ObjectAttributeInfo(attribute.getName(),
358                 attribute.getDescription(),
359                 attribute.getType(),
360                 attribute.isWritable(),
361                 attribute.isReadable(),
362                 attribute.isIs());
363     }
364
365     protected static ObjectConstructorInfo[]
366             toObjectConstructors(MBeanConstructorInfo[] constructors){
367         ObjectConstructorInfo[] objCtors =
368                 new ObjectConstructorInfo[constructors.length];
369         for(int i=0; i < constructors.length; i++) {
370             objCtors[i] = toObjectConstructorInfo(constructors[i]);
371         }
372         return objCtors;
373     }
374
375     protected static ObjectConstructorInfo
376             toObjectConstructorInfo(MBeanConstructorInfo constructor){
377         return new ObjectConstructorInfo(constructor.getName(),
378                 constructor.getDescription(),
379                 toObjectParameters(constructor.getSignature()));
380     }
381
382     protected static ObjectOperationInfo[]
383             toObjectOperations(MBeanOperationInfo[] operations){
384         ObjectOperationInfo[] objOperations =
385                 new ObjectOperationInfo[operations.length];
386         for(int i=0; i < operations.length; i++) {
387             objOperations[i] = toObjectOperationInfo(operations[i]);
388         }
389         return objOperations;
390     }
391
392     protected static ObjectOperationInfo
393             toObjectOperationInfo(MBeanOperationInfo operation){
394         return new ObjectOperationInfo(operation.getName(),
395                 operation.getDescription(),
396                 toObjectParameters(operation.getSignature()),
397                 operation.getReturnType(),
398                 operation.getImpact());
399     }
400
401     protected static ObjectNotificationInfo[]
402                 toObjectNotifications(MBeanNotificationInfo[] notifications){
403         ObjectNotificationInfo[] objNotifications =
404                 new ObjectNotificationInfo[notifications.length];
405         for(int i=0; i < notifications.length; i++) {
406             objNotifications[i] = toObjectNotificationInfo(notifications[i]);
407         }
408         return objNotifications;
409     }
410
411     protected static ObjectNotificationInfo
412             toObjectNotificationInfo(MBeanNotificationInfo notification){
413         return new ObjectNotificationInfo(notification.getNotifTypes(),
414                 notification.getName(),
415                 notification.getDescription());
416     }
417
418     protected static ObjectParameterInfo[]
419             toObjectParameters(MBeanParameterInfo[] parameters){
420         ObjectParameterInfo[] objParameters =
421                 new ObjectParameterInfo[parameters.length];
422         for(int i=0; i < parameters.length; i++) {
423             objParameters[i] = toObjectParameterInfo(parameters[i]);
424         }
425         return objParameters;
426     }
427
428     protected static ObjectParameterInfo
429             toObjectParameterInfo(MBeanParameterInfo parameter){
430
431         return new ObjectParameterInfo(parameter.getName(),
432                 parameter.getDescription(), parameter.getType());
433     }
434
435     protected static List toObjectAttributeList(AttributeList attrList){
436         final List objAttrList = new ArrayList(attrList.size());
437         for(Iterator it=attrList.iterator(); it.hasNext(); ){
438             Attribute attr = (Attribute)it.next();
439             objAttrList.add(toObjectAttribute(attr));
440         }
441         return objAttrList;
442     }
443
444     protected static ObjectAttribute toObjectAttribute(Attribute attr){
445         Object JavaDoc value = attr.getValue();
446         if(value != null){
447             // todo: ideally this needs to be done only if the JMX classes
448
// are not compatible
449
if(value instanceof CompositeData JavaDoc){
450                 value = JMXInterfaceProxy.newProxyInstance(
451                         CompositeData JavaDoc.class, value);
452             }else if(value instanceof TabularData JavaDoc){
453                 value = JMXInterfaceProxy.newProxyInstance(
454                         TabularData JavaDoc.class, value);
455             }
456         }
457         return new ObjectAttribute(attr.getName(), value);
458     }
459
460     protected static AttributeList toJMXAttributeList(List objAttrs){
461         AttributeList attrList = new AttributeList(objAttrs.size());
462         for(Iterator it=objAttrs.iterator(); it.hasNext(); ){
463             attrList.add(toJMXAttribute((ObjectAttribute)it.next()));
464         }
465         return attrList;
466     }
467
468     protected static Attribute toJMXAttribute(ObjectAttribute objAttr){
469         return new Attribute(objAttr.getName(), objAttr.getValue());
470     }
471
472     protected static ObjectNotification toObjectNotification(
473             Notification n){
474
475         return new ObjectNotification(n.getType(), n.getSource(),
476                 n.getSequenceNumber(), n.getTimeStamp(),
477                 n.getMessage(), n.getUserData());
478     }
479
480     protected static NotificationListener toJMXNotificationListener(
481             final ObjectNotificationListener listener){
482
483         return new NotificationListener(){
484             public void handleNotification(Notification notification,
485                                        Object JavaDoc handback) {
486                 listener.handleNotification(toObjectNotification(notification),
487                         handback);
488             }
489         };
490     }
491
492     protected static NotificationFilter toJMXNotificationFilter(
493             final ObjectNotificationFilter filter){
494         NotificationFilterSupport notificationFilter =
495                 new NotificationFilterSupport();
496         for(Iterator it=filter.getEnabledTypes().iterator(); it.hasNext();){
497             notificationFilter.enableType((String JavaDoc)it.next());
498         }
499         return notificationFilter;
500     }
501 }
502
Popular Tags