Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getPropertyType.

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:org.eclipse.scada.da.core.VariantBeanHelper.java

public static void applyValue(final Object target, final PropertyDescriptor pd, final Variant value)
        throws OperationException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    // ensure for the following calls that the PD has a write method
    final Method m = pd.getWriteMethod();
    if (m == null) {
        throw new OperationException(String.format("Property '%s' is write protected", pd.getName()));
    }//from ww w  . j  a  v  a 2  s.  com

    final Class<?> targetType = pd.getPropertyType();
    if (targetType.isAssignableFrom(Variant.class)) {
        // direct set using variant type
        m.invoke(target, value);
        return;
    }

    // now we need to convert
    if (!applyValueAsObject(target, pd, value.getValue())) {
        throw new OperationException(
                String.format("There is no way to convert '%s' to '%s'", value, targetType));
    }
}

From source file:com.nortal.petit.beanmapper.BeanMappingUtils.java

/**
 * Adds an extended property to the BeanMapping. 
 * /*from www . j av  a2s.  c  om*/
 * @param props
 * @param name
 * @param type
 * @param columnMapping
 * @return
 */
public static <B> Property<B, Object> initExtendedProperty(Map<String, Property<B, Object>> props, String name,
        Class<B> type, String columnMapping) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name);

    if (!isPropertyReadableAndWritable(pd)) {
        return null;
    }

    List<Annotation> ans = BeanMappingReflectionUtils.readAnnotations(type, pd.getName());

    Column column = BeanMappingReflectionUtils.getAnnotation(ans, Column.class);

    ReflectionProperty<B, Object> prop = new ReflectionProperty<B, Object>(name,
            (Class<Object>) pd.getPropertyType(),
            inferColumn(columnMapping != null ? columnMapping : name, column), pd.getWriteMethod(),
            pd.getReadMethod());

    if (column != null) {
        prop.readOnly(true);
    }

    if (BeanMappingReflectionUtils.getAnnotation(ans, Id.class) != null) {
        prop.setIdProperty(true);
    }

    if (useAdditionalConfiguration()) {
        prop.getConfiguration().setAnnotations(ans);
        if (Collection.class.isAssignableFrom(pd.getPropertyType())) {
            prop.getConfiguration().setCollectionTypeArguments(
                    ((ParameterizedType) pd.getReadMethod().getGenericReturnType()).getActualTypeArguments());
        }
    }

    if (BeanMappingReflectionUtils.getAnnotation(ans, Embedded.class) != null) {
        props.putAll(getCompositeProperties(prop, ans));
    } else {
        props.put(prop.name(), prop);
    }

    return prop;
}

From source file:org.wallride.web.support.ControllerUtils.java

private static String convertPropertyValueForString(Object target, PropertyDescriptor descriptor,
        Object propertyValue) {/*from  w w  w. j av a 2s. co  m*/
    DateTimeFormat dateTimeFormat;
    try {
        dateTimeFormat = target.getClass().getDeclaredField(descriptor.getName())
                .getAnnotation(DateTimeFormat.class);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
    if (dateTimeFormat != null) {
        JodaDateTimeFormatAnnotationFormatterFactory factory = new JodaDateTimeFormatAnnotationFormatterFactory();
        Printer printer = factory.getPrinter(dateTimeFormat, descriptor.getPropertyType());
        return printer.print(propertyValue, LocaleContextHolder.getLocale());
    }
    return propertyValue.toString();
}

From source file:org.openlmis.fulfillment.testutils.DtoGenerator.java

private static <T> void generate(Class<T> clazz) {
    Object instance;/*from   ww w  .j  ava  2 s.  co  m*/

    try {
        instance = clazz.newInstance();
    } catch (Exception exp) {
        throw new IllegalStateException("Missing no args constructor", exp);
    }

    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(clazz)) {
        if ("class".equals(descriptor.getName())) {
            continue;
        }

        if (null == descriptor.getReadMethod() || null == descriptor.getWriteMethod()) {
            // we support only full property (it has to have a getter and setter)
            continue;
        }

        try {
            Object value = generateValue(clazz, descriptor.getPropertyType());
            PropertyUtils.setProperty(instance, descriptor.getName(), value);
        } catch (Exception exp) {
            throw new IllegalStateException("Can't set value for property: " + descriptor.getName(), exp);
        }
    }

    REFERENCES.put(clazz, instance);
}

