KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xsocket > IntrospectionBasedDynamicBean


1 // $Id: IntrospectionBasedDynamicBean.java 1175 2007-04-18 18:30:43Z grro $
2
/*
3  * Copyright (c) xsocket.org, 2006 - 2007. All rights reserved.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  *
19  * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
20  * The latest copy of this software may be found on http://www.xsocket.org/
21  */

22 package org.xsocket;
23
24 import java.lang.reflect.Method JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Map JavaDoc;
28
29 import javax.management.Attribute JavaDoc;
30 import javax.management.AttributeList JavaDoc;
31 import javax.management.AttributeNotFoundException JavaDoc;
32 import javax.management.DynamicMBean JavaDoc;
33 import javax.management.InvalidAttributeValueException JavaDoc;
34 import javax.management.MBeanAttributeInfo JavaDoc;
35 import javax.management.MBeanException JavaDoc;
36 import javax.management.MBeanInfo JavaDoc;
37 import javax.management.ReflectionException JavaDoc;
38
39
40 /**
41  * introspection based dynamic mbean, which exposes the getter and setter methods
42  * (all visibilities) of the underlying object by using introspection <br>
43  *
44  * <b>framework internal class</b>
45  *
46  * @author grro@xsocket.org
47  */

48 public final class IntrospectionBasedDynamicBean implements DynamicMBean JavaDoc {
49     
50     private Object JavaDoc obj = null;
51     
52     private final Map JavaDoc<String JavaDoc, Info JavaDoc> properties = new HashMap JavaDoc<String JavaDoc, Info JavaDoc>();
53
54     /**
55      * constructore
56      *
57      * @param obj the object to create a mbean for
58      */

59     public IntrospectionBasedDynamicBean(Object JavaDoc obj) {
60         this.obj = obj;
61     }
62     
63     
64     /**
65      * @see javax.management.DynamicMBean#getAttribute(java.lang.String)
66      */

67     public Object JavaDoc getAttribute(String JavaDoc attribute) throws AttributeNotFoundException JavaDoc, MBeanException JavaDoc, ReflectionException JavaDoc {
68         String JavaDoc methodName = "get" + attribute;
69         try {
70             Method JavaDoc method = getMethod(obj.getClass(), methodName, new Class JavaDoc[0]);
71             method.setAccessible(true);
72             return method.invoke(obj, new Object JavaDoc[0]);
73         } catch (Exception JavaDoc e) {
74             e.printStackTrace();
75             throw new ReflectionException JavaDoc(e);
76         }
77     }
78     
79     @SuppressWarnings JavaDoc("unchecked")
80     private Method JavaDoc getMethod(Class JavaDoc clazz, String JavaDoc methodname, Class JavaDoc[] params) {
81         do {
82             try {
83                 Method JavaDoc method = clazz.getDeclaredMethod(methodname, params);
84                 method.setAccessible(true);
85                 return method;
86             } catch (Exception JavaDoc ignore) { }
87             
88             for (Class JavaDoc interf : clazz.getInterfaces()) {
89                 getMethod(interf, methodname, params);
90             }
91             
92             clazz = clazz.getSuperclass();
93             
94         } while (clazz != null);
95         
96         return null;
97     }
98     
99
100     /**
101      * {@inheritDoc}
102      */

103     public AttributeList JavaDoc getAttributes(String JavaDoc[] attributes) {
104         AttributeList JavaDoc list = new AttributeList JavaDoc();
105         for (String JavaDoc attribute : attributes) {
106             try {
107                 list.add(new Attribute JavaDoc(attribute, getAttribute(attribute)));
108             } catch (Exception JavaDoc ignore) { }
109         }
110         return list;
111     }
112
113
114     /**
115      * {@inheritDoc}
116      */

117     public void setAttribute(Attribute JavaDoc attribute) throws AttributeNotFoundException JavaDoc, InvalidAttributeValueException JavaDoc, MBeanException JavaDoc, ReflectionException JavaDoc {
118         String JavaDoc methodName = "set" + attribute.getName();
119         
120         Info JavaDoc info = getInfo(attribute.getName());
121         
122         try {
123             Method JavaDoc method = getMethod(obj.getClass(), methodName, new Class JavaDoc[] { info.propertyType });
124             method.setAccessible(true);
125             method.invoke(obj, new Object JavaDoc[] { attribute.getValue() });
126         } catch (Exception JavaDoc e) {
127             throw new ReflectionException JavaDoc(e);
128         }
129     }
130
131
132     /**
133      * {@inheritDoc}
134      */

135     public AttributeList JavaDoc setAttributes(AttributeList JavaDoc attributes) {
136         AttributeList JavaDoc result = new AttributeList JavaDoc();
137
138         Attribute JavaDoc[] attrs = (Attribute JavaDoc[]) attributes.toArray(new Attribute JavaDoc[attributes.size()]);
139         for (Attribute JavaDoc attr : attrs) {
140             try {
141                 setAttribute(attr);
142                 result.add(new Attribute JavaDoc(attr.getName(), attr.getValue()));
143             } catch (Exception JavaDoc ignore) { }
144         }
145         return result;
146     }
147     
148     
149
150     /**
151      * {@inheritDoc}
152      */

153     public Object JavaDoc invoke(String JavaDoc actionName, Object JavaDoc[] params, String JavaDoc[] signature) throws MBeanException JavaDoc, ReflectionException JavaDoc {
154         // TODO Auto-generated method stub
155
return null;
156     }
157     
158
159     /**
160      * {@inheritDoc}
161      */

162     public synchronized MBeanInfo JavaDoc getMBeanInfo() {
163         
164         analyze(obj);
165
166         String JavaDoc[] attributes = properties.keySet().toArray(new String JavaDoc[properties.size()]);
167         MBeanAttributeInfo JavaDoc[] attrs = new MBeanAttributeInfo JavaDoc[attributes.length];
168         for (int i = 0; i < attrs.length; i++) {
169             attrs[i] = properties.get(attributes[i]).asbMBeanAttributeInfo();
170         }
171
172             
173         return new MBeanInfo JavaDoc(
174                 obj.getClass().getName(),
175                 "",
176                 attrs,
177                 null, // constructors
178
null,
179                 null); // notifications
180
}
181     
182     
183     private void analyze(Object JavaDoc obj) {
184         Class JavaDoc clazz = obj.getClass();
185         do {
186             analyzeType(clazz);
187             
188             for (Class JavaDoc interf: clazz.getInterfaces()) {
189                 analyzeType(interf);
190             }
191             
192             clazz = clazz.getSuperclass();
193             
194         } while (clazz != null);
195     }
196     
197     private void analyzeType(Class JavaDoc clazz) {
198         for (Method JavaDoc method : clazz.getDeclaredMethods()) {
199             String JavaDoc name = method.getName();
200             
201             if ((name.length() > 3) && name.startsWith("get")) {
202                 if (method.getParameterTypes().length == 0) {
203                     Class JavaDoc propertyType = method.getReturnType();
204                 
205                     if(isAcceptedPropertyType(propertyType)) {
206                         Info JavaDoc info = getInfo(name.substring(3, name.length()));
207                         info.isReadable = true;
208                         info.propertyType = propertyType;
209                     }
210                 }
211             }
212             
213             if ((name.length() > 3) && name.startsWith("set")) {
214                 if (method.getParameterTypes().length == 1) {
215                     Class JavaDoc propertyType = method.getParameterTypes()[0];
216                     
217                     if(isAcceptedPropertyType(propertyType)) {
218                         Info JavaDoc info = getInfo(name.substring(3, name.length()));
219                         info.isWriteable = true;
220                         info.propertyType = propertyType;
221                     }
222                 }
223             }
224         }
225     }
226     
227     
228     private Info JavaDoc getInfo(String JavaDoc name) {
229         Info JavaDoc info = properties.get(name);
230         if (info == null) {
231             info = new Info JavaDoc();
232             info.propertyName = name;
233             info.propertyDescription = "Property " + info.propertyName;
234             properties.put(name, info);
235         }
236         return info;
237     }
238     
239     
240     
241     
242     @SuppressWarnings JavaDoc("unchecked")
243     private boolean isAcceptedPropertyType(Class JavaDoc clazz) {
244         if (clazz.isAssignableFrom(List JavaDoc.class)) {
245             return true;
246         }
247         
248         String JavaDoc name = clazz.getName();
249         return name.equals("int")
250                || name.equals("java.lang.Integer")
251                || name.equals("long")
252                || name.equals("java.lang.Long")
253                || name.equals("double")
254                || name.equals("java.lang.Double")
255                || name.equals("boolean")
256                || name.equals("java.lang.Boolean")
257                || name.equals("float")
258                || name.equals("java.lang.String")
259                || name.equals("java.lang.Float");
260     }
261
262     
263     private static class Info {
264         String JavaDoc propertyName = null;
265         Class JavaDoc propertyType = null;
266         String JavaDoc propertyDescription = null;
267         boolean isReadable = false;
268         boolean isWriteable = false;
269         boolean isIs = false;
270
271
272         MBeanAttributeInfo JavaDoc asbMBeanAttributeInfo() {
273             return new MBeanAttributeInfo JavaDoc(propertyName, propertyType.getName(), propertyDescription, isReadable, isWriteable, isIs);
274         }
275     }
276 }
277
Popular Tags