KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > jmx > support > JmxUtils


1 /*
2  * Copyright 2002-2007 the original author or authors.
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
17 package org.springframework.jmx.support;
18
19 import java.beans.PropertyDescriptor JavaDoc;
20 import java.lang.management.ManagementFactory JavaDoc;
21 import java.lang.reflect.Method JavaDoc;
22 import java.util.Hashtable JavaDoc;
23 import java.util.List JavaDoc;
24
25 import javax.management.DynamicMBean JavaDoc;
26 import javax.management.MBeanParameterInfo JavaDoc;
27 import javax.management.MBeanServer JavaDoc;
28 import javax.management.MBeanServerFactory JavaDoc;
29 import javax.management.MalformedObjectNameException JavaDoc;
30 import javax.management.ObjectName JavaDoc;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34
35 import org.springframework.core.JdkVersion;
36 import org.springframework.jmx.MBeanServerNotFoundException;
37 import org.springframework.util.ClassUtils;
38 import org.springframework.util.ObjectUtils;
39 import org.springframework.util.StringUtils;
40
41 /**
42  * Collection of generic utility methods to support Spring JMX.
43  * Includes a convenient method to locate an MBeanServer.
44  *
45  * @author Rob Harrop
46  * @author Juergen Hoeller
47  * @since 1.2
48  * @see #locateMBeanServer
49  */