From source file:jp.go.nict.langrid.p2pgridbasis.data.langrid.converter.ConvertUtil.java

public static void decode(DataAttributes from, Object to) throws DataConvertException {
    setLangridConverter();/*  w w w .  j av  a2 s. c  om*/
    logger.debug("##### decode #####");
    try {
        for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(to)) {
            logger.debug(
                    "Name : " + descriptor.getName() + " / PropertyType : " + descriptor.getPropertyType());
            Object value = from.getValue(descriptor.getName());
            if (PropertyUtils.isWriteable(to, descriptor.getName()) && value != null) {
                //Write OK
                try {
                    Converter converter = ConvertUtils.lookup(descriptor.getPropertyType());
                    if (!ignoreProps.contains(descriptor.getName())) {
                        if (converter == null) {
                            logger.error("no converter is registered : " + descriptor.getName() + " "
                                    + descriptor.getPropertyType());
                        } else {
                            Object obj = converter.convert(descriptor.getPropertyType(), value);
                            PropertyUtils.setProperty(to, descriptor.getName(), obj);
                        }
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    logger.info(e.getMessage());
                } catch (NoSuchMethodException e) {
                    logger.info(e.getMessage());
                }
            } else {
                if (value != null) {
                    //Write NG
                    logger.debug("isWriteable = false");
                } else {
                    //Write NG
                    logger.debug("value = null");
                }
            }
        }
    } catch (IllegalAccessException e) {
        throw new DataConvertException(e);
    } catch (InvocationTargetException e) {
        throw new DataConvertException(e);
    }
}

From source file:org.jaxygen.converters.properties.PropertiesToBeanConverter.java

private static void fillBeanArrayField(final String name, Object value, Object bean, BeanInfo beanInfo,
        String[] path, final String fieldName, int bracketStart, int len)
        throws IllegalAccessException, InvocationTargetException, IntrospectionException,
        InstantiationException, IllegalArgumentException, WrongProperyIndex {
    final String indexStr = fieldName.substring(bracketStart + 1, len - 1);
    final String propertyName = fieldName.substring(0, bracketStart);
    int index = Integer.parseInt(indexStr);
    String childName = "";
    int firstDot = name.indexOf(".");
    if (firstDot > 0) {
        childName = name.substring(firstDot + 1);
    }//from w ww . ja v a 2 s.c  o m

    for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
        if (pd.getName().equals(propertyName)) {
            Method writter = pd.getWriteMethod();
            Method reader = pd.getReadMethod();
            if (writter != null && reader != null) {
                Object array = reader.invoke(bean);
                if (pd.getPropertyType().isArray()) {
                    if (array == null) {
                        array = Array.newInstance(pd.getPropertyType().getComponentType(), index + 1);
                        writter.invoke(bean, array);
                    }
                    if (Array.getLength(array) < (index + 1)) {
                        array = resizeArray(array, index + 1);
                        writter.invoke(bean, array);
                    }
                    if (path.length == 1) {
                        Object valueObject = parsePropertyToValue(value, array.getClass().getComponentType());
                        Array.set(array, index, valueObject);
                    } else {
                        Object valueObject = fillBeanValueByName(childName, value,
                                array.getClass().getComponentType(), Array.get(array, index));
                        Array.set(array, index, valueObject);
                    }
                } else if (pd.getPropertyType().equals(List.class)) {
                    if (array == null) {
                        array = pd.getPropertyType().newInstance();
                        writter.invoke(bean, array);
                    }
                    Class<?> genericClass = array.getClass().getTypeParameters()[0].getClass();
                    if (path.length == 1) {
                        Object valueObject = parsePropertyToValue(value, genericClass);
                        Array.set(array, index, valueObject);
                    } else {
                        Object valueObject = fillBeanValueByName(childName, value, genericClass, null);
                        Array.set(array, index, valueObject);
                    }
                }
            }
        }
    }
}

From source file:cn.fql.utility.ClassUtility.java

/**
 * Import value to object according specified  <code>org.xml.sax.Attributes</code>
 *
 * @param obj  specified object instance
 * @param atts <code>org.xml.sax.Attributes</code>
 *///w ww. j  a  v a2s .com
public static void importValueFromAttribute(Object obj, org.xml.sax.Attributes atts) {
    if (atts != null) {
        PropertyDescriptor[] pds;
        try {
            pds = exportPropertyDesc(obj.getClass());
            if (pds != null && pds.length > 0) {
                for (int i = 0; i < pds.length; i++) {
                    PropertyDescriptor pd = pds[i];
                    String strValue = atts.getValue(pd.getName());
                    if (strValue != null) {
                        Method setter = pd.getWriteMethod();
                        if (setter != null) {
                            Object value = ConvertUtils.convert(strValue, pd.getPropertyType());
                            Object[] params = { value };
                            setter.invoke(obj, params);
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

From source file:org.bibsonomy.plugin.jabref.util.JabRefModelConverter.java

protected static void copyStringProperties(BibtexEntry entry, BibTex bibtex) throws IntrospectionException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    /*/*  w w w  .j ava  2  s .co  m*/
     * we use introspection to get all fields ...
     */
    final BeanInfo info = Introspector.getBeanInfo(bibtex.getClass());
    final PropertyDescriptor[] descriptors = info.getPropertyDescriptors();

    /*
     * iterate over all properties
     */
    for (final PropertyDescriptor pd : descriptors) {

        final Method getter = pd.getReadMethod();

        // loop over all String attributes
        final Object o = getter.invoke(bibtex, (Object[]) null);

        if (String.class.equals(pd.getPropertyType()) && (o != null)
                && !JabRefModelConverter.EXCLUDE_FIELDS.contains(pd.getName())) {
            final String value = ((String) o);
            if (present(value)) {
                entry.setField(pd.getName().toLowerCase(), value);
            }
        }
    }
}

From source file:org.jaffa.util.BeanHelper.java

/** This method will introspect the beanClass & get the getter method for the input propertyName.
 * It will then try & convert the propertyValue to the appropriate datatype.
 * @param beanClass The bean class to be introspected.
 * @param propertyName The Property being searched for.
 * @param propertyValue The value to be converted.
 * @throws IntrospectionException if an exception occurs during introspection.
 * @throws IllegalArgumentException if the property cannot be found on the input class.
 * @throws ClassCastException if the input value can't be mapped to target class
 * @return a converted propertyValue compatible with the getter.
 * @deprecated Use DataTypeMapper.instance() instead.
 *///from   w  w w  .  j a  va  2 s  .  c o  m
public static Object convertDataType(Class beanClass, String propertyName, String propertyValue)
        throws IntrospectionException, IllegalArgumentException, ClassCastException {
    Object convertedPropertyValue = null;
    if (propertyValue != null) {
        boolean foundProperty = false;
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        if (beanInfo != null) {
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            if (pds != null) {
                for (PropertyDescriptor pd : pds) {
                    if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) {
                        foundProperty = true;
                        if (pd.getPropertyType().isEnum()) {
                            convertedPropertyValue = findEnum(pd.getPropertyType(), propertyValue.toString());
                            if (convertedPropertyValue == null)
                                throw new IllegalArgumentException("Property " + beanClass.getName() + '.'
                                        + propertyName + ", cannot be set to the value " + propertyValue
                                        + ", since it is not defined in the Enum " + pd.getPropertyType());
                        } else {
                            convertedPropertyValue = DataTypeMapper.instance().map(propertyValue,
                                    pd.getPropertyType());
                        }
                        break;
                    }
                }
            }
        }
        if (!foundProperty)
            throw new IllegalArgumentException(
                    "Could not find the the property: " + beanClass.getName() + '.' + propertyName);
    }
    return convertedPropertyValue;
}

From source file:org.moneta.config.ConnectionPoolFactory.java

protected static PropertyDescriptor assignProperty(String dataSourceName, Object poolRelatedBean,
        String propName, String propValue) {
    PropertyDescriptor pDesc = null;
    try {/*from  www. j av  a  2 s  .co  m*/
        pDesc = PropertyUtils.getPropertyDescriptor(poolRelatedBean, propName);
    } catch (Exception e) {
        throw new MonetaException("Connection pool property not valid")
                .addContextValue("Data source name", dataSourceName).addContextValue("Property name", propName);
    }

    if (pDesc == null) {
        return null;
    }

    try {
        PropertyUtils.setProperty(poolRelatedBean, propName,
                ValueNormalizationUtil.convertString(pDesc.getPropertyType(), propValue));
    } catch (Exception e) {
        throw new MonetaException("Error setting connection pool property", e)
                .addContextValue("Data source name", dataSourceName).addContextValue("Property name", propName);
    }
    return pDesc;
}