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:com.blackbear.flatworm.ParseUtils.java

/**
 * Attempt to find the collection property on {@code target} indicated by the {@code propertyName} and then see if the "collection"
 * returned has an {@code add(Object)} method and if it does - invoke it with the {@code toAdd} instance. If any of the parameters are
 * {@code null} then no action is taken.
 *
 * @param target                 The object that has the collection property for which the {@code toAdd} instance will be added.
 * @param collectionPropertyName The name of the Java BeanBO property that will return a collection (may not be a {@link
 *                               java.util.Collection} so long as there is an {@code add(Object)} method). Note that if this returns a
 *                               null value a {@link FlatwormConfigurationException} will be thrown.
 * @param toAdd                  The instance to add to the collection indicated.
 * @throws FlatwormParserException Should the underlying collection referenced by {@code propertyName} be {@code null} or non-existent,
 *                                 should no {@code add(Object)} method exist on the collection and should any error occur while
 *                                 invoking the {@code add(Object)} method if it is found (reflection style errors).
 *//*w  w w.j a v a2s.com*/
public static void addValueToCollection(Object target, String collectionPropertyName, Object toAdd)
        throws FlatwormParserException {
    if (target == null || StringUtils.isBlank(collectionPropertyName) || toAdd == null)
        return;
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(target,
                collectionPropertyName);
        if (propertyDescriptor != null) {
            Object collectionInstance = PropertyUtils.getProperty(target, collectionPropertyName);
            if (collectionInstance != null) {
                // Once compiled, generics lose their converterName reference and it defaults to a simple java.lang.Object.class
                // so that's the method parameter we'll search by.
                Method addMethod = propertyDescriptor.getPropertyType().getMethod("add", Object.class);
                if (addMethod != null) {
                    addMethod.invoke(collectionInstance, toAdd);
                } else {
                    throw new FlatwormParserException(String.format(
                            "The collection instance %s for property %s in class %s does not have an add method.",
                            collectionInstance.getClass().getName(), propertyDescriptor.getName(),
                            target.getClass().getName()));
                }
            } else {
                throw new FlatwormParserException(String.format(
                        "Unable to invoke the add method on collection %s as it is currently null for instance %s.",
                        propertyDescriptor.getName(), target.getClass().getName()));
            }
        } else {
            throw new FlatwormParserException(String.format(
                    "%s does not have a getter for property %s - the %s instance could therefore not be added to the collection.",
                    target.getClass().getName(), collectionPropertyName, toAdd.getClass().getName()));
        }
    } catch (Exception e) {
        throw new FlatwormParserException(String.format(
                "Unable to invoke the add method on the collection for property %s in bean %s with object of converterName %s",
                collectionPropertyName, target.getClass().getName(), toAdd.getClass().getName()), e);
    }
}

From source file:org.codehaus.groovy.grails.commons.GrailsDomainConfigurationUtil.java

/**
 * Checks whether is property is configurational.
 *
 * @param descriptor The descriptor/*  www .j  a v  a 2 s  .c  om*/
 * @return true if it is configurational
 */
