Search in sources :

Example 31 with BeanInfo

use of java.beans.BeanInfo in project flow by vaadin.

the class BeanUtil method getBeanPropertyDescriptors.

/**
 * Returns the property descriptors of a class or an interface.
 *
 * For an interface, superinterfaces are also iterated as Introspector does
 * not take them into account (Oracle Java bug 4275879), but in that case,
 * both the setter and the getter for a property must be in the same
 * interface and should not be overridden in subinterfaces for the discovery
 * to work correctly.
 * <p>
 * NOTE : This utility method relies on introspection (and returns
 * PropertyDescriptor) which is a part of java.beans package. The latter
 * package could require bigger JDK in the future (with Java 9+). So it may
 * be changed in the future.
 * <p>
 * For interfaces, the iteration is depth first and the properties of
 * superinterfaces are returned before those of their subinterfaces.
 *
 * @param beanType
 *            the type whose properties to query
 * @return a list of property descriptors of the given type
 * @throws IntrospectionException
 *             if the introspection fails
 */
public static List<PropertyDescriptor> getBeanPropertyDescriptors(final Class<?> beanType) throws IntrospectionException {
    // an interface
    if (beanType.isInterface()) {
        List<PropertyDescriptor> propertyDescriptors = new ArrayList<>();
        for (Class<?> cls : beanType.getInterfaces()) {
            propertyDescriptors.addAll(getBeanPropertyDescriptors(cls));
        }
        BeanInfo info = Introspector.getBeanInfo(beanType);
        propertyDescriptors.addAll(getPropertyDescriptors(info));
        return propertyDescriptors;
    } else {
        BeanInfo info = Introspector.getBeanInfo(beanType);
        return getPropertyDescriptors(info);
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) ArrayList(java.util.ArrayList)

Example 32 with BeanInfo

use of java.beans.BeanInfo in project flow by vaadin.

the class JsonSerializer method toJson.

/**
 * Converts a Java bean, {@link JsonSerializable} instance, String, wrapper
 * of primitive type or enum to a {@link JsonValue}.
 * <p>
 * When a bean is used, a {@link JsonObject} is returned.
 *
 * @param bean
 *            Java object to be converted
 * @return the json representation of the Java object
 */
public static JsonValue toJson(Object bean) {
    if (bean == null) {
        return Json.createNull();
    }
    if (bean instanceof Collection) {
        return toJson((Collection<?>) bean);
    }
    if (bean.getClass().isArray()) {
        return toJsonArray(bean);
    }
    if (bean instanceof JsonSerializable) {
        return ((JsonSerializable) bean).toJson();
    }
    Optional<JsonValue> simpleType = tryToConvertToSimpleType(bean);
    if (simpleType.isPresent()) {
        return simpleType.get();
    }
    try {
        JsonObject json = Json.createObject();
        BeanInfo info = Introspector.getBeanInfo(bean.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            if ("class".equals(pd.getName())) {
                continue;
            }
            Method reader = pd.getReadMethod();
            if (reader != null) {
                json.put(pd.getName(), toJson(reader.invoke(bean)));
            }
        }
        return json;
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not serialize object of type " + bean.getClass() + " to JsonValue", e);
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) JsonSerializable(com.vaadin.flow.component.JsonSerializable) JsonValue(elemental.json.JsonValue) Collection(java.util.Collection) JsonObject(elemental.json.JsonObject) Method(java.lang.reflect.Method)

Example 33 with BeanInfo

use of java.beans.BeanInfo in project flow by vaadin.

the class ComponentTest method setup.

@Before
public void setup() throws IntrospectionException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    component = createComponent();
    WHITE_LIST.add("visible");
    addProperties();
    BeanInfo componentInfo = Introspector.getBeanInfo(component.getClass());
    Stream.of(componentInfo.getPropertyDescriptors()).filter(descriptor -> !WHITE_LIST.contains(descriptor.getName())).forEach(this::assertProperty);
}
Also used : Component(com.vaadin.flow.component.Component) Set(java.util.Set) Test(org.junit.Test) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Introspector(java.beans.Introspector) List(java.util.List) Stream(java.util.stream.Stream) ParameterizedType(java.lang.reflect.ParameterizedType) HtmlComponent(com.vaadin.flow.component.HtmlComponent) Type(java.lang.reflect.Type) PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) Element(com.vaadin.flow.dom.Element) Optional(java.util.Optional) Assert(org.junit.Assert) Before(org.junit.Before) BeanInfo(java.beans.BeanInfo) Before(org.junit.Before)

