001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.util;
018
019 import java.beans.PropertyEditor;
020 import java.beans.PropertyEditorManager;
021 import java.lang.reflect.Field;
022 import java.lang.reflect.InvocationTargetException;
023 import java.lang.reflect.Method;
024 import java.lang.reflect.Modifier;
025 import java.net.URI;
026 import java.net.URISyntaxException;
027 import java.util.Arrays;
028 import java.util.HashMap;
029 import java.util.Iterator;
030 import java.util.LinkedHashMap;
031 import java.util.LinkedHashSet;
032 import java.util.Map;
033 import java.util.Set;
034
035 import org.apache.camel.NoTypeConversionAvailableException;
036 import org.apache.camel.TypeConverter;
037 import org.apache.commons.logging.Log;
038 import org.apache.commons.logging.LogFactory;
039
040 /**
041 * Helper for introspections of beans.
042 */
043 public final class IntrospectionSupport {
044
045 private static final transient Log LOG = LogFactory.getLog(IntrospectionSupport.class);
046
047 /**
048 * Utility classes should not have a public constructor.
049 */
050 private IntrospectionSupport() {
051 }
052
053 public static boolean getProperties(Object target, Map props, String optionPrefix) {
054 boolean rc = false;
055 if (target == null) {
056 throw new IllegalArgumentException("target was null.");
057 }
058 if (props == null) {
059 throw new IllegalArgumentException("props was null.");
060 }
061 if (optionPrefix == null) {
062 optionPrefix = "";
063 }
064
065 Class clazz = target.getClass();
066 Method[] methods = clazz.getMethods();
067 for (Method method : methods) {
068 String name = method.getName();
069 Class type = method.getReturnType();
070 Class params[] = method.getParameterTypes();
071 if (name.startsWith("get") && params.length == 0 && type != null && isSettableType(type)) {
072 try {
073 Object value = method.invoke(target);
074 if (value == null) {
075 continue;
076 }
077
078 String strValue = convertToString(value, type);
079 if (strValue == null) {
080 continue;
081 }
082
083 name = name.substring(3, 4).toLowerCase() + name.substring(4);
084 props.put(optionPrefix + name, strValue);
085 rc = true;
086 } catch (Throwable ignore) {
087 // ignore
088 }
089 }
090 }
091
092 return rc;
093 }
094
095 public static Object getProperty(Object target, String prop) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
096 if (target == null) {
097 throw new IllegalArgumentException("target was null.");
098 }
099 if (prop == null) {
100 throw new IllegalArgumentException("prop was null.");
101 }
102 prop = prop.substring(0, 1).toUpperCase() + prop.substring(1);
103
104 Class clazz = target.getClass();
105 Method method = getPropertyGetter(clazz, prop);
106 return method.invoke(target);
107 }
108
109 public static Method getPropertyGetter(Class type, String propertyName) throws NoSuchMethodException {
110 Method method = type.getMethod("get" + ObjectHelper.capitalize(propertyName));
111 return method;
112 }
113
114 public static boolean setProperties(Object target, Map props, String optionPrefix) throws Exception {
115 boolean rc = false;
116 if (target == null) {
117 throw new IllegalArgumentException("target was null.");
118 }
119 if (props == null) {
120 throw new IllegalArgumentException("props was null.");
121 }
122
123 for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
124 String name = (String)iter.next();
125 if (name.startsWith(optionPrefix)) {
126 Object value = props.get(name);
127 name = name.substring(optionPrefix.length());
128 if (setProperty(target, name, value)) {
129 iter.remove();
130 rc = true;
131 }
132 }
133 }
134 return rc;
135 }
136
137 public static Map extractProperties(Map props, String optionPrefix) {
138 if (props == null) {
139 throw new IllegalArgumentException("props was null.");
140 }
141
142 HashMap rc = new HashMap(props.size());
143
144 for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
145 String name = (String)iter.next();
146 if (name.startsWith(optionPrefix)) {
147 Object value = props.get(name);
148 name = name.substring(optionPrefix.length());
149 rc.put(name, value);
150 iter.remove();
151 }
152 }
153
154 return rc;
155 }
156
157 public static boolean setProperties(TypeConverter typeConverter, Object target, Map props) throws Exception {
158 boolean rc = false;
159
160 if (target == null) {
161 throw new IllegalArgumentException("target was null.");
162 }
163 if (props == null) {
164 throw new IllegalArgumentException("props was null.");
165 }
166
167 for (Iterator iter = props.entrySet().iterator(); iter.hasNext();) {
168 Map.Entry entry = (Map.Entry)iter.next();
169 if (setProperty(typeConverter, target, (String)entry.getKey(), entry.getValue())) {
170 iter.remove();
171 rc = true;
172 }
173 }
174
175 return rc;
176 }
177
178 public static boolean setProperties(Object target, Map props) throws Exception {
179 return setProperties(null, target, props);
180 }
181
182 public static boolean setProperty(TypeConverter typeConverter, Object target, String name, Object value) throws Exception {
183 try {
184 Class clazz = target.getClass();
185 // find candidates of setter methods as there can be overloaded setters
186 Set<Method> setters = findSetterMethods(typeConverter, clazz, name, value);
187 if (setters.isEmpty()) {
188 return false;
189 }
190
191 // loop and execute the best setter method
192 Exception typeConvertionFailed = null;
193 for (Method setter : setters) {
194 // If the type is null or it matches the needed type, just use the value directly
195 if (value == null || setter.getParameterTypes()[0].isAssignableFrom(value.getClass())) {
196 setter.invoke(target, value);
197 return true;
198 } else {
199 // We need to convert it
200 try {
201 // ignore exceptions as there could be another setter method where we could type convert successfully
202 Object convertedValue = convert(typeConverter, setter.getParameterTypes()[0], value);
203 setter.invoke(target, convertedValue);
204 return true;
205 } catch (NoTypeConversionAvailableException e) {
206 typeConvertionFailed = e;
207 } catch (IllegalArgumentException e) {
208 typeConvertionFailed = e;
209 }
210 LOG.trace("Setter \"" + setter + "\" with parameter type \""
211 + setter.getParameterTypes()[0] + "\" could not be used for type conertions of " + value);
212 }
213 }
214 // we did not find a setter method to use, and if we did try to use a type converter then throw
215 // this kind of exception as the caused by will hint this error
216 if (typeConvertionFailed != null) {
217 throw new IllegalArgumentException("Could not find a suitable setter for property: " + name
218 + " as there isn't a setter method with same type: " + value.getClass().getCanonicalName()
219 + " nor type convertion possbile: " + typeConvertionFailed.getMessage());
220 } else {
221 return false;
222 }
223 } catch (InvocationTargetException e) {
224 // lets unwrap the exception
225 Throwable throwable = e.getCause();
226 if (throwable instanceof Exception) {
227 Exception exception = (Exception)throwable;
228 throw exception;
229 } else {
230 Error error = (Error)throwable;
231 throw error;
232 }
233 }
234 }
235
236 public static boolean setProperty(Object target, String name, Object value) throws Exception {
237 return setProperty(null, target, name, value);
238 }
239
240 private static Object convert(TypeConverter typeConverter, Class type, Object value) throws URISyntaxException {
241 if (typeConverter != null) {
242 return typeConverter.convertTo(type, value);
243 }
244 PropertyEditor editor = PropertyEditorManager.findEditor(type);
245 if (editor != null) {
246 editor.setAsText(value.toString());
247 return editor.getValue();
248 }
249 if (type == URI.class) {
250 return new URI(value.toString());
251 }
252 return null;
253 }
254
255 private static String convertToString(Object value, Class type) throws URISyntaxException {
256 PropertyEditor editor = PropertyEditorManager.findEditor(type);
257 if (editor != null) {
258 editor.setValue(value);
259 return editor.getAsText();
260 }
261 if (type == URI.class) {
262 return value.toString();
263 }
264 return null;
265 }
266
267 private static Set<Method> findSetterMethods(TypeConverter typeConverter, Class clazz, String name, Object value) {
268 Set<Method> candidates = new LinkedHashSet<Method>();
269
270 // Build the method name.
271 name = "set" + ObjectHelper.capitalize(name);
272 while (clazz != Object.class) {
273 Method[] methods = clazz.getMethods();
274 for (Method method : methods) {
275 Class params[] = method.getParameterTypes();
276 if (method.getName().equals(name) && params.length == 1) {
277 Class paramType = params[0];
278 if (typeConverter != null || isSettableType(paramType) || paramType.isInstance(value)) {
279 candidates.add(method);
280 }
281 }
282 }
283 clazz = clazz.getSuperclass();
284 }
285
286 if (candidates.isEmpty()) {
287 return candidates;
288 } else if (candidates.size() == 1) {
289 // only one
290 return candidates;
291 } else {
292 // find the best match if possible
293 if (LOG.isTraceEnabled()) {
294 LOG.trace("Found " + candidates.size() + " suitable setter methods for setting " + name);
295 }
296 // perfer to use the one with the same instance if any exists
297 for (Method method : candidates) {
298 if (method.getParameterTypes()[0].isInstance(value)) {
299 if (LOG.isTraceEnabled()) {
300 LOG.trace("Method " + method + " is the best candidate as it has parameter with same instance type");
301 }
302 // retain only this method in the answer
303 candidates.clear();
304 candidates.add(method);
305 return candidates;
306 }
307 }
308 // fallback to return what we have found as candidates so far
309 return candidates;
310 }
311 }
312
313 private static boolean isSettableType(Class clazz) {
314 if (PropertyEditorManager.findEditor(clazz) != null) {
315 return true;
316 }
317 if (clazz == URI.class) {
318 return true;
319 }
320 if (clazz == Boolean.class) {
321 return true;
322 }
323 return false;
324 }
325
326 public static String toString(Object target) {
327 return toString(target, Object.class);
328 }
329
330 public static String toString(Object target, Class stopClass) {
331 LinkedHashMap map = new LinkedHashMap();
332 addFields(target, target.getClass(), stopClass, map);
333 StringBuffer buffer = new StringBuffer(simpleName(target.getClass()));
334 buffer.append(" {");
335 Set entrySet = map.entrySet();
336 boolean first = true;
337 for (Iterator iter = entrySet.iterator(); iter.hasNext();) {
338 Map.Entry entry = (Map.Entry)iter.next();
339 if (first) {
340 first = false;
341 } else {
342 buffer.append(", ");
343 }
344 buffer.append(entry.getKey());
345 buffer.append(" = ");
346 appendToString(buffer, entry.getValue());
347 }
348 buffer.append("}");
349 return buffer.toString();
350 }
351
352 protected static void appendToString(StringBuffer buffer, Object value) {
353 // if (value instanceof ActiveMQDestination) {
354 // ActiveMQDestination destination = (ActiveMQDestination) value;
355 // buffer.append(destination.getQualifiedName());
356 // }
357 // else {
358 buffer.append(value);
359 // }
360 }
361
362 public static String simpleName(Class clazz) {
363 String name = clazz.getName();
364 int p = name.lastIndexOf(".");
365 if (p >= 0) {
366 name = name.substring(p + 1);
367 }
368 return name;
369 }
370
371 private static void addFields(Object target, Class startClass, Class stopClass, LinkedHashMap map) {
372 if (startClass != stopClass) {
373 addFields(target, startClass.getSuperclass(), stopClass, map);
374 }
375
376 Field[] fields = startClass.getDeclaredFields();
377 for (Field field : fields) {
378 if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())
379 || Modifier.isPrivate(field.getModifiers())) {
380 continue;
381 }
382
383 try {
384 field.setAccessible(true);
385 Object o = field.get(target);
386 if (o != null && o.getClass().isArray()) {
387 try {
388 o = Arrays.asList((Object[])o);
389 } catch (Throwable e) {
390 // ignore
391 }
392 }
393 map.put(field.getName(), o);
394 } catch (Throwable e) {
395 LOG.debug("Error adding fields", e);
396 }
397 }
398 }
399
400 }