src/main/java/org/vaadin/console/ObjectInspector.java
changeset 0 c46bb04134cb
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/main/java/org/vaadin/console/ObjectInspector.java	Sun May 15 17:46:06 2011 +0400
     1.3 @@ -0,0 +1,420 @@
     1.4 +package org.vaadin.console;
     1.5 +
     1.6 +import java.beans.BeanInfo;
     1.7 +import java.beans.Introspector;
     1.8 +import java.beans.PropertyDescriptor;
     1.9 +import java.io.Serializable;
    1.10 +import java.lang.reflect.Field;
    1.11 +import java.lang.reflect.InvocationTargetException;
    1.12 +import java.lang.reflect.Method;
    1.13 +import java.util.ArrayList;
    1.14 +import java.util.Arrays;
    1.15 +import java.util.Collections;
    1.16 +import java.util.HashMap;
    1.17 +import java.util.HashSet;
    1.18 +import java.util.LinkedHashMap;
    1.19 +import java.util.LinkedHashSet;
    1.20 +import java.util.List;
    1.21 +import java.util.Map;
    1.22 +import java.util.Set;
    1.23 +
    1.24 +import org.vaadin.console.Console.Command;
    1.25 +
    1.26 +import com.vaadin.ui.Component;
    1.27 +
    1.28 +/**
    1.29 + * Java object inspector.
    1.30 + *
    1.31 + * With object inspector you can simply wire methods from a class as commands to
    1.32 + * the Console.
    1.33 + *
    1.34 + * @author Sami Ekblad
    1.35 + *
    1.36 + */
    1.37 +public class ObjectInspector implements Serializable, Console.CommandProvider {
    1.38 +    private static final long serialVersionUID = -5001688079827306472L;
    1.39 +    private static final List<String> OBJECT_BLACKLIST = Arrays
    1.40 +            .asList(new String[] { "equals", "class", "hashCode", "notify",
    1.41 +                    "notifyAll", "toString", "wait" });
    1.42 +    private static final List<String> VAADIN_BLACKLIST = Arrays
    1.43 +            .asList(new String[] { "addListener", "attach", "application",
    1.44 +                    "changeVariables", "childRequestedRepaint",
    1.45 +                    "componentError", "detach", "handleError", "paint",
    1.46 +                    "paintContent", "removeListener", "requestRepaint",
    1.47 +                    "requestRepaintRequests", "style", "tag" });
    1.48 +
    1.49 +    private Object theObject;
    1.50 +    private final Map<String, Caller> commands = new HashMap<String, Caller>();
    1.51 +    private Set<String> ignoredCommands = new HashSet<String>();
    1.52 +
    1.53 +    public ObjectInspector(final Object obj) {
    1.54 +
    1.55 +        // Default ignores
    1.56 +        ignoredCommands.addAll(OBJECT_BLACKLIST);
    1.57 +        if (obj instanceof Component) {
    1.58 +            ignoredCommands.addAll(VAADIN_BLACKLIST);
    1.59 +        }
    1.60 +
    1.61 +        // Create bean information
    1.62 +        setObject(obj);
    1.63 +
    1.64 +    }
    1.65 +
    1.66 +    private void setObject(final Object c) {
    1.67 +        theObject = c;
    1.68 +        listBeanPropertyCommands();
    1.69 +        listMethodCommands();
    1.70 +    }
    1.71 +
    1.72 +    public Set<String> getAvailableCommands() {
    1.73 +        final List<String> l = new ArrayList<String>();
    1.74 +        l.addAll(commands.keySet());
    1.75 +        Collections.sort(l);
    1.76 +        return new LinkedHashSet<String>(l);
    1.77 +    }
    1.78 +
    1.79 +
    1.80 +
    1.81 +    private void listMethodCommands() {
    1.82 +
    1.83 +        final Method[] methods = theObject.getClass().getMethods();
    1.84 +        for (final Method method : methods) {
    1.85 +            final Method m = method;
    1.86 +            if (!isBeanGetter(m) && !isBeanSetter(m)) {
    1.87 +
    1.88 +                String un = m.getName();
    1.89 +                if (isIgnored(un)
    1.90 +                        || !isParamTypesOkForConsole(m.getParameterTypes())) {
    1.91 +                    continue;
    1.92 +                }
    1.93 +
    1.94 +                // Make unique. Try param names first.
    1.95 +                if (commands.containsKey(un)) {
    1.96 +                    un += paramsToShortString(m.getParameterTypes());
    1.97 +                }
    1.98 +
    1.99 +                // Fallback to appending number
   1.100 +                int j = 1;
   1.101 +                while (commands.containsKey(un)) {
   1.102 +                    un = m.getName() + (j++);
   1.103 +                }
   1.104 +
   1.105 +                final Caller cmd = m.getParameterTypes().length == 0 ? new Caller(theObject,
   1.106 +                        m.getName(), null, m.getParameterTypes()) : new Caller(theObject,
   1.107 +                        null, m.getName(), m.getParameterTypes());
   1.108 +                commands.put(un, cmd);
   1.109 +            }
   1.110 +        }
   1.111 +    }
   1.112 +
   1.113 +    private String paramsToShortString(final Class<?>[] parameterTypes) {
   1.114 +        StringBuilder s = new StringBuilder();
   1.115 +        if (parameterTypes != null) {
   1.116 +            for (final Class<?> c : parameterTypes) {
   1.117 +                s.append(c.getSimpleName().substring(0, 3));
   1.118 +            }
   1.119 +        }
   1.120 +        return s.toString();
   1.121 +    }
   1.122 +
   1.123 +    private boolean isBeanSetter(final Method m) {
   1.124 +        if (m.getName().startsWith("set")) {
   1.125 +            Method setMethod = null;
   1.126 +            try {
   1.127 +                final String n = "g" + m.getName().substring(1);
   1.128 +                setMethod = m.getDeclaringClass().getMethod(n);
   1.129 +            } catch (final SecurityException e) {
   1.130 +            } catch (final NoSuchMethodException e) {
   1.131 +            }
   1.132 +            if (setMethod == null) {
   1.133 +                try {
   1.134 +                    final String n = "is" + m.getName().substring(3);
   1.135 +                    setMethod = m.getDeclaringClass().getMethod(n);
   1.136 +                } catch (final SecurityException e) {
   1.137 +                } catch (final NoSuchMethodException e) {
   1.138 +                }
   1.139 +            }
   1.140 +            return setMethod != null;
   1.141 +        }
   1.142 +        return false;
   1.143 +    }
   1.144 +
   1.145 +    private boolean isBeanGetter(final Method m) {
   1.146 +        final String n = m.getName();
   1.147 +        return (n.startsWith("is") && n.length() > 2)
   1.148 +                || (n.startsWith("get") && n.length() > 2);
   1.149 +    }
   1.150 +
   1.151 +    /**
   1.152 +     * <p>
   1.153 +     * Perform introspection on a Java Bean class to find its properties.
   1.154 +     * </p>
   1.155 +     *
   1.156 +     * <p>
   1.157 +     * Note : This version only supports introspectable bean properties and
   1.158 +     * their getter and setter methods. Stand-alone <code>is</code> and
   1.159 +     * <code>are</code> methods are not supported.
   1.160 +     * </p>
   1.161 +     *
   1.162 +     * @param beanClass
   1.163 +     *            the Java Bean class to get properties for.
   1.164 +     * @return an ordered map from property names to property descriptors
   1.165 +     */
   1.166 +    static LinkedHashMap<String, PropertyDescriptor> getPropertyDescriptors(
   1.167 +            final Class<?> beanClass) {
   1.168 +        final LinkedHashMap<String, PropertyDescriptor> pdMap = new LinkedHashMap<String, PropertyDescriptor>();
   1.169 +
   1.170 +        // Try to introspect, if it fails, we just have an empty Item
   1.171 +        try {
   1.172 +            final BeanInfo info = Introspector.getBeanInfo(beanClass);
   1.173 +            final PropertyDescriptor[] pds = info.getPropertyDescriptors();
   1.174 +
   1.175 +            // Add all the bean properties as MethodProperties to this Item
   1.176 +            for (final PropertyDescriptor pd : pds) {
   1.177 +                final Method getMethod = pd.getReadMethod();
   1.178 +                if ((getMethod != null)
   1.179 +                        && getMethod.getDeclaringClass() != Object.class) {
   1.180 +                    pdMap.put(pd.getName(), pd);
   1.181 +                }
   1.182 +            }
   1.183 +        } catch (final java.beans.IntrospectionException ignored) {
   1.184 +        }
   1.185 +
   1.186 +        return pdMap;
   1.187 +    }
   1.188 +
   1.189 +    /**
   1.190 +     * List commands for the theObject.
   1.191 +     *
   1.192 +     * @return
   1.193 +     */
   1.194 +    private void listBeanPropertyCommands() {
   1.195 +
   1.196 +        final LinkedHashMap<String, PropertyDescriptor> beanProperties = getPropertyDescriptors(theObject
   1.197 +                .getClass());
   1.198 +        // bean properties
   1.199 +        for (final PropertyDescriptor p : beanProperties.values()) {
   1.200 +
   1.201 +            // Make unique
   1.202 +            final String name = p.getName();
   1.203 +            if (isIgnored(name)) {
   1.204 +                continue;
   1.205 +            }
   1.206 +
   1.207 +            commands.put(name,
   1.208 +                    new Caller(theObject,p.getReadMethod().getName(),
   1.209 +                            p.getWriteMethod() != null ? p.getWriteMethod()
   1.210 +                                    .getName() : null,
   1.211 +                            p.getWriteMethod() != null ? p.getWriteMethod()
   1.212 +                                    .getParameterTypes() : null));
   1.213 +
   1.214 +            // beanCommands.put(un, p);
   1.215 +        }
   1.216 +    }
   1.217 +
   1.218 +    public static boolean isParamTypesOkForConsole(final Class<?>[] cls) {
   1.219 +        if (cls == null) {
   1.220 +            return true;
   1.221 +        }
   1.222 +        for (int i = 0; i < cls.length; i++) {
   1.223 +            if (!isParamTypeOkForConsole(cls[i])) {
   1.224 +                return false;
   1.225 +            }
   1.226 +        }
   1.227 +        return true;
   1.228 +    }
   1.229 +
   1.230 +    public static boolean isParamTypeOkForConsole(final Class<?> cls) {
   1.231 +        return cls.isEnum() || cls == Boolean.class || cls == boolean.class
   1.232 +                || cls == long.class || cls == Long.class || cls == int.class
   1.233 +                || cls == Integer.class || cls == byte.class
   1.234 +                || cls == Byte.class || cls == float.class
   1.235 +                || cls == Float.class || cls == double.class
   1.236 +                || cls == Double.class || cls == String.class;
   1.237 +    }
   1.238 +
   1.239 +    public boolean isIgnored(final String commandName) {
   1.240 +        return getIgnoredCommands().contains(commandName);
   1.241 +    }
   1.242 +
   1.243 +    protected static Object[] argvToParams(final String[] argv,
   1.244 +            final Class<?>[] pt) {
   1.245 +        if (pt.length != argv.length - 1) {
   1.246 +            throw new IllegalArgumentException("Invalid number of parameters");
   1.247 +        }
   1.248 +        final Object[] args = new Object[argv.length - 1];
   1.249 +        for (int j = 1; j < argv.length; j++) {
   1.250 +            if (pt[j - 1] == String.class) {
   1.251 +                args[j - 1] = argv[j];
   1.252 +            } else if (pt[j - 1] == Byte.class || pt[j - 1] == byte.class) {
   1.253 +                args[j - 1] = Byte.parseByte(argv[j]);
   1.254 +            } else if (pt[j - 1] == Character.class || pt[j - 1] == char.class) {
   1.255 +                args[j - 1] = argv[j].charAt(0);
   1.256 +            } else if (pt[j - 1] == Long.class || pt[j - 1] == long.class) {
   1.257 +                args[j - 1] = Long.parseLong(argv[j]);
   1.258 +            } else if (pt[j - 1] == Integer.class || pt[j - 1] == int.class) {
   1.259 +                args[j - 1] = Integer.parseInt(argv[j]);
   1.260 +            } else if (pt[j - 1] == Boolean.class || pt[j - 1] == boolean.class) {
   1.261 +                args[j - 1] = Boolean.parseBoolean(argv[j]);
   1.262 +            } else if (pt[j - 1] == Float.class || pt[j - 1] == float.class) {
   1.263 +                args[j - 1] = Float.parseFloat(argv[j]);
   1.264 +            } else if (pt[j - 1] == Double.class || pt[j - 1] == double.class) {
   1.265 +                args[j - 1] = Float.parseFloat(argv[j]);
   1.266 +            } else if (pt[j - 1].isEnum()) {
   1.267 +                Field e;
   1.268 +                try {
   1.269 +                    e = pt[j - 1].getDeclaredField(argv[j].toUpperCase());
   1.270 +                    args[j - 1] = e.get(null);
   1.271 +                } catch (final Exception e1) {
   1.272 +                    throw new IllegalArgumentException("Enum not found: "
   1.273 +                            + argv[j].toUpperCase(), e1);
   1.274 +                }
   1.275 +            }
   1.276 +        }
   1.277 +        return args;
   1.278 +    }
   1.279 +
   1.280 +    public Class<?>[] getCommandParams(final String method) {
   1.281 +        if (commands.containsKey(method)) {
   1.282 +            final Caller m = commands.get(method);
   1.283 +            return m.getParameterTypes() != null ? m.getParameterTypes()
   1.284 +                    : new Class<?>[] {};
   1.285 +        }
   1.286 +        return new Class<?>[] {};
   1.287 +    }
   1.288 +
   1.289 +    public void setIgnoredCommands(final Set<String> ignoredCommands) {
   1.290 +        this.ignoredCommands = ignoredCommands;
   1.291 +    }
   1.292 +
   1.293 +    public Set<String> getIgnoredCommands() {
   1.294 +        return ignoredCommands;
   1.295 +    }
   1.296 +
   1.297 +    /**
   1.298 +     * Method wrapper that serializes nicely.
   1.299 +     *
   1.300 +     */
   1.301 +    private static class Caller implements Console.Command, Serializable {
   1.302 +
   1.303 +        private static final long serialVersionUID = -810707579200844512L;
   1.304 +
   1.305 +        private final Object theObject;
   1.306 +        private final String readMethod;
   1.307 +        private final String writeMethod;
   1.308 +        private final Class<?>[] paramTypes;
   1.309 +
   1.310 +        transient private Method rm;
   1.311 +        transient private Method wm;
   1.312 +
   1.313 +        private Caller(final Object obj, final String read, final String write,
   1.314 +                final Class<?>[] params) {
   1.315 +            theObject = obj;
   1.316 +            readMethod = read;
   1.317 +            writeMethod = write;
   1.318 +            paramTypes = params;
   1.319 +        }
   1.320 +
   1.321 +        private boolean isWritable() {
   1.322 +            return writeMethod != null && paramTypes != null
   1.323 +                    && paramTypes.length > 0;
   1.324 +        }
   1.325 +
   1.326 +        public boolean isReadable() {
   1.327 +            return readMethod != null;
   1.328 +        }
   1.329 +
   1.330 +        public Object write(final Object[] params) throws SecurityException,
   1.331 +                NoSuchMethodException, IllegalArgumentException,
   1.332 +                IllegalAccessException, InvocationTargetException {
   1.333 +            if (wm == null) {
   1.334 +                wm = theObject.getClass().getMethod(writeMethod, paramTypes);
   1.335 +            }
   1.336 +            return wm.invoke(theObject, params);
   1.337 +        }
   1.338 +
   1.339 +        public Object read() throws SecurityException, NoSuchMethodException,
   1.340 +                IllegalArgumentException, IllegalAccessException,
   1.341 +                InvocationTargetException {
   1.342 +            if (rm == null) {
   1.343 +                rm = theObject.getClass().getMethod(readMethod,
   1.344 +                        new Class<?>[] {});
   1.345 +            }
   1.346 +            return rm.invoke(theObject);
   1.347 +        }
   1.348 +
   1.349 +        public Object write(final String[] argv) throws SecurityException,
   1.350 +                NoSuchMethodException, IllegalArgumentException,
   1.351 +                IllegalAccessException, InvocationTargetException {
   1.352 +            return write(parseWriteParams(argv));
   1.353 +        }
   1.354 +
   1.355 +        private Class<?>[] getParameterTypes() {
   1.356 +            return paramTypes;
   1.357 +        }
   1.358 +
   1.359 +        private Object[] parseWriteParams(final String[] argv)
   1.360 +                throws SecurityException, NoSuchMethodException {
   1.361 +            if (wm == null) {
   1.362 +                wm = theObject.getClass().getMethod(writeMethod, paramTypes);
   1.363 +            }
   1.364 +            return argvToParams(argv, wm.getParameterTypes());
   1.365 +        }
   1.366 +
   1.367 +        public Object execute(final Console console, final String[] argv)
   1.368 +                throws Exception {
   1.369 +//            public Object execute(final String[] argv) throws Exception {
   1.370 +
   1.371 +                if (argv == null || argv.length < 1) {
   1.372 +                    throw new IllegalArgumentException("Missing command");
   1.373 +                }
   1.374 +
   1.375 +                if (argv.length > 1
   1.376 +                        && !isParamTypesOkForConsole(getParameterTypes())) {
   1.377 +                    throw new IllegalArgumentException("Unsupported parameter types");
   1.378 +                }
   1.379 +
   1.380 +                if (argv.length == 1 && isReadable()) {
   1.381 +                    // Read
   1.382 +                    return read();
   1.383 +                } else if (isWritable()) {
   1.384 +                    // Write
   1.385 +                    if (isReadable()) {
   1.386 +                        write(argv);
   1.387 +                        return read(); // Return the read method instead
   1.388 +                    } else {
   1.389 +                        return write(argv); // return whatever is returned
   1.390 +                    }
   1.391 +
   1.392 +                }
   1.393 +
   1.394 +                return null;
   1.395 +            }
   1.396 +        public String getUsage(final Console console, final String[] argv) {
   1.397 +            return null;
   1.398 +        }
   1.399 +    }
   1.400 +
   1.401 +    public String getCommandUsage(final String[] argv) {
   1.402 +        return argv[0] + " " + paramsToString(getCommandParams(argv[0]));
   1.403 +    }
   1.404 +
   1.405 +    private static String paramsToString(final Class<?>[] paramTypes) {
   1.406 +        StringBuilder res = new StringBuilder();
   1.407 +        if (paramTypes != null) {
   1.408 +            for (final Class<?> paramType : paramTypes) {
   1.409 +                res.append("<" + paramType.getSimpleName() + "> ");
   1.410 +            }
   1.411 +        }
   1.412 +        return res.toString();
   1.413 +    }
   1.414 +
   1.415 +    public Set<String> getAvailableCommands(final Console console) {
   1.416 +        return getAvailableCommands();
   1.417 +    }
   1.418 +
   1.419 +    public Command getCommand(final Console console, final String commandName) {
   1.420 +        return commands.get(commandName);
   1.421 +    }
   1.422 +
   1.423 +}