src/main/java/org/vaadin/console/ObjectInspector.java
author indvdum
Wed, 07 Sep 2011 13:43:13 +0300
changeset 20 f927e5a4ccba
parent 0 c46bb04134cb
permissions -rw-r--r--
vaadin versions
     1 package org.vaadin.console;
     2 
     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;
    18 import java.util.Map;
    19 import java.util.Set;
    20 
    21 import org.vaadin.console.Console.Command;
    22 
    23 import com.vaadin.ui.Component;
    24 
    25 /**
    26  * Java object inspector.
    27  *
    28  * With object inspector you can simply wire methods from a class as commands to
    29  * the Console.
    30  *
    31  * @author Sami Ekblad
    32  *
    33  */
    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" });
    45 
    46     private Object theObject;
    47     private final Map<String, Caller> commands = new HashMap<String, Caller>();
    48     private Set<String> ignoredCommands = new HashSet<String>();
    49 
    50     public ObjectInspector(final Object obj) {
    51 
    52         // Default ignores
    53         ignoredCommands.addAll(OBJECT_BLACKLIST);
    54         if (obj instanceof Component) {
    55             ignoredCommands.addAll(VAADIN_BLACKLIST);
    56         }
    57 
    58         // Create bean information
    59         setObject(obj);
    60 
    61     }
    62 
    63     private void setObject(final Object c) {
    64         theObject = c;
    65         listBeanPropertyCommands();
    66         listMethodCommands();
    67     }
    68 
    69     public Set<String> getAvailableCommands() {
    70         final List<String> l = new ArrayList<String>();
    71         l.addAll(commands.keySet());
    72         Collections.sort(l);
    73         return new LinkedHashSet<String>(l);
    74     }
    75 
    76 
    77 
    78     private void listMethodCommands() {
    79 
    80         final Method[] methods = theObject.getClass().getMethods();
    81         for (final Method method : methods) {
    82             final Method m = method;
    83             if (!isBeanGetter(m) && !isBeanSetter(m)) {
    84 
    85                 String un = m.getName();
    86                 if (isIgnored(un)
    87                         || !isParamTypesOkForConsole(m.getParameterTypes())) {
    88                     continue;
    89                 }
    90 
    91                 // Make unique. Try param names first.
    92                 if (commands.containsKey(un)) {
    93                     un += paramsToShortString(m.getParameterTypes());
    94                 }
    95 
    96                 // Fallback to appending number
    97                 int j = 1;
    98                 while (commands.containsKey(un)) {
    99                     un = m.getName() + (j++);
   100                 }
   101 
   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);
   106             }
   107         }
   108     }
   109 
   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));
   115             }
   116         }
   117         return s.toString();
   118     }
   119 
   120     private boolean isBeanSetter(final Method m) {
   121         if (m.getName().startsWith("set")) {
   122             Method setMethod = null;
   123             try {
   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) {
   128             }
   129             if (setMethod == null) {
   130                 try {
   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) {
   135                 }
   136             }
   137             return setMethod != null;
   138         }
   139         return false;
   140     }
   141 
   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);
   146     }
   147 
   148     /**
   149      * <p>
   150      * Perform introspection on a Java Bean class to find its properties.
   151      * </p>
   152      *
   153      * <p>
   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.
   157      * </p>
   158      *
   159      * @param beanClass
   160      *            the Java Bean class to get properties for.
   161      * @return an ordered map from property names to property descriptors
   162      */
   163     static LinkedHashMap<String, PropertyDescriptor> getPropertyDescriptors(
   164             final Class<?> beanClass) {
   165         final LinkedHashMap<String, PropertyDescriptor> pdMap = new LinkedHashMap<String, PropertyDescriptor>();
   166 
   167         // Try to introspect, if it fails, we just have an empty Item
   168         try {
   169             final BeanInfo info = Introspector.getBeanInfo(beanClass);
   170             final PropertyDescriptor[] pds = info.getPropertyDescriptors();
   171 
   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);
   178                 }
   179             }
   180         } catch (final java.beans.IntrospectionException ignored) {
   181         }
   182 
   183         return pdMap;
   184     }
   185 
   186     /**
   187      * List commands for the theObject.
   188      *
   189      * @return
   190      */
   191     private void listBeanPropertyCommands() {
   192 
   193         final LinkedHashMap<String, PropertyDescriptor> beanProperties = getPropertyDescriptors(theObject
   194                 .getClass());
   195         // bean properties
   196         for (final PropertyDescriptor p : beanProperties.values()) {
   197 
   198             // Make unique
   199             final String name = p.getName();
   200             if (isIgnored(name)) {
   201                 continue;
   202             }
   203 
   204             commands.put(name,
   205                     new Caller(theObject,p.getReadMethod().getName(),
   206                             p.getWriteMethod() != null ? p.getWriteMethod()
   207                                     .getName() : null,
   208                             p.getWriteMethod() != null ? p.getWriteMethod()
   209                                     .getParameterTypes() : null));
   210 
   211             // beanCommands.put(un, p);
   212         }
   213     }
   214 
   215     public static boolean isParamTypesOkForConsole(final Class<?>[] cls) {
   216         if (cls == null) {
   217             return true;
   218         }
   219         for (int i = 0; i < cls.length; i++) {
   220             if (!isParamTypeOkForConsole(cls[i])) {
   221                 return false;
   222             }
   223         }
   224         return true;
   225     }
   226 
   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;
   234     }
   235 
   236     public boolean isIgnored(final String commandName) {
   237         return getIgnoredCommands().contains(commandName);
   238     }
   239 
   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");
   244         }
   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()) {
   264                 Field e;
   265                 try {
   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);
   271                 }
   272             }
   273         }
   274         return args;
   275     }
   276 
   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()
   281                     : new Class<?>[] {};
   282         }
   283         return new Class<?>[] {};
   284     }
   285 
   286     public void setIgnoredCommands(final Set<String> ignoredCommands) {
   287         this.ignoredCommands = ignoredCommands;
   288     }
   289 
   290     public Set<String> getIgnoredCommands() {
   291         return ignoredCommands;
   292     }
   293 
   294     /**
   295      * Method wrapper that serializes nicely.
   296      *
   297      */
   298     private static class Caller implements Console.Command, Serializable {
   299 
   300         private static final long serialVersionUID = -810707579200844512L;
   301 
   302         private final Object theObject;
   303         private final String readMethod;
   304         private final String writeMethod;
   305         private final Class<?>[] paramTypes;
   306 
   307         transient private Method rm;
   308         transient private Method wm;
   309 
   310         private Caller(final Object obj, final String read, final String write,
   311                 final Class<?>[] params) {
   312             theObject = obj;
   313             readMethod = read;
   314             writeMethod = write;
   315             paramTypes = params;
   316         }
   317 
   318         private boolean isWritable() {
   319             return writeMethod != null && paramTypes != null
   320                     && paramTypes.length > 0;
   321         }
   322 
   323         public boolean isReadable() {
   324             return readMethod != null;
   325         }
   326 
   327         public Object write(final Object[] params) throws SecurityException,
   328                 NoSuchMethodException, IllegalArgumentException,
   329                 IllegalAccessException, InvocationTargetException {
   330             if (wm == null) {
   331                 wm = theObject.getClass().getMethod(writeMethod, paramTypes);
   332             }
   333             return wm.invoke(theObject, params);
   334         }
   335 
   336         public Object read() throws SecurityException, NoSuchMethodException,
   337                 IllegalArgumentException, IllegalAccessException,
   338                 InvocationTargetException {
   339             if (rm == null) {
   340                 rm = theObject.getClass().getMethod(readMethod,
   341                         new Class<?>[] {});
   342             }
   343             return rm.invoke(theObject);
   344         }
   345 
   346         public Object write(final String[] argv) throws SecurityException,
   347                 NoSuchMethodException, IllegalArgumentException,
   348                 IllegalAccessException, InvocationTargetException {
   349             return write(parseWriteParams(argv));
   350         }
   351 
   352         private Class<?>[] getParameterTypes() {
   353             return paramTypes;
   354         }
   355 
   356         private Object[] parseWriteParams(final String[] argv)
   357                 throws SecurityException, NoSuchMethodException {
   358             if (wm == null) {
   359                 wm = theObject.getClass().getMethod(writeMethod, paramTypes);
   360             }
   361             return argvToParams(argv, wm.getParameterTypes());
   362         }
   363 
   364         public Object execute(final Console console, final String[] argv)
   365                 throws Exception {
   366 //            public Object execute(final String[] argv) throws Exception {
   367 
   368                 if (argv == null || argv.length < 1) {
   369                     throw new IllegalArgumentException("Missing command");
   370                 }
   371 
   372                 if (argv.length > 1
   373                         && !isParamTypesOkForConsole(getParameterTypes())) {
   374                     throw new IllegalArgumentException("Unsupported parameter types");
   375                 }
   376 
   377                 if (argv.length == 1 && isReadable()) {
   378                     // Read
   379                     return read();
   380                 } else if (isWritable()) {
   381                     // Write
   382                     if (isReadable()) {
   383                         write(argv);
   384                         return read(); // Return the read method instead
   385                     } else {
   386                         return write(argv); // return whatever is returned
   387                     }
   388 
   389                 }
   390 
   391                 return null;
   392             }
   393         public String getUsage(final Console console, final String[] argv) {
   394             return null;
   395         }
   396     }
   397 
   398     public String getCommandUsage(final String[] argv) {
   399         return argv[0] + " " + paramsToString(getCommandParams(argv[0]));
   400     }
   401 
   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() + "> ");
   407             }
   408         }
   409         return res.toString();
   410     }
   411 
   412     public Set<String> getAvailableCommands(final Console console) {
   413         return getAvailableCommands();
   414     }
   415 
   416     public Command getCommand(final Console console, final String commandName) {
   417         return commands.get(commandName);
   418     }
   419 
   420 }