50 public abstract class JmxUtils {
51
52     /**
53      * The key used when extending an existing {@link ObjectName} with the
54      * identity hash code of its corresponding managed resource.
55      */

56     public static final String JavaDoc IDENTITY_OBJECT_NAME_KEY = "identity";
57
58     /**
59      * Suffix used to identify an MBean interface
60      */

61     private static final String JavaDoc MBEAN_SUFFIX = "MBean";
62
63
64     private static final Log logger = LogFactory.getLog(JmxUtils.class);
65
66
67     /**
68      * Attempt to find a locally running <code>MBeanServer</code>. Fails if no
69      * <code>MBeanServer</code> can be found. Logs a warning if more than one
70      * <code>MBeanServer</code> found, returning the first one from the list.
71      * @return the <code>MBeanServer</code> if found
72      * @throws org.springframework.jmx.MBeanServerNotFoundException
73      * if no <code>MBeanServer</code> could be found
74      * @see javax.management.MBeanServerFactory#findMBeanServer
75      */

76     public static MBeanServer JavaDoc locateMBeanServer() throws MBeanServerNotFoundException {
77         return locateMBeanServer(null);
78     }
79
80     /**
81      * Attempt to find a locally running <code>MBeanServer</code>. Fails if no
82      * <code>MBeanServer</code> can be found. Logs a warning if more than one
83      * <code>MBeanServer</code> found, returning the first one from the list.
84      * @param agentId the agent identifier of the MBeanServer to retrieve.
85      * If this parameter is <code>null</code>, all registered MBeanServers are
86      * considered.
87      * @return the <code>MBeanServer</code> if found
88      * @throws org.springframework.jmx.MBeanServerNotFoundException
89      * if no <code>MBeanServer</code> could be found
90      * @see javax.management.MBeanServerFactory#findMBeanServer(String)
91      */

92     public static MBeanServer JavaDoc locateMBeanServer(String JavaDoc agentId) throws MBeanServerNotFoundException {
93         List JavaDoc servers = MBeanServerFactory.findMBeanServer(agentId);
94
95         MBeanServer JavaDoc server = null;
96         if (servers != null && servers.size() > 0) {
97             // Check to see if an MBeanServer is registered.
98
if (servers.size() > 1 && logger.isWarnEnabled()) {
99                 logger.warn("Found more than one MBeanServer instance" +
100                         (agentId != null ? " with agent id [" + agentId + "]" : "") +
101                         ". Returning first from list.");
102             }
103             server = (MBeanServer JavaDoc) servers.get(0);
104         }
105
106         if (server == null && agentId == null && JdkVersion.isAtLeastJava15()) {
107             // Attempt to load the PlatformMBeanServer.
108
try {
109                 server = ManagementFactory.getPlatformMBeanServer();
110             }
111             catch (SecurityException JavaDoc ex) {
112                 throw new MBeanServerNotFoundException("No specific MBeanServer found, " +
113                         "and not allowed to obtain the Java platform MBeanServer", ex);
114             }
115         }
116
117         if (server == null) {
118             throw new MBeanServerNotFoundException(
119                     "Unable to locate an MBeanServer instance" +
120                     (agentId != null ? " with agent id [" + agentId + "]" : ""));
121         }
122
123         if (logger.isDebugEnabled()) {
124             logger.debug("Found MBeanServer: " + server);
125         }
126         return server;
127     }
128
129     /**
130      * Convert an array of <code>MBeanParameterInfo</code> into an array of
131      * <code>Class</code> instances corresponding to the parameters.
132      * @param paramInfo the JMX parameter info
133      * @return the parameter types as classes
134      * @throws ClassNotFoundException if a parameter type could not be resolved
135      */

136     public static Class JavaDoc[] parameterInfoToTypes(MBeanParameterInfo JavaDoc[] paramInfo) throws ClassNotFoundException JavaDoc {
137         Class JavaDoc[] types = null;
138         if (paramInfo != null && paramInfo.length > 0) {
139             types = new Class JavaDoc[paramInfo.length];
140             for (int x = 0; x < paramInfo.length; x++) {
141                 types[x] = ClassUtils.forName(paramInfo[x].getType());
142             }
143         }
144         return types;
145     }
146
147     /**
148      * Create a <code>String[]</code> representing the argument signature of a
149      * method. Each element in the array is the fully qualified class name
150      * of the corresponding argument in the methods signature.
151      * @param method the method to build an argument signature for
152      * @return the signature as array of argument types
153      */

154     public static String JavaDoc[] getMethodSignature(Method JavaDoc method) {
155         Class JavaDoc[] types = method.getParameterTypes();
156         String JavaDoc[] signature = new String JavaDoc[types.length];
157         for (int x = 0; x < types.length; x++) {
158             signature[x] = types[x].getName();
159         }
160         return signature;
161     }
162
163     /**
164      * Return the JMX attribute name to use for the given JavaBeans property.
165      * <p>When using strict casing, a JavaBean property with a getter method
166      * such as <code>getFoo()</code> translates to an attribute called
167      * <code>Foo</code>. With strict casing disabled, <code>getFoo()</code>
168      * would translate to just <code>foo</code>.
169      * @param property the JavaBeans property descriptor
170      * @param useStrictCasing whether to use strict casing
171      * @return the JMX attribute name to use
172      */

173     public static String JavaDoc getAttributeName(PropertyDescriptor JavaDoc property, boolean useStrictCasing) {
174         if (useStrictCasing) {
175             return StringUtils.capitalize(property.getName());
176         }
177         else {
178             return property.getName();
179         }
180     }
181
182     /**
183      * Determine whether the given bean class qualifies as an MBean as-is.
184      * <p>This implementation checks for {@link javax.management.DynamicMBean}
185      * classes as well as classes with corresponding "*MBean" interface
186      * (Standard MBeans).
187      * @param beanClass the bean class to analyze
188      * @return whether the class qualifies as an MBean
189      * @see org.springframework.jmx.export.MBeanExporter#isMBean(Class)
190      */

191     public static boolean isMBean(Class JavaDoc beanClass) {
192         if (beanClass == null) {
193             return false;
194         }
195         if (DynamicMBean JavaDoc.class.isAssignableFrom(beanClass)) {
196             return true;
197         }
198         Class JavaDoc cls = beanClass;
199         while (cls != null && cls != Object JavaDoc.class) {
200             if (hasMBeanInterface(cls)) {
201                 return true;
202             }
203             cls = cls.getSuperclass();
204         }
205         return false;
206     }
207
208     /**
209      * Return the class or interface to expose for the given bean.
210      * This is the class that will be searched for attributes and operations
211      * (for example, checked for annotations).
212      * <p>This implementation returns the superclass for a CGLIB proxy and
213      * the class of the given bean else (for a JDK proxy or a plain bean class).
214      * @param managedBean the bean instance (might be an AOP proxy)
215      * @return the bean class to expose
216      * @see org.springframework.util.ClassUtils#getUserClass(Object)
217      */

218     public static Class JavaDoc getClassToExpose(Object JavaDoc managedBean) {
219         return ClassUtils.getUserClass(managedBean);
220     }
221
222     /**
223      * Return the class or interface to expose for the given bean class.
224      * This is the class that will be searched for attributes and operations
225      * (for example, checked for annotations).
226      * <p>This implementation returns the superclass for a CGLIB proxy and
227      * the class of the given bean else (for a JDK proxy or a plain bean class).
228      * @param beanClass the bean class (might be an AOP proxy class)
229      * @return the bean class to expose
230      * @see org.springframework.util.ClassUtils#getUserClass(Class)
231      */

232     public static Class JavaDoc getClassToExpose(Class JavaDoc beanClass) {
233         return ClassUtils.getUserClass(beanClass);
234     }
235
236     /**
237      * Return whether a Standard MBean interface exists for the given class
238      * (that is, an interface whose name matches the class name of the
239      * given class but with suffix "MBean).
240      * @param clazz the class to check
241      * @return whether there is a Standard MBean interface for the given class
242      */

243     private static boolean hasMBeanInterface(Class JavaDoc clazz) {
244         Class JavaDoc[] implementedInterfaces = clazz.getInterfaces();
245         String JavaDoc mbeanInterfaceName = clazz.getName() + MBEAN_SUFFIX;
246         for (int x = 0; x < implementedInterfaces.length; x++) {
247             Class JavaDoc iface = implementedInterfaces[x];
248             if (iface.getName().equals(mbeanInterfaceName)) {
249                 return true;
250             }
251         }
252         return false;
253     }
254
255     /**
256      * Append an additional key/value pair to an existing {@link ObjectName} with the key being
257      * the static value <code>identity</code> and the value being the identity hash code of the
258      * managed resource being exposed on the supplied {@link ObjectName}. This can be used to
259      * provide a unique {@link ObjectName} for each distinct instance of a particular bean or
260      * class. Useful when generating {@link ObjectName ObjectNames} at runtime for a set of
261      * managed resources based on the template value supplied by a
262      * {@link org.springframework.jmx.export.naming.ObjectNamingStrategy}.
263      * @param objectName the original JMX ObjectName
264      * @param managedResource the MBean instance
265      * @return an ObjectName with the MBean identity added
266      * @throws MalformedObjectNameException in case of an invalid object name specification
267      * @see org.springframework.util.ObjectUtils#getIdentityHexString(Object)
268      */

269     public static ObjectName JavaDoc appendIdentityToObjectName(ObjectName JavaDoc objectName, Object JavaDoc managedResource)
270             throws MalformedObjectNameException JavaDoc {
271
272         Hashtable JavaDoc keyProperties = objectName.getKeyPropertyList();
273         keyProperties.put(IDENTITY_OBJECT_NAME_KEY, ObjectUtils.getIdentityHexString(managedResource));
274         return ObjectNameManager.getInstance(objectName.getDomain(), keyProperties);
275     }
276
277 }
278
Popular Tags