Example 34 with BeanInfo

use of java.beans.BeanInfo in project jaffa-framework by jaffa-projects.

the class BeanHelper method cloneBean.

/**
 * Clones the input bean, performing a deep copy of its properties.
 * @param bean the bean to be cloned.
 * @param deepCloneForeignField if false, then the foreign-fields of a GraphDataObject will not be deep cloned.
 * @return a clone of the input bean.
 * @throws IllegalAccessException if the underlying method is inaccessible.
 * @throws InvocationTargetException if the underlying method throws an exception.
 * @throws InstantiationException if the bean cannot be instantiated.
 * @throws IntrospectionException if an exception occurs during introspection.
 */
public static Object cloneBean(Object bean, boolean deepCloneForeignField) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException {
    if (bean == null)
        return bean;
    Class beanClass = bean.getClass();
    // Return the input as-is, if immutable
    if (beanClass == String.class || beanClass == Boolean.class || Number.class.isAssignableFrom(beanClass) || IDateBase.class.isAssignableFrom(beanClass) || Currency.class.isAssignableFrom(beanClass) || beanClass.isPrimitive()) {
        return bean;
    }
    // Handle an array
    if (beanClass.isArray()) {
        Class componentType = beanClass.getComponentType();
        int length = Array.getLength(bean);
        Object clone = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Object arrayElementClone = cloneBean(Array.get(bean, i), deepCloneForeignField);
            Array.set(clone, i, arrayElementClone);
        }
        return clone;
    }
    // Handle a Collection
    if (bean instanceof Collection) {
        Collection clone = (Collection) bean.getClass().newInstance();
        for (Object collectionElement : (Collection) bean) {
            Object collectionElementClone = cloneBean(collectionElement, deepCloneForeignField);
            clone.add(collectionElementClone);
        }
        return clone;
    }
    // Handle a Map
    if (bean instanceof Map) {
        Map clone = (Map) bean.getClass().newInstance();
        for (Iterator i = ((Map) bean).entrySet().iterator(); i.hasNext(); ) {
            Map.Entry me = (Map.Entry) i.next();
            Object keyClone = cloneBean(me.getKey(), deepCloneForeignField);
            Object valueClone = cloneBean(me.getValue(), deepCloneForeignField);
            clone.put(keyClone, valueClone);
        }
        return clone;
    }
    // Invoke the 'public Object clone()' method, if available
    if (bean instanceof Cloneable) {
        try {
            Method cloneMethod = beanClass.getMethod("clone");
            return cloneMethod.invoke(bean);
        } catch (NoSuchMethodException e) {
        // do nothing
        }
    }
    // Create a clone using bean introspection
    Object clone = beanClass.newInstance();
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            // Obtain a GraphMapping; only if foreign-fields are not to be cloned
            // Use reflection to achieve the following:
            // GraphMapping graphMapping = !deepCloneForeignField && bean instanceof GraphDataObject ? MappingFactory.getInstance(bean) : null;
            Object graphMapping = null;
            Method isForeignFieldMethod = null;
            try {
                if (!deepCloneForeignField && Class.forName("org.jaffa.soa.graph.GraphDataObject").isInstance(bean)) {
                    graphMapping = Class.forName("org.jaffa.soa.dataaccess.MappingFactory").getMethod("getInstance", Object.class).invoke(null, bean);
                    isForeignFieldMethod = graphMapping.getClass().getMethod("isForeignField", String.class);
                }
            } catch (Exception e) {
                // do nothing since JaffaSOA may not be deployed
                if (log.isDebugEnabled())
                    log.debug("Exception in obtaining the GraphMapping", e);
            }
            for (PropertyDescriptor pd : pds) {
                if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                    // Do not clone a foreign-field
                    Object property = pd.getReadMethod().invoke(bean);
                    // Use reflection to achieve the following:
                    // Object propertyClone = graphMapping != null && graphMapping.isForeignField(pd.getName()) ? property : cloneBean(property, deepCloneForeignField);
                    Object propertyClone = null;
                    boolean propertyCloned = false;
                    if (graphMapping != null && isForeignFieldMethod != null) {
                        try {
                            if ((Boolean) isForeignFieldMethod.invoke(graphMapping, pd.getName())) {
                                propertyClone = property;
                                propertyCloned = true;
                            }
                        } catch (Exception e) {
                            // do nothing since JaffaSOA may not be deployed
                            if (log.isDebugEnabled())
                                log.debug("Exception in invoking GraphMapping.isForeignField()", e);
                        }
                    }
                    if (!propertyCloned)
                        propertyClone = cloneBean(property, deepCloneForeignField);
                    pd.getWriteMethod().invoke(clone, propertyClone);
                }
            }
        }
    }
    return clone;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IDateBase(org.jaffa.datatypes.IDateBase) Iterator(java.util.Iterator) Collection(java.util.Collection) Map(java.util.Map)

