KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > util > IntrospectionSupport


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

18 package org.apache.activemq.util;
19
20 import org.apache.activemq.command.ActiveMQDestination;
21
22 import java.beans.PropertyEditor JavaDoc;
23 import java.beans.PropertyEditorManager JavaDoc;
24 import java.lang.reflect.Field JavaDoc;
25 import java.lang.reflect.Method JavaDoc;
26 import java.lang.reflect.Modifier JavaDoc;
27 import java.net.URI JavaDoc;
28 import java.net.URISyntaxException JavaDoc;
29 import java.util.Arrays JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.LinkedHashMap JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35 import java.util.Map.Entry;
36
37 public class IntrospectionSupport {
38         
39     
40     static public boolean getProperties(Object JavaDoc target, Map JavaDoc props, String JavaDoc optionPrefix) {
41         
42         boolean rc = false;
43         if( target == null )
44             throw new IllegalArgumentException JavaDoc("target was null.");
45         if( props == null )
46             throw new IllegalArgumentException JavaDoc("props was null.");
47         
48         if( optionPrefix == null )
49             optionPrefix="";
50         
51         Class JavaDoc clazz = target.getClass();
52         Method JavaDoc[] methods = clazz.getMethods();
53         for (int i = 0; i < methods.length; i++) {
54             Method JavaDoc method = methods[i];
55             String JavaDoc name = method.getName();
56             Class JavaDoc type = method.getReturnType();
57             Class JavaDoc params[] = method.getParameterTypes();
58             if( name.startsWith("get") && params.length==0 &&
59                     type!=null && isSettableType(type)) {
60
61                 try {
62                     
63                     Object JavaDoc value = method.invoke(target, new Object JavaDoc[]{});
64                     if( value == null )
65                         continue;
66                     
67                     String JavaDoc strValue = convertToString(value, type);
68                     if( strValue ==null )
69                         continue;
70                     
71                     name = name.substring(3,4).toLowerCase()+name.substring(4);
72                     props.put(optionPrefix+name, strValue);
73                     rc = true;
74                     
75                 } catch ( Throwable JavaDoc ignore) {
76                 }
77                 
78             }
79         }
80         
81         return rc;
82     }
83     
84     
85     
86     static public boolean setProperties(Object JavaDoc target, Map JavaDoc props, String JavaDoc optionPrefix) {
87         boolean rc = false;
88         if( target == null )
89             throw new IllegalArgumentException JavaDoc("target was null.");
90         if( props == null )
91             throw new IllegalArgumentException JavaDoc("props was null.");
92         
93         for (Iterator JavaDoc iter = props.keySet().iterator(); iter.hasNext();) {
94             String JavaDoc name = (String JavaDoc) iter.next();
95             if( name.startsWith(optionPrefix) ) {
96                 Object JavaDoc value = props.get(name);
97                 name = name.substring(optionPrefix.length());
98                 if( setProperty(target, name, value) ) {
99                     iter.remove();
100                     rc = true;
101                 }
102             }
103         }
104         return rc;
105     }
106     
107     public static Map JavaDoc extractProperties(Map JavaDoc props, String JavaDoc optionPrefix) {
108         if( props == null )
109             throw new IllegalArgumentException JavaDoc("props was null.");
110
111         HashMap JavaDoc rc = new HashMap JavaDoc(props.size());
112         
113         for (Iterator JavaDoc iter = props.keySet().iterator(); iter.hasNext();) {
114             String JavaDoc name = (String JavaDoc) iter.next();
115             if( name.startsWith(optionPrefix) ) {
116                 Object JavaDoc value = props.get(name);
117                 name = name.substring(optionPrefix.length());
118                 rc.put(name, value);
119                 iter.remove();
120             }
121         }
122         
123         return rc;
124     }
125           
126     public static boolean setProperties(Object JavaDoc target, Map JavaDoc props) {
127         boolean rc = false;
128         
129         if( target == null )
130             throw new IllegalArgumentException JavaDoc("target was null.");
131         if( props == null )
132             throw new IllegalArgumentException JavaDoc("props was null.");
133         
134         for (Iterator JavaDoc iter = props.entrySet().iterator(); iter.hasNext();) {
135             Map.Entry JavaDoc entry = (Entry) iter.next();
136             if( setProperty(target, (String JavaDoc) entry.getKey(), entry.getValue()) ) {
137                 iter.remove();
138                 rc=true;
139             }
140         }
141         
142         return rc;
143     }
144
145     public static boolean setProperty(Object JavaDoc target, String JavaDoc name, Object JavaDoc value) {
146         try {
147             Class JavaDoc clazz = target.getClass();
148             Method JavaDoc setter = findSetterMethod(clazz, name);
149             if( setter == null )
150                 return false;
151             
152             // If the type is null or it matches the needed type, just use the value directly
153
if( value == null || value.getClass()==setter.getParameterTypes()[0] ) {
154                 setter.invoke(target, new Object JavaDoc[]{value});
155             } else {
156                 // We need to convert it
157
setter.invoke(target, new Object JavaDoc[]{ convert(value, setter.getParameterTypes()[0]) });
158             }
159             return true;
160         } catch (Throwable JavaDoc ignore) {
161             return false;
162         }
163     }
164
165     private static Object JavaDoc convert(Object JavaDoc value, Class JavaDoc type) throws URISyntaxException JavaDoc {
166         PropertyEditor JavaDoc editor = PropertyEditorManager.findEditor(type);
167         if( editor != null ) {
168             editor.setAsText(value.toString());
169             return editor.getValue();
170         }
171         if( type == URI JavaDoc.class ) {
172             return new URI JavaDoc(value.toString());
173         }
174         return null;
175     }
176
177     private static String JavaDoc convertToString(Object JavaDoc value, Class JavaDoc type) throws URISyntaxException JavaDoc {
178         PropertyEditor JavaDoc editor = PropertyEditorManager.findEditor(type);
179         if( editor != null ) {
180             editor.setValue(value);
181             return editor.getAsText();
182         }
183         if( type == URI JavaDoc.class ) {
184             return ((URI JavaDoc)value).toString();
185         }
186         return null;
187     }
188
189     private static Method JavaDoc findSetterMethod(Class JavaDoc clazz, String JavaDoc name) {
190         // Build the method name.
191
name = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
192         Method JavaDoc[] methods = clazz.getMethods();
193         for (int i = 0; i < methods.length; i++) {
194             Method JavaDoc method = methods[i];
195             Class JavaDoc params[] = method.getParameterTypes();
196             if( method.getName().equals(name)
197                     && params.length==1
198                     && isSettableType(params[0])) {
199                 return method;
200             }
201         }
202         return null;
203     }
204
205     private static boolean isSettableType(Class JavaDoc clazz) {
206         if( PropertyEditorManager.findEditor(clazz)!=null )
207             return true;
208         if( clazz == URI JavaDoc.class )
209             return true;
210         if( clazz == Boolean JavaDoc.class )
211             return true;
212         return false;
213     }
214
215     static public String JavaDoc toString(Object JavaDoc target) {
216         return toString(target, Object JavaDoc.class);
217     }
218
219     static public String JavaDoc toString(Object JavaDoc target, Class JavaDoc stopClass) {
220         LinkedHashMap JavaDoc map = new LinkedHashMap JavaDoc();
221         addFields(target, target.getClass(), stopClass, map);
222         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(simpleName(target.getClass()));
223         buffer.append(" {");
224         Set JavaDoc entrySet = map.entrySet();
225         boolean first = true;
226         for (Iterator JavaDoc iter = entrySet.iterator(); iter.hasNext();) {
227             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iter.next();
228             if (first) {
229                 first = false;
230             }
231             else {
232                 buffer.append(", ");
233             }
234             buffer.append(entry.getKey());
235             buffer.append(" = ");
236             appendToString(buffer, entry.getValue());
237         }
238         buffer.append("}");
239         return buffer.toString();
240     }
241
242     protected static void appendToString(StringBuffer JavaDoc buffer, Object JavaDoc value) {
243         if (value instanceof ActiveMQDestination) {
244             ActiveMQDestination destination = (ActiveMQDestination) value;
245             buffer.append(destination.getQualifiedName());
246         }
247         else {
248             buffer.append(value);
249         }
250     }
251
252     static public String JavaDoc simpleName(Class JavaDoc clazz) {
253         String JavaDoc name = clazz.getName();
254         int p = name.lastIndexOf(".");
255         if( p >= 0 ) {
256             name = name.substring(p+1);
257         }
258         return name;
259     }
260     
261
262     static private void addFields(Object JavaDoc target, Class JavaDoc startClass, Class JavaDoc stopClass, LinkedHashMap JavaDoc map) {
263         
264         if( startClass!=stopClass )
265             addFields( target, startClass.getSuperclass(), stopClass, map );
266         
267         Field JavaDoc[] fields = startClass.getDeclaredFields();
268         for (int i = 0; i < fields.length; i++) {
269             Field JavaDoc field = fields[i];
270             if( Modifier.isStatic(field.getModifiers()) ||
271                 Modifier.isTransient(field.getModifiers()) ||
272                 Modifier.isPrivate(field.getModifiers()) ) {
273                 continue;
274             }
275             
276             try {
277                 field.setAccessible(true);
278                 Object JavaDoc o = field.get(target);
279                 if( o!=null && o.getClass().isArray() ) {
280                     try {
281                         o = Arrays.asList((Object JavaDoc[]) o);
282                     } catch (Throwable JavaDoc e) {
283                     }
284                 }
285                 map.put(field.getName(), o);
286             } catch (Throwable JavaDoc e) {
287                 e.printStackTrace();
288             }
289         }
290         
291     }
292
293     
294 }
295
Popular Tags