Search in sources :

Example 51 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project OpenGrok by OpenGrok.

the class ClassUtil method invokeGetter.

/**
 * Invokes a getter of a property on an object.
 *
 * @param obj the object
 * @param field string with field name
 * @return string representation of the field value
 * @throws java.io.IOException exception
 */
public static String invokeGetter(Object obj, String field) throws IOException {
    String val = null;
    try {
        PropertyDescriptor desc = new PropertyDescriptor(field, obj.getClass());
        Method getter = desc.getReadMethod();
        if (getter == null) {
            throw new IOException(String.format("No getter for the name \"%s\".", field));
        }
        if (getter.getParameterCount() != 0) {
            /**
             * Actually should not happen as it is not considered as a
             * read method so an exception would be thrown earlier.
             */
            throw new IOException(String.format("The getter \"%s\" for the name \"%s\" takes a parameter.", getter.getName(), field));
        }
        val = getter.invoke(obj).toString();
    } catch (IntrospectionException | IllegalAccessException | InvocationTargetException | IllegalArgumentException ex) {
        throw new IOException(String.format("Unsupported operation with object of class %s for name \"%s\" - %s.", obj.getClass().toString(), field, ex.getCause() == null ? ex.getLocalizedMessage() : ex.getCause().getLocalizedMessage()), ex);
    }
    return val;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) IntrospectionException(java.beans.IntrospectionException) Method(java.lang.reflect.Method) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 52 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project OpenGrok by OpenGrok.

the class ClassUtil method invokeSetter.

/**
 * Invokes a setter on an object and passes a value to that setter.
 *
 * The value is passed as string and the function will automatically try to
 * convert it to the parameter type in the setter. These conversion are
 * available only for
 * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">java
 * primitive datatypes</a>:
 * <ul>
 * <li>Boolean or boolean</li>
 * <li>Short or short</li>
 * <li>Integer or integer</li>
 * <li>Long or long</li>
 * <li>Float or float</li>
 * <li>Double or double</li>
 * <li>Byte or byte</li>
 * <li>Character or char</li>
 * <li>String</li>
 * </ul>
 * Any other parameter type will cause an exception.
 *
 * @param obj the object
 * @param field name of the field which will be changed
 * @param value desired value
 *
 * @throws IOException if any error occurs (no suitable method, bad
 * conversion, ...)
 */