public static boolean isNotConfigurational(PropertyDescriptor descriptor) {

    final String name = descriptor.getName();
    Method readMethod = descriptor.getReadMethod();
    Method writeMethod = descriptor.getWriteMethod();

    if ((readMethod != null && Modifier.isStatic(readMethod.getModifiers())
            || (writeMethod != null && Modifier.isStatic(writeMethod.getModifiers())))) {
        return false;
    }

    return !Errors.class.isAssignableFrom(descriptor.getPropertyType()) && isNotConfigurational(name);
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Modifies the value of the bean's property represented by
 * the supplied property descriptor.//  w  w w  .java2 s . c om
 * @param bean to read
 * @param propertyDescriptor indicating what to read
 * @param value to set
 */
public static void setValue(Object bean, PropertyDescriptor propertyDescriptor, Object value) {
    try {
        Method method = getAccessibleMethod(propertyDescriptor.getWriteMethod());
        if (method == null) {
            throw new JXPathException("No write method");
        }
        value = convert(value, propertyDescriptor.getPropertyType());
        method.invoke(bean, new Object[] { value });
    } catch (Exception ex) {
        throw new JXPathException("Cannot modify property: "
                + (bean == null ? "null" : bean.getClass().getName()) + "." + propertyDescriptor.getName(), ex);
    }
}

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

/** 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.//  www . j  a  v  a2 s. co m
 * @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;
}

From source file:cat.albirar.framework.sets.SetUtils.java

/**
 * Check if path is correct for the indicated model.
 * @param model The model//from ww  w.j a v a 2  s  . c  o  m
 * @param propertyPath The property path, required
 * @return true if correct and false if not
 * @throws IllegalArgumentException If model is null or if the property path is null or empty or only whitespace or not correct format
 */
public static boolean checkPathForModel(Class<?> model, String propertyPath) {
    StringTokenizer stk;
    ModelDescriptor pathFollower;
    PropertyDescriptor pdesc;
    String ppath;

    Assert.hasText(propertyPath, "The property path is required and cannot be empty or only whitespace");

    // Check pattern
    if (!pathPattern.matcher(propertyPath).matches()) {
        throw new IllegalArgumentException(String.format("The property path '%s' is incorrect!", propertyPath));
    }
    stk = new StringTokenizer(propertyPath, ".");
    pathFollower = new ModelDescriptor(model);
    while (stk.hasMoreTokens()) {
        ppath = stk.nextToken();
        if ((pdesc = pathFollower.getProperties().get(ppath)) != null) {
            if (stk.hasMoreTokens()) {
                pathFollower = new ModelDescriptor(pdesc.getPropertyType());
            }
        } else {
            // Error
            return false;
        }
    }
    return true;
}

From source file:io.coala.enterprise.Fact.java

/**
 * override and deserialize bean properties as declared in factType
 * <p>// ww  w  . ja v a2 s  .c o m
 * TODO detect properties from builder methods: {@code withKey(T value)}
 * 
 * @param om
 * @param json
 * @param factType
 * @param properties
 * @return the properties again, to allow chaining
 * @throws IntrospectionException
 */
static <T extends Fact> Map<String, Object> fromJSON(final ObjectMapper om, final TreeNode json,
        final Class<T> factType, final Map<String, Object> properties) {
    try {
        final ObjectNode tree = (ObjectNode) json;
        final BeanInfo beanInfo = Introspector.getBeanInfo(factType);
        for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors())
            if (tree.has(pd.getName()))
                properties.computeIfPresent(pd.getName(),
                        (property, current) -> JsonUtil.valueOf(om, tree.get(property), pd.getPropertyType()));
        return properties;
    } catch (final Throwable e) {
        return Thrower.rethrowUnchecked(e);
    }
}

From source file:com.unboundid.scim2.common.utils.SchemaUtils.java

/**
 * This method will determine if this attribute can have multieple
 * values, and set that in the builder.//from   w  w  w  . j  a v a  2 s .c  om
 *
 * @param attributeBuilder builder for a scim attribute.
 * @param propertyDescriptor property descriptor for the field to build
 *                           the attribute for.
 * @param schemaProperty the schema property annotation for the field
 *                       to build an attribute for.
 * @return this.
 */
private static AttributeDefinition.Builder addMultiValued(final AttributeDefinition.Builder attributeBuilder,
        final PropertyDescriptor propertyDescriptor, final Attribute schemaProperty) {
    Class<?> multiValuedClass = schemaProperty.multiValueClass();
    boolean multiValued = !multiValuedClass.equals(NullType.class);
    boolean collectionOrArray = isCollectionOrArray(propertyDescriptor.getPropertyType());

    // if the multiValuedClass attribute is present in the annotation,
    // make sure this is a collection or array.
    if (multiValued && !collectionOrArray) {
        throw new RuntimeException("Property named " + propertyDescriptor.getName()
                + " is annotated with a multiValuedClass, " + "but is not a Collection or an array");
    }

    if (!multiValued && collectionOrArray) {
        throw new RuntimeException("Property named " + propertyDescriptor.getName()
                + " is not annotated with a multiValuedClass, " + "but is a Collection or an array");
    }

    attributeBuilder.setMultiValued(multiValued);

    return attributeBuilder;
}

From source file:org.kuali.rice.krad.datadictionary.DataDictionaryPropertyUtils.java

/**
 * @return PropertyDescriptor for the getter for the named property of the given class, if one exists.
 *///from  ww w. j av a2s .  co m
private static PropertyDescriptor buildReadDescriptor(Class propertyClass, String propertyName) {
    if (propertyClass == null) {
        throw new IllegalArgumentException("invalid (null) propertyClass");
    }
    if (StringUtils.isBlank(propertyName)) {
        throw new IllegalArgumentException("invalid (blank) propertyName");
    }

    PropertyDescriptor propertyDescriptor = null;

    String[] intermediateProperties = propertyName.split("\\.");
    int lastLevel = intermediateProperties.length - 1;
    Class currentClass = propertyClass;

    for (int i = 0; i <= lastLevel; ++i) {

        String currentPropertyName = intermediateProperties[i];
        propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName);

        if (i < lastLevel) {

            if (propertyDescriptor != null) {

                Class propertyType = propertyDescriptor.getPropertyType();
                if (getLegacyDataAdapter().isExtensionAttribute(currentClass, currentPropertyName,
                        propertyType)) {
                    propertyType = getLegacyDataAdapter().getExtensionAttributeClass(currentClass,
                            currentPropertyName);
                }
                if (Collection.class.isAssignableFrom(propertyType)) {
                    currentClass = getLegacyDataAdapter().determineCollectionObjectType(currentClass,
                            currentPropertyName);
                } else {
                    currentClass = propertyType;
                }

            }

        }

    }

    return propertyDescriptor;
}