Example 35 with BeanInfo

use of java.beans.BeanInfo in project jaffa-framework by jaffa-projects.

the class BeanHelper method setField.

/**
 * This method will introspect the bean & get the setter method for the input propertyName.
 * It will then try & convert the propertyValue to the appropriate datatype.
 * Finally it will invoke the setter.
 * @return A true indicates, the property was succesfully set to the passed value. A false indicates the property doesn't exist or the propertyValue passed is not compatible with the setter.
 * @param bean The bean class to be introspected.
 * @param propertyName The Property being searched for.
 * @param propertyValue The value to be set.
 * @throws IntrospectionException if an exception occurs during introspection.
 * @throws IllegalAccessException if the underlying method is inaccessible.
 * @throws InvocationTargetException if the underlying method throws an exception.
 */
public static boolean setField(Object bean, String propertyName, Object propertyValue) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    boolean result = false;
    if (bean instanceof DynaBean) {
        try {
            PropertyUtils.setProperty(bean, propertyName, propertyValue);
            result = true;
        } catch (NoSuchMethodException ignore) {
            // If the bean is a FlexBean instance, then the field could exist on the associated persistentObject
            if (bean instanceof FlexBean && ((FlexBean) bean).getPersistentObject() != null) {
                try {
                    PropertyUtils.setProperty(((FlexBean) bean).getPersistentObject(), propertyName, propertyValue);
                    result = true;
                } catch (NoSuchMethodException ignore2) {
                }
            }
        }
    } else {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        if (beanInfo != null) {
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            if (pds != null) {
                for (PropertyDescriptor pd : pds) {
                    if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) {
                        Method m = pd.getWriteMethod();
                        Object convertedPropertyValue = null;
                        if (propertyValue != null) {
                            if (pd.getPropertyType().isEnum()) {
                                convertedPropertyValue = findEnum(pd.getPropertyType(), propertyValue.toString());
                            } else {
                                try {
                                    convertedPropertyValue = DataTypeMapper.instance().map(propertyValue, pd.getPropertyType());
                                } catch (Exception e) {
                                    // do nothing
                                    break;
                                }
                            }
                        }
                        m.invoke(bean, new Object[] { convertedPropertyValue });
                        result = true;
                        break;
                    }
                }
            }
        }
        try {
            // Finally, check the FlexBean
            if (!result && bean instanceof IFlexFields && ((IFlexFields) bean).getFlexBean() != null && ((IFlexFields) bean).getFlexBean().getDynaClass().getDynaProperty(propertyName) != null) {
                ((IFlexFields) bean).getFlexBean().set(propertyName, propertyValue);
                result = true;
            }
        } catch (Exception ignore) {
        }
    }
    return result;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) DynaBean(org.apache.commons.beanutils.DynaBean) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) IFlexFields(org.jaffa.flexfields.IFlexFields) FlexBean(org.jaffa.flexfields.FlexBean) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

BeanInfo (java.beans.BeanInfo)420 PropertyDescriptor (java.beans.PropertyDescriptor)328 Method (java.lang.reflect.Method)217 SimpleBeanInfo (java.beans.SimpleBeanInfo)167 FakeFox01BeanInfo (org.apache.harmony.beans.tests.support.mock.FakeFox01BeanInfo)161 IndexedPropertyDescriptor (java.beans.IndexedPropertyDescriptor)148 IntrospectionException (java.beans.IntrospectionException)115 InvocationTargetException (java.lang.reflect.InvocationTargetException)38 HashMap (java.util.HashMap)33 Test (org.junit.jupiter.api.Test)33 ArrayList (java.util.ArrayList)30 Field (java.lang.reflect.Field)17 Map (java.util.Map)17 Test (org.junit.Test)13 EventSetDescriptor (java.beans.EventSetDescriptor)12 MethodDescriptor (java.beans.MethodDescriptor)12 List (java.util.List)11 BeanDescriptor (java.beans.BeanDescriptor)10 HashSet (java.util.HashSet)8 Introspector (java.beans.Introspector)7