public static void invokeSetter(Object obj, String field, String value) throws IOException {
    try {
        PropertyDescriptor desc = new PropertyDescriptor(field, obj.getClass());
        Method setter = desc.getWriteMethod();
        if (setter == null) {
            throw new IOException(String.format("No setter for the name \"%s\".", field));
        }
        if (setter.getParameterCount() != 1) {
            /**
             * Actually should not happen as it is not considered as a
             * writer method so an exception would be thrown earlier.
             */
            throw new IOException(String.format("The setter \"%s\" for the name \"%s\" does not take exactly 1 parameter.", setter.getName(), field));
        }
        Class c = setter.getParameterTypes()[0];
        String paramClass = c.getName();
        /**
         * Java primitive types as per
         * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">java
         * datatypes</a>.
         */
        if (paramClass.equals("boolean") || paramClass.equals(Boolean.class.getName())) {
            if (!BooleanUtil.isBoolean(value)) {
                throw new IOException(String.format("Unsupported type conversion from String to a boolean for name \"%s\" -" + " got \"%s\" - allowed values are [false, off, 0, true, on, 1].", field, value));
            }
            Boolean v = Boolean.valueOf(value);
            if (!v) {
                /**
                 * The Boolean.valueOf() returns true only for "true" case
                 * insensitive so now we have either the false values or
                 * "on" or "1". These are convenient shortcuts for "on", "1"
                 * to be interpreted as booleans.
                 */
                v = v || value.equalsIgnoreCase("on");
                v = v || value.equals("1");
            }
            setter.invoke(obj, v);
        } else if (paramClass.equals("short") || paramClass.equals(Short.class.getName())) {
            setter.invoke(obj, Short.valueOf(value));
        } else if (paramClass.equals("int") || paramClass.equals(Integer.class.getName())) {
            setter.invoke(obj, Integer.valueOf(value));
        } else if (paramClass.equals("long") || paramClass.equals(Long.class.getName())) {
            setter.invoke(obj, Long.valueOf(value));
        } else if (paramClass.equals("float") || paramClass.equals(Float.class.getName())) {
            setter.invoke(obj, Float.valueOf(value));
        } else if (paramClass.equals("double") || paramClass.equals(Double.class.getName())) {
            setter.invoke(obj, Double.valueOf(value));
        } else if (paramClass.equals("byte") || paramClass.equals(Byte.class.getName())) {
            setter.invoke(obj, Byte.valueOf(value));
        } else if (paramClass.equals("char") || paramClass.equals(Character.class.getName())) {
            setter.invoke(obj, value.charAt(0));
        } else if (paramClass.equals(String.class.getName())) {
            setter.invoke(obj, value);
        } else {
            // error unknown type
            throw new IOException(String.format("Unsupported type conversion for the name \"%s\". Expecting \"%s\".", field, paramClass));
        }
    } catch (NumberFormatException ex) {
        throw new IOException(String.format("Unsupported type conversion from String to a number for name \"%s\" - %s.", field, ex.getLocalizedMessage()), ex);
    } catch (IndexOutOfBoundsException ex) {
        throw new IOException(String.format("The string is not long enough to extract 1 character for name \"%s\" - %s.", field, ex.getLocalizedMessage()), ex);
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | /**
     * This the case when the invocation failed because the invoked
     * method failed with an exception. All exceptions are
     * propagated through this exception.
     */
    InvocationTargetException ex) {
        throw new IOException(String.format("Unsupported operation with object of class %s for name \"%s\" - %s.", obj.getClass().toString(), field, ex.getCause() == null ? ex.getLocalizedMessage() : ex.getCause().getLocalizedMessage()), ex);
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) IntrospectionException(java.beans.IntrospectionException) Method(java.lang.reflect.Method) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 53 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project OpenGrok by OpenGrok.

the class ConfigMerge method merge.

/**
 * Merge base and new configuration.
 * @param cfgBase base configuration
 * @param cfgNew new configuration, will receive properties from the base configuration
 * @throws Exception exception
 */
public static void merge(Configuration cfgBase, Configuration cfgNew) throws Exception {
    Configuration cfgDefault = new Configuration();
    // from cfgBase that are not of default value and set them to cfgNew.
    for (Field field : cfgBase.getClass().getDeclaredFields()) {
        String fieldName = field.getName();
        int modifiers = field.getModifiers();
        if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers) || Modifier.isFinal(modifiers)) {
            continue;
        }
        PropertyDescriptor desc = null;
        try {
            desc = new PropertyDescriptor(fieldName, Configuration.class);
        } catch (IntrospectionException ex) {
            throw new Exception("cannot get property descriptor for '" + fieldName + "'");
        }
        Method setter = desc.getWriteMethod();
        if (setter == null) {
            throw new Exception("no setter for '" + fieldName + "'");
        }
        Method getter = desc.getReadMethod();
        if (getter == null) {
            throw new Exception("no getter for '" + fieldName + "'");
        }
        try {
            Object obj = getter.invoke(cfgBase);
            if ((obj == null && getter.invoke(cfgDefault) == null) || obj.equals(getter.invoke(cfgDefault))) {
                continue;
            }
        } catch (Exception ex) {
            throw new Exception("failed to invoke getter for " + fieldName + ": " + ex);
        }
        try {
            setter.invoke(cfgNew, getter.invoke(cfgBase));
        } catch (Exception ex) {
            throw new Exception("failed to invoke setter for '" + fieldName + "'");
        }
    }
}
Also used : Field(java.lang.reflect.Field) PropertyDescriptor(java.beans.PropertyDescriptor) IntrospectionException(java.beans.IntrospectionException) Method(java.lang.reflect.Method) IOException(java.io.IOException) ParseException(java.text.ParseException) IntrospectionException(java.beans.IntrospectionException)

Example 54 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project yamcs-studio by yamcs.

the class DefaultWidgetIntrospector method getBeanInfo.

public BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException {
    Introspector.flushFromCaches(beanClass);
    BeanInfo bi = Introspector.getBeanInfo(beanClass);
    BeanDescriptor bd = bi.getBeanDescriptor();
    MethodDescriptor[] mds = bi.getMethodDescriptors();
    EventSetDescriptor[] esds = bi.getEventSetDescriptors();
    PropertyDescriptor[] pds = bi.getPropertyDescriptors();
    List<PropertyDescriptor> filteredPDList = new ArrayList<PropertyDescriptor>();
    List<String> nonPropList = Arrays.asList(getNonProperties());
    for (PropertyDescriptor pd : pds) {
        if (!nonPropList.contains(pd.getName()) && pd.getWriteMethod() != null && pd.getReadMethod() != null)
            filteredPDList.add(pd);
    }
    int defaultEvent = bi.getDefaultEventIndex();
    int defaultProperty = bi.getDefaultPropertyIndex();
    return new GenericBeanInfo(bd, esds, defaultEvent, filteredPDList.toArray(new PropertyDescriptor[filteredPDList.size()]), defaultProperty, mds, null);
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) ArrayList(java.util.ArrayList) MethodDescriptor(java.beans.MethodDescriptor) EventSetDescriptor(java.beans.EventSetDescriptor) BeanDescriptor(java.beans.BeanDescriptor)

Example 55 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project JWildfire by thargor6.

the class Action method importProperties.

public void importProperties(ManagedObject pManagedObject) {
    BeanInfo beanInfo = pManagedObject.getBeanInfo();
    if (beanInfo != null) {
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        if (props != null) {
            for (PropertyDescriptor prop : props) {
                Method readMethod = prop.getReadMethod();
                if (readMethod != null) {
                    try {
                        Object val = readMethod.invoke(pManagedObject);
                        Class<?> cls = prop.getPropertyType();
                        if (cls == Color.class) {
                            Color color = (Color) val;
                            String name = prop.getName();
                            Parameter param;
                            param = new Parameter();
                            parameterList.add(param);
                            param.setName(name + ".r");
                            param.setValue(color != null ? String.valueOf(color.getRed()) : null);
                            param = new Parameter();
                            parameterList.add(param);
                            param.setName(name + ".g");
                            param.setValue(color != null ? String.valueOf(color.getGreen()) : null);
                            param = new Parameter();
                            parameterList.add(param);
                            param.setName(name + ".b");
                            param.setValue(color != null ? String.valueOf(color.getBlue()) : null);
                        } else {
                            Parameter param = new Parameter();
                            parameterList.add(param);
                            param.setName(prop.getName());
                            param.setValue(val != null ? val.toString() : "");
                        }
                    } catch (Throwable ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) Color(java.awt.Color) ManagedObject(org.jwildfire.base.ManagedObject) Method(java.lang.reflect.Method)

Aggregations

PropertyDescriptor (java.beans.PropertyDescriptor)836 Method (java.lang.reflect.Method)396 BeanInfo (java.beans.BeanInfo)339 IntrospectionException (java.beans.IntrospectionException)188 IndexedPropertyDescriptor (java.beans.IndexedPropertyDescriptor)171 SimpleBeanInfo (java.beans.SimpleBeanInfo)142 FakeFox01BeanInfo (org.apache.harmony.beans.tests.support.mock.FakeFox01BeanInfo)141 InvocationTargetException (java.lang.reflect.InvocationTargetException)108 ArrayList (java.util.ArrayList)90 HashMap (java.util.HashMap)66 Field (java.lang.reflect.Field)59 Map (java.util.Map)52 Test (org.junit.Test)39 IOException (java.io.IOException)34 MockJavaBean (org.apache.harmony.beans.tests.support.mock.MockJavaBean)34 List (java.util.List)33 HashSet (java.util.HashSet)21 Type (java.lang.reflect.Type)20 Set (java.util.Set)20 LinkedHashMap (java.util.LinkedHashMap)19