1 package org.vaadin.console;
3 import java.beans.BeanInfo;
4 import java.beans.Introspector;
5 import java.beans.PropertyDescriptor;
6 import java.io.Serializable;
7 import java.lang.reflect.Field;
8 import java.lang.reflect.InvocationTargetException;
9 import java.lang.reflect.Method;
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Collections;
13 import java.util.HashMap;
14 import java.util.HashSet;
15 import java.util.LinkedHashMap;
16 import java.util.LinkedHashSet;
17 import java.util.List;
21 import org.vaadin.console.Console.Command;
23 import com.vaadin.ui.Component;
26 * Java object inspector.
28 * With object inspector you can simply wire methods from a class as commands to
34 public class ObjectInspector implements Serializable, Console.CommandProvider {
35 private static final long serialVersionUID = -5001688079827306472L;
36 private static final List<String> OBJECT_BLACKLIST = Arrays
37 .asList(new String[] { "equals", "class", "hashCode", "notify",
38 "notifyAll", "toString", "wait" });
39 private static final List<String> VAADIN_BLACKLIST = Arrays
40 .asList(new String[] { "addListener", "attach", "application",
41 "changeVariables", "childRequestedRepaint",
42 "componentError", "detach", "handleError", "paint",
43 "paintContent", "removeListener", "requestRepaint",
44 "requestRepaintRequests", "style", "tag" });
46 private Object theObject;
47 private final Map<String, Caller> commands = new HashMap<String, Caller>();
48 private Set<String> ignoredCommands = new HashSet<String>();
50 public ObjectInspector(final Object obj) {
53 ignoredCommands.addAll(OBJECT_BLACKLIST);
54 if (obj instanceof Component) {
55 ignoredCommands.addAll(VAADIN_BLACKLIST);
58 // Create bean information
63 private void setObject(final Object c) {
65 listBeanPropertyCommands();
69 public Set<String> getAvailableCommands() {
70 final List<String> l = new ArrayList<String>();
71 l.addAll(commands.keySet());
73 return new LinkedHashSet<String>(l);
78 private void listMethodCommands() {
80 final Method[] methods = theObject.getClass().getMethods();
81 for (final Method method : methods) {
82 final Method m = method;
83 if (!isBeanGetter(m) && !isBeanSetter(m)) {
85 String un = m.getName();
87 || !isParamTypesOkForConsole(m.getParameterTypes())) {
91 // Make unique. Try param names first.
92 if (commands.containsKey(un)) {
93 un += paramsToShortString(m.getParameterTypes());
96 // Fallback to appending number
98 while (commands.containsKey(un)) {
99 un = m.getName() + (j++);
102 final Caller cmd = m.getParameterTypes().length == 0 ? new Caller(theObject,
103 m.getName(), null, m.getParameterTypes()) : new Caller(theObject,
104 null, m.getName(), m.getParameterTypes());
105 commands.put(un, cmd);
110 private String paramsToShortString(final Class<?>[] parameterTypes) {
111 StringBuilder s = new StringBuilder();
112 if (parameterTypes != null) {
113 for (final Class<?> c : parameterTypes) {
114 s.append(c.getSimpleName().substring(0, 3));
120 private boolean isBeanSetter(final Method m) {
121 if (m.getName().startsWith("set")) {
122 Method setMethod = null;
124 final String n = "g" + m.getName().substring(1);
125 setMethod = m.getDeclaringClass().getMethod(n);
126 } catch (final SecurityException e) {
127 } catch (final NoSuchMethodException e) {
129 if (setMethod == null) {
131 final String n = "is" + m.getName().substring(3);
132 setMethod = m.getDeclaringClass().getMethod(n);
133 } catch (final SecurityException e) {
134 } catch (final NoSuchMethodException e) {
137 return setMethod != null;
142 private boolean isBeanGetter(final Method m) {
143 final String n = m.getName();
144 return (n.startsWith("is") && n.length() > 2)
145 || (n.startsWith("get") && n.length() > 2);
150 * Perform introspection on a Java Bean class to find its properties.
154 * Note : This version only supports introspectable bean properties and
155 * their getter and setter methods. Stand-alone <code>is</code> and
156 * <code>are</code> methods are not supported.
160 * the Java Bean class to get properties for.
161 * @return an ordered map from property names to property descriptors
163 static LinkedHashMap<String, PropertyDescriptor> getPropertyDescriptors(
164 final Class<?> beanClass) {
165 final LinkedHashMap<String, PropertyDescriptor> pdMap = new LinkedHashMap<String, PropertyDescriptor>();
167 // Try to introspect, if it fails, we just have an empty Item
169 final BeanInfo info = Introspector.getBeanInfo(beanClass);
170 final PropertyDescriptor[] pds = info.getPropertyDescriptors();
172 // Add all the bean properties as MethodProperties to this Item
173 for (final PropertyDescriptor pd : pds) {
174 final Method getMethod = pd.getReadMethod();
175 if ((getMethod != null)
176 && getMethod.getDeclaringClass() != Object.class) {
177 pdMap.put(pd.getName(), pd);
180 } catch (final java.beans.IntrospectionException ignored) {
187 * List commands for the theObject.
191 private void listBeanPropertyCommands() {
193 final LinkedHashMap<String, PropertyDescriptor> beanProperties = getPropertyDescriptors(theObject
196 for (final PropertyDescriptor p : beanProperties.values()) {
199 final String name = p.getName();
200 if (isIgnored(name)) {
205 new Caller(theObject,p.getReadMethod().getName(),
206 p.getWriteMethod() != null ? p.getWriteMethod()
208 p.getWriteMethod() != null ? p.getWriteMethod()
209 .getParameterTypes() : null));
211 // beanCommands.put(un, p);
215 public static boolean isParamTypesOkForConsole(final Class<?>[] cls) {
219 for (int i = 0; i < cls.length; i++) {
220 if (!isParamTypeOkForConsole(cls[i])) {
227 public static boolean isParamTypeOkForConsole(final Class<?> cls) {
228 return cls.isEnum() || cls == Boolean.class || cls == boolean.class
229 || cls == long.class || cls == Long.class || cls == int.class
230 || cls == Integer.class || cls == byte.class
231 || cls == Byte.class || cls == float.class
232 || cls == Float.class || cls == double.class
233 || cls == Double.class || cls == String.class;
236 public boolean isIgnored(final String commandName) {
237 return getIgnoredCommands().contains(commandName);
240 protected static Object[] argvToParams(final String[] argv,
241 final Class<?>[] pt) {
242 if (pt.length != argv.length - 1) {
243 throw new IllegalArgumentException("Invalid number of parameters");
245 final Object[] args = new Object[argv.length - 1];
246 for (int j = 1; j < argv.length; j++) {
247 if (pt[j - 1] == String.class) {
248 args[j - 1] = argv[j];
249 } else if (pt[j - 1] == Byte.class || pt[j - 1] == byte.class) {
250 args[j - 1] = Byte.parseByte(argv[j]);
251 } else if (pt[j - 1] == Character.class || pt[j - 1] == char.class) {
252 args[j - 1] = argv[j].charAt(0);
253 } else if (pt[j - 1] == Long.class || pt[j - 1] == long.class) {
254 args[j - 1] = Long.parseLong(argv[j]);
255 } else if (pt[j - 1] == Integer.class || pt[j - 1] == int.class) {
256 args[j - 1] = Integer.parseInt(argv[j]);
257 } else if (pt[j - 1] == Boolean.class || pt[j - 1] == boolean.class) {
258 args[j - 1] = Boolean.parseBoolean(argv[j]);
259 } else if (pt[j - 1] == Float.class || pt[j - 1] == float.class) {
260 args[j - 1] = Float.parseFloat(argv[j]);
261 } else if (pt[j - 1] == Double.class || pt[j - 1] == double.class) {
262 args[j - 1] = Float.parseFloat(argv[j]);
263 } else if (pt[j - 1].isEnum()) {
266 e = pt[j - 1].getDeclaredField(argv[j].toUpperCase());
267 args[j - 1] = e.get(null);
268 } catch (final Exception e1) {
269 throw new IllegalArgumentException("Enum not found: "
270 + argv[j].toUpperCase(), e1);
277 public Class<?>[] getCommandParams(final String method) {
278 if (commands.containsKey(method)) {
279 final Caller m = commands.get(method);
280 return m.getParameterTypes() != null ? m.getParameterTypes()
283 return new Class<?>[] {};
286 public void setIgnoredCommands(final Set<String> ignoredCommands) {
287 this.ignoredCommands = ignoredCommands;
290 public Set<String> getIgnoredCommands() {
291 return ignoredCommands;
295 * Method wrapper that serializes nicely.
298 private static class Caller implements Console.Command, Serializable {
300 private static final long serialVersionUID = -810707579200844512L;
302 private final Object theObject;
303 private final String readMethod;
304 private final String writeMethod;
305 private final Class<?>[] paramTypes;
307 transient private Method rm;
308 transient private Method wm;
310 private Caller(final Object obj, final String read, final String write,
311 final Class<?>[] params) {
318 private boolean isWritable() {
319 return writeMethod != null && paramTypes != null
320 && paramTypes.length > 0;
323 public boolean isReadable() {
324 return readMethod != null;
327 public Object write(final Object[] params) throws SecurityException,
328 NoSuchMethodException, IllegalArgumentException,
329 IllegalAccessException, InvocationTargetException {
331 wm = theObject.getClass().getMethod(writeMethod, paramTypes);
333 return wm.invoke(theObject, params);
336 public Object read() throws SecurityException, NoSuchMethodException,
337 IllegalArgumentException, IllegalAccessException,
338 InvocationTargetException {
340 rm = theObject.getClass().getMethod(readMethod,
343 return rm.invoke(theObject);
346 public Object write(final String[] argv) throws SecurityException,
347 NoSuchMethodException, IllegalArgumentException,
348 IllegalAccessException, InvocationTargetException {
349 return write(parseWriteParams(argv));
352 private Class<?>[] getParameterTypes() {
356 private Object[] parseWriteParams(final String[] argv)
357 throws SecurityException, NoSuchMethodException {
359 wm = theObject.getClass().getMethod(writeMethod, paramTypes);
361 return argvToParams(argv, wm.getParameterTypes());
364 public Object execute(final Console console, final String[] argv)
366 // public Object execute(final String[] argv) throws Exception {
368 if (argv == null || argv.length < 1) {
369 throw new IllegalArgumentException("Missing command");
373 && !isParamTypesOkForConsole(getParameterTypes())) {
374 throw new IllegalArgumentException("Unsupported parameter types");
377 if (argv.length == 1 && isReadable()) {
380 } else if (isWritable()) {
384 return read(); // Return the read method instead
386 return write(argv); // return whatever is returned
393 public String getUsage(final Console console, final String[] argv) {
398 public String getCommandUsage(final String[] argv) {
399 return argv[0] + " " + paramsToString(getCommandParams(argv[0]));
402 private static String paramsToString(final Class<?>[] paramTypes) {
403 StringBuilder res = new StringBuilder();
404 if (paramTypes != null) {
405 for (final Class<?> paramType : paramTypes) {
406 res.append("<" + paramType.getSimpleName() + "> ");
409 return res.toString();
412 public Set<String> getAvailableCommands(final Console console) {
413 return getAvailableCommands();
416 public Command getCommand(final Console console, final String commandName) {
417 return commands.get(commandName);