From source file:edu.ku.brc.af.ui.forms.FormHelper.java

/**
 * Helper for setting a value into a data object using reflection
 * @param fieldNames the field name(s)// w  ww.j  a v a  2s . c o m
 * @param dataObj the data object that will get the new value
 * @param newData the new data object
 * @param getter the getter to use
 * @param setter the setter to use
 */
public static void setFieldValue(final String fieldNames, final Object dataObj, final Object newData,
        final DataObjectGettable getter, final DataObjectSettable setter) {
    if (StringUtils.isNotEmpty(fieldNames)) {
        if (setter.usesDotNotation()) {
            int inx = fieldNames.indexOf(".");
            if (inx > -1) {
                String[] fileNameArray = StringUtils.split(fieldNames, '.');
                Object data = dataObj;
                for (int i = 0; i < fileNameArray.length; i++) {
                    String fieldName = fileNameArray[i];
                    if (i < fileNameArray.length - 1) {
                        data = getter.getFieldValue(data, fieldName);
                        if (data == null) {
                            try {
                                //log.debug("fieldName ["+fieldName+"]");
                                PropertyDescriptor descr = PropertyUtils.getPropertyDescriptor(dataObj,
                                        fieldName.trim());
                                Class<?> classObj = descr.getPropertyType();
                                Object newObj = classObj.newInstance();
                                //log.debug("New Obj ["+newObj+"] of type ["+ classObj +"]being added to ["+dataObj+"]");
                                if (newObj != null) {

                                    Method method = newObj.getClass().getMethod("initialize",
                                            new Class<?>[] {});
                                    method.invoke(newObj, new Object[] {});
                                    setter.setFieldValue(dataObj, fieldName, newObj);
                                    data = newObj;

                                    //log.debug("Inserting New Obj ["+newObj+"] at top of new DB ObjCache");

                                }
                            } catch (NoSuchMethodException ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class,
                                        ex);

                            } catch (IllegalAccessException ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class,
                                        ex);

                            } catch (InvocationTargetException ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class,
                                        ex);

                            } catch (InstantiationException ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class,
                                        ex);
                            }
                        }
                    } else {
                        //log.info("Data Obj ["+newData+"] being added to ["+data+"]");
                        setter.setFieldValue(data, fieldName, newData);
                    }
                }
            } else {
                //log.info("setFieldValue -  newData ["+newData+"] fieldNames["+fieldNames+"] set into ["+dataObj+"]");
                setter.setFieldValue(dataObj, fieldNames, newData);
            }
        } else {
            //log.info("setFieldValue -  newData ["+newData+"] fieldNames["+fieldNames+"] set into ["+dataObj+"]");
            setter.setFieldValue(dataObj, fieldNames, newData);
        }
    }
}

From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java

/**
 * Copies a property from a source object to a target object given two
 * respective property descriptors.//from w w w  . ja v a 2 s  . co m
 * The target's property type has to be a super-type of the source's
 * property type. If both are sub-types of {@link Number}, we use a 
 * converter to convert the source property to a type compatible with
 * the target property. This may lead to loss of precision.
 * 
 * TODO: We could also support other conversions, e.g. Character -> String
 * 
 * @param source
 * @param target
 * @param sourcePd
 * @param targetPd
 */
public static void copyProperty(Object source, Object target, PropertyDescriptor sourcePd,
        PropertyDescriptor targetPd) {
    if (source == null || target == null || sourcePd == null || targetPd == null) {
        return;
    }
    Class<?> targetPdType = targetPd.getPropertyType();
    Class<?> sourcePdType = sourcePd.getPropertyType();

    boolean assignable = targetPdType.isAssignableFrom(sourcePdType);
    boolean differentNumberTypes = Number.class.isAssignableFrom(targetPdType)
            && Number.class.isAssignableFrom(sourcePdType) && !assignable;

    if (assignable || differentNumberTypes) {
        Method getter = sourcePd.getReadMethod();
        if (getter != null) {
            Object[] getterArgs = null;
            Object value = ReflectionUtils.invoke(getter, source, getterArgs);
            Method setter = targetPd.getWriteMethod();
            if (setter != null) {
                if (differentNumberTypes) {
                    @SuppressWarnings("unchecked")
                    NumberConverter converter = new NumberConverter((Class<? extends Number>) targetPdType);
                    value = converter.execute((Number) value);
                }
                Object[] setterArgs = { value };
                ReflectionUtils.invoke(setter, target, setterArgs);
            }
        }
    }
}