Example usage for java.beans PropertyDescriptor getWriteMethod

List of usage examples for java.beans PropertyDescriptor getWriteMethod

Introduction

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

Prototype

public synchronized Method getWriteMethod() 

Source Link

Document

Gets the method that should be used to write the property value.

Usage

From source file:nl.strohalm.cyclos.utils.binding.CustomBeanUtilsBean.java

@Override
public void setProperty(final Object bean, String name, final Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Resolve any nested expression to get the actual target bean
    Object target = bean;/*from  w ww.ja v a2s  . c om*/
    final int delim = findLastNestedIndex(name);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (final NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class<?> type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the property name, index, and key values
    propName = name;
    final int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        final int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (final NumberFormatException e) {
            // Ignore
        }
        propName = propName.substring(0, i);
    }
    final int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        final int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (final IndexOutOfBoundsException e) {
            // Ignore
        }
        propName = propName.substring(0, j);
    }

    // Calculate the property type
    if (target instanceof DynaBean) {
        final DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        final DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
        if (type.isArray() || Collection.class.isAssignableFrom(type)) {
            type = Object[].class;
        }
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (final NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();

            /**
             * Overriden behaviour ------------------- When a type is Object on a mapped property, retrieve the value to check if it's an array
             */
            if (Object.class.equals(type)) {
                try {
                    final Object retrieved = getPropertyUtils().getMappedProperty(target, propName, key);
                    if (retrieved != null) {
                        final Class<?> retrievedType = retrieved.getClass();
                        if (retrievedType.isArray() || Collection.class.isAssignableFrom(retrievedType)) {
                            type = Object[].class;
                        }
                    }
                } catch (final NoSuchMethodException e) {
                    throw new PropertyException(target, propName + "(" + key + ")");
                }
            }
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            if (descriptor.getWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    /**
     * Overriden behaviour ------------------- When a type is Map on a mapped property, retrieve the value to check if it's an array
     */
    if (Map.class.isAssignableFrom(type) && StringUtils.isNotEmpty(key)) {
        try {
            final Map<?, ?> map = (Map<?, ?>) getPropertyUtils().getProperty(target, propName);
            final Object retrieved = map.get(key);
            if (retrieved != null) {
                final Class<?> retrievedType = retrieved.getClass();
                if (retrievedType.isArray() || Collection.class.isAssignableFrom(retrievedType)) {
                    type = Object[].class;
                }
            }
        } catch (final NoSuchMethodException e) {
            throw new PropertyException(target, propName + "(" + key + ")");
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            final String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            final String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if ((value instanceof String) || (value == null)) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else if (getConvertUtils().lookup(value.getClass()) != null) {
            newValue = getConvertUtils().convert(value.toString(), type);
        } else {
            newValue = value;
        }
    }

    // Invoke the setter method
    try {
        if (index >= 0) {
            getPropertyUtils().setIndexedProperty(target, propName, index, newValue);
        } else if (key != null) {
            getPropertyUtils().setMappedProperty(target, propName, key, newValue);
        } else {
            getPropertyUtils().setProperty(target, propName, newValue);
        }
    } catch (final NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private static final Object newLazyObject(Class<?> targetClass)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, IntrospectionException,
        IllegalArgumentException, InvocationTargetException, PersistenceException {
    Object lazyObj = targetClass.newInstance();
    String name = targetClass.getName();
    Set<PropertyDescriptor> pds = idsByClassName.get(name);
    for (PropertyDescriptor pd : pds) {
        pd.getWriteMethod().invoke(lazyObj, getLazyValue(pd.getPropertyType()));
    }//  w  w  w. j a  va  2  s . co m
    return lazyObj;
}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

/**
 * <p>//from   w  w  w  . j  av a  2s  . c o m
 * Return an accessible property setter method for this property, if there
 * is one; otherwise return <code>null</code>.
 * </p>
 *
 * <p>
 * <em>Note:</em> This method does not work correctly with custom bean
 * introspection under certain circumstances. It may return {@code null}
 * even if a write method is defined for the property in question. Use
 * {@link #getWriteMethod(Class, PropertyDescriptor)} to be sure that the
 * correct result is returned.
 * </p>
 * <p>
 * <strong>FIXME</strong> - Does not work with DynaBeans.
 * </p>
 *
 * @param descriptor
 *            Property descriptor to return a setter for
 * @return The write method
 */
public Method getWriteMethod(final PropertyDescriptor descriptor) {

    return MethodUtils.getAccessibleMethod(descriptor.getWriteMethod());

}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private static Object deproxyObject(Class<?> targetClass, Object proxy)
        throws InstantiationException, IllegalAccessException, IntrospectionException,
        InvocationTargetException, PersistenceException, ClassNotFoundException {
    Object target = targetClass.newInstance();
    PropertyDescriptor[] targetPds = Introspector.getBeanInfo(targetClass).getPropertyDescriptors();
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getReadMethod() != null && targetPd.getWriteMethod() != null) {
            Object o = targetPd.getReadMethod().invoke(proxy, new Object[0]);
            if (o != null) {
                Class<?> propertyType = targetPd.getPropertyType();
                String className = propertyType.getName();
                if (!propertyType.isPrimitive() && !o.getClass().isPrimitive() && !(o instanceof Date)
                        && isProxy(o, className)) {
                    if (Set.class.isAssignableFrom(propertyType)) {
                        o = new LazySet();
                    } else if (List.class.isAssignableFrom(propertyType)) {
                        o = new LazyList();
                    } else
                        o = newLazyObject(propertyType);
                }//from   www. j a  v  a 2  s  . co m
                targetPd.getWriteMethod().invoke(target, o);
            }
        }
    }

    return target;
}

From source file:org.enerj.apache.commons.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>/*from  www.j  av  a  2  s . c om*/
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String values[] = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    int delim = findLastNestedIndex(name);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
        if (log.isTraceEnabled()) {
            log.trace("    Target bean = " + target);
            log.trace("    Target name = " + name);
        }
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the property name, index, and key values
    propName = name;
    int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (NumberFormatException e) {
            ;
        }
        propName = propName.substring(0, i);
    }
    int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (IndexOutOfBoundsException e) {
            ;
        }
        propName = propName.substring(0, j);
    }

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if ((value instanceof String) || (value == null)) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else if (getConvertUtils().lookup(value.getClass()) != null) {
            newValue = getConvertUtils().convert(value.toString(), type);
        } else {
            newValue = value;
        }
    }

    // Invoke the setter method
    try {
        if (index >= 0) {
            getPropertyUtils().setIndexedProperty(target, propName, index, newValue);
        } else if (key != null) {
            getPropertyUtils().setMappedProperty(target, propName, key, newValue);
        } else {
            getPropertyUtils().setProperty(target, propName, newValue);
        }
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:org.ajax4jsf.builder.config.ComponentBaseBean.java

/**
 * @param superClass/*from w  w w.  java 2  s.c  o m*/
 */
private void checkPropertiesForClass(Class<?> superClass) {
    getLog().debug("Check properties for class " + superClass.getName());
    // get all property descriptors
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(superClass);
    // for all properties, add it to component. If property have not abstract getter/setter ,
    // add it with exist = true . If property in list of hidden names, set hidden = true.
    PropertyBean property;
    for (int i = 0; i < properties.length; i++) {
        PropertyDescriptor descriptor = properties[i];
        if (!containProperty(descriptor.getName())) {
            if (isIgnorableProperty(superClass, descriptor.getName())) {
                continue;
            }
            Class<?> type = descriptor.getPropertyType();
            getLog().debug("Register property  " + descriptor.getName() + " with type name "
                    + type.getCanonicalName());
            property = new PropertyBean();
            property.setName(descriptor.getName());
            property.setDescription(descriptor.getShortDescription());
            property.setDisplayname(descriptor.getDisplayName());
            property.setClassname(descriptor.getPropertyType().getCanonicalName());
            property.setExist(true);
            addProperty(property);
        } else {
            // Load and check property.
            getLog().debug("Check  property  " + descriptor.getName());
            property = (PropertyBean) this.properties.get(descriptor.getName());
            if (property.getClassname() == null) {
                property.setClassname(descriptor.getPropertyType().getCanonicalName());
            } else {
                if (!property.getClassname().equals(descriptor.getPropertyType().getCanonicalName())) {
                    String message = "Class " + property.getClassname() + " for property " + property.getName()
                            + " not equals with real bean property type: "
                            + descriptor.getPropertyType().getCanonicalName();
                    getLog().error(message);
                    //throw new IllegalArgumentException(message);
                }
            }
            if (property.getDescription() == null) {
                property.setDescription(descriptor.getShortDescription());
            }
            if (property.getDisplayname() == null) {
                property.setDisplayname(descriptor.getDisplayName());
            }
            property.setExist(true);
        }
        Method getter = descriptor.getReadMethod();
        Method setter = descriptor.getWriteMethod();
        // Abstract methods
        if (null != setter && null != getter) {
            if ((Modifier.isAbstract(getter.getModifiers()) && Modifier.isAbstract(setter.getModifiers()))
                    || superClass.isInterface()) {
                getLog().debug("Detect as abstract property  " + descriptor.getName());
                property.setExist(false);
            }
        }

        if (null == setter || (!Modifier.isPublic(setter.getModifiers()))) {
            getLog().debug("Detect as hidden property  " + descriptor.getName());
            property.setHidden(true);
        }
        if (isAttachedProperty(property)) {
            property.setAttachedstate(true);
        }
        if (property.isInstanceof("javax.faces.el.MethodBinding")
                || property.isInstanceof("javax.faces.el.ValueBinding")) {
            property.setElonly(true);
        }

    }
}

From source file:utils.beanUtils.JIMBeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>/*from w w  w  .j av a 2  s  . co m*/
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
protected void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String values[] = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    int delim = findLastNestedIndex(name);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
        if (log.isTraceEnabled()) {
            log.trace("    Target bean = " + target);
            log.trace("    Target name = " + name);
        }
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the property name, index, and key values
    propName = name;
    int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (NumberFormatException e) {
            ;
        }
        propName = propName.substring(0, i);
    }
    int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (IndexOutOfBoundsException e) {
            ;
        }
        propName = propName.substring(0, j);
    }

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if ((value instanceof String) || (value == null)) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else if (getConvertUtils().lookup(value.getClass()) != null) {
            newValue = getConvertUtils().convert(value.toString(), type);
        } else {
            newValue = value;
        }
    }

    // Invoke the setter method
    try {
        if (index >= 0) {
            getPropertyUtils().setIndexedProperty(target, propName, index, newValue);
        } else if (key != null) {
            getPropertyUtils().setMappedProperty(target, propName, key, newValue);
        } else {
            getPropertyUtils().setProperty(target, propName, newValue);
        }
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:com.turbospaces.model.BO.java

/**
 * create business object over actual basic persistent entity
 * /*from   ww  w. j  a va2 s  . c  o m*/
 * @param delegate
 *            the actual persistent entity meta-data provider
 * @throws NoSuchMethodException
 *             re-throw cglib exception
 * @throws SecurityException
 *             re-throw cglib exception
 * @throws IntrospectionException
 *             re-throw exceptions
 */
public BO(final BasicPersistentEntity delegate)
        throws SecurityException, NoSuchMethodException, IntrospectionException {
    this.delegate = delegate;
    this.fastConstructor = FastClass.create(delegate.getType())
            .getConstructor(delegate.getType().getConstructor());

    // find optimistic lock version/routing fields
    {
        final Collection<PersistentProperty> versionCandidates = Lists.newLinkedList();
        final Collection<PersistentProperty> routingCandidates = Lists.newLinkedList();
        delegate.doWithProperties(new PropertyHandler() {
            @Override
            public void doWithPersistentProperty(final PersistentProperty persistentProperty) {
                PropertyDescriptor propertyDescriptor = persistentProperty.getPropertyDescriptor();
                Field field = persistentProperty.getField();

                if (hasAnnotation(propertyDescriptor, field, Version.class))
                    versionCandidates.add(persistentProperty);
                if (hasAnnotation(propertyDescriptor, field, Routing.class))
                    routingCandidates.add(persistentProperty);
            }

            private boolean hasAnnotation(final PropertyDescriptor descriptor, final Field field,
                    final Class annotation) {
                if (descriptor != null && descriptor.getReadMethod() != null
                        && descriptor.getReadMethod().getAnnotation(annotation) != null)
                    return true;
                if (field != null && field.getAnnotation(annotation) != null)
                    return true;
                return false;
            }
        });
        Preconditions.checkArgument(versionCandidates.size() <= 1,
                "too many fields marked with @Version annotation, candidates = "
                        + versionCandidates.toString());
        Preconditions.checkArgument(routingCandidates.size() <= 1,
                "too many fields marked with @Routing annotation, candidates = "
                        + routingCandidates.toString());

        if (!versionCandidates.isEmpty())
            optimisticLockVersionProperty = versionCandidates.iterator().next();
        if (!routingCandidates.isEmpty())
            routingProperty = routingCandidates.iterator().next();
    }

    {
        // Java Beans convention marker
        AtomicBoolean propertyAccess = new AtomicBoolean(true);

        List<String> setters = Lists.newLinkedList();
        List<String> getters = Lists.newLinkedList();
        List<Class<?>> types = Lists.newLinkedList();

        for (PersistentProperty<?> persistentProperty : getOrderedProperties()) {
            PropertyDescriptor propertyDescriptor = persistentProperty.getPropertyDescriptor();
            if (propertyDescriptor != null) {
                if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) {
                    setters.add(propertyDescriptor.getWriteMethod().getName());
                    getters.add(propertyDescriptor.getReadMethod().getName());
                    types.add(persistentProperty.getType());
                }
            } else {
                propertyAccess.set(false);
                brokenProperties.add(persistentProperty);
            }
        }

        if (propertyAccess.get())
            // create properties extract for all persistent properties
            bulkBean = BulkBean.create(delegate.getType(), getters.toArray(new String[getters.size()]),
                    setters.toArray(new String[setters.size()]), types.toArray(new Class[types.size()]));
        else
            Log.warn(String.format(
                    "PropetiesSerializer-%s unable to use getters-setters access optimization. Suspected/Corrupted properties = %s",
                    delegate.getType().getSimpleName(), getBrokenProperties()));

        boolean canOptimizeIdProperty = hasReadWriteMethods(delegate.getIdProperty());
        boolean canOptimizeVersionProperty = hasReadWriteMethods(getOptimisticLockVersionProperty());
        boolean canOptimizeRoutingProperty = hasReadWriteMethods(getRoutingProperty());

        // create id/version/routing bulk fields extractor
        if (canOptimizeIdProperty && canOptimizeVersionProperty && canOptimizeRoutingProperty) {
            String[] g = new String[] {
                    delegate.getIdProperty().getPropertyDescriptor().getReadMethod().getName(),
                    getOptimisticLockVersionProperty().getPropertyDescriptor().getReadMethod().getName(),
                    getRoutingProperty().getPropertyDescriptor().getReadMethod().getName() };
            String[] s = new String[] {
                    delegate.getIdProperty().getPropertyDescriptor().getWriteMethod().getName(),
                    getOptimisticLockVersionProperty().getPropertyDescriptor().getWriteMethod().getName(),
                    getRoutingProperty().getPropertyDescriptor().getWriteMethod().getName() };
            Class<?>[] c = new Class[] { delegate.getIdProperty().getType(),
                    getOptimisticLockVersionProperty().getType(), getRoutingProperty().getType() };

            idVersionRoutingBulkBean = BulkBean.create(delegate.getType(), g, s, c);
        }
    }
}

From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java

public static DatabaseObject read(Node node) throws EngineException {
    String objectClassName = "n/a";
    String childNodeName = "n/a";
    String propertyName = "n/a";
    String propertyValue = "n/a";
    DatabaseObject databaseObject = null;
    Element element = (Element) node;

    objectClassName = element.getAttribute("classname");

    // Migration to 4.x+ projects
    if (objectClassName.equals("com.twinsoft.convertigo.beans.core.ScreenClass")) {
        objectClassName = "com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass";
    }/*  ww w . jav  a  2  s  .co  m*/

    String version = element.getAttribute("version");
    if ("".equals(version)) {
        version = node.getOwnerDocument().getDocumentElement().getAttribute("beans");
        if (!"".equals(version)) {
            element.setAttribute("version", version);
        }
    }
    // Verifying product version
    if (VersionUtils.compareProductVersion(Version.productVersion, version) < 0) {
        String message = "Unable to create an object of product version superior to the current beans product version ("
                + com.twinsoft.convertigo.beans.Version.version + ").\n" + "Object class: " + objectClassName
                + "\n" + "Object version: " + version;
        EngineException ee = new EngineException(message);
        throw ee;
    }

    try {
        Engine.logBeans.trace("Creating object of class \"" + objectClassName + "\"");
        databaseObject = (DatabaseObject) Class.forName(objectClassName).newInstance();
    } catch (Exception e) {
        String s = node.getNodeName();// XMLUtils.prettyPrintDOM(node);
        String message = "Unable to create a new instance of the object from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "Object version: " + version + "\n"
                + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration before object de-serialization
        databaseObject.preconfigure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data before its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        long priority = new Long(element.getAttribute("priority")).longValue();
        databaseObject.priority = priority;

        Class<? extends DatabaseObject> databaseObjectClass = databaseObject.getClass();
        BeanInfo bi = CachedIntrospector.getBeanInfo(databaseObjectClass);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        NodeList childNodes = element.getChildNodes();
        int len = childNodes.getLength();

        PropertyDescriptor pd;
        Object propertyObjectValue;
        Class<?> propertyType;
        NamedNodeMap childAttributes;
        boolean maskValue = false;

        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            Element childElement = (Element) childNode;

            childNodeName = childNode.getNodeName();

            Engine.logBeans.trace("Analyzing node '" + childNodeName + "'");

            if (childNodeName.equalsIgnoreCase("property")) {
                childAttributes = childNode.getAttributes();
                propertyName = childAttributes.getNamedItem("name").getNodeValue();
                Engine.logBeans.trace("  name = '" + propertyName + "'");
                pd = findPropertyDescriptor(pds, propertyName);
                if (pd == null) {
                    Engine.logBeans.warn(
                            "Unable to find the definition of property \"" + propertyName + "\"; skipping.");
                    continue;
                }
                propertyType = pd.getPropertyType();
                propertyObjectValue = XMLUtils
                        .readObjectFromXml((Element) XMLUtils.findChildNode(childNode, Node.ELEMENT_NODE));

                // Hides value in log trace if needed
                if ("false".equals(childElement.getAttribute("traceable"))) {
                    maskValue = true;
                }
                Engine.logBeans.trace("  value='"
                        + (maskValue ? Visibility.maskValue(propertyObjectValue) : propertyObjectValue) + "'");

                // Decrypts value if needed
                try {
                    if ("true".equals(childElement.getAttribute("ciphered"))) {
                        propertyObjectValue = decryptPropertyValue(propertyObjectValue);
                    }
                } catch (Exception e) {
                }

                propertyObjectValue = databaseObject.compileProperty(propertyType, propertyName,
                        propertyObjectValue);

                if (Enum.class.isAssignableFrom(propertyType)) {
                    propertyObjectValue = EnumUtils.valueOf(propertyType, propertyObjectValue);
                }

                propertyValue = propertyObjectValue.toString();

                Method setter = pd.getWriteMethod();
                Engine.logBeans.trace("  setter='" + setter.getName() + "'");
                Engine.logBeans.trace("  param type='" + propertyObjectValue.getClass().getName() + "'");
                Engine.logBeans.trace("  expected type='" + propertyType.getName() + "'");
                try {
                    setter.invoke(databaseObject, new Object[] { propertyObjectValue });
                } catch (InvocationTargetException e) {
                    Throwable targetException = e.getTargetException();
                    Engine.logBeans.warn("Unable to set the property '" + propertyName + "' for the object '"
                            + databaseObject.getName() + "' (" + objectClassName + "): ["
                            + targetException.getClass().getName() + "] " + targetException.getMessage());
                }

                if (Boolean.TRUE.equals(pd.getValue("nillable"))) {
                    Node nodeNull = childAttributes.getNamedItem("isNull");
                    String valNull = (nodeNull == null) ? "false" : nodeNull.getNodeValue();
                    Engine.logBeans.trace("  treats as null='" + valNull + "'");
                    try {
                        Method method = databaseObject.getClass().getMethod("setNullProperty",
                                new Class[] { String.class, Boolean.class });
                        method.invoke(databaseObject, new Object[] { propertyName, Boolean.valueOf(valNull) });
                    } catch (Exception ex) {
                        Engine.logBeans.warn("Unable to set the 'isNull' attribute for property '"
                                + propertyName + "' of '" + databaseObject.getName() + "' object");
                    }
                }
            }
        }
    } catch (Exception e) {
        String message = "Unable to set the object properties from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML analyzed node: " + childNodeName + "\n"
                + "Property name: " + propertyName + "\n" + "Property value: " + propertyValue;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration
        databaseObject.configure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data after its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    return databaseObject;
}

From source file:org.evergreen.web.utils.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>/*  w w  w. j  ava2 s .  c o m*/
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {
    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String[] values = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    Resolver resolver = getPropertyUtils().getResolver();
    while (resolver.hasNested(name)) {
        try {
            target = getPropertyUtils().getProperty(target, resolver.next(name));
            name = resolver.remove(name);
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    Target bean = " + target);
        log.trace("    Target name = " + name);
    }

    // Declare local variables we will require
    String propName = resolver.getProperty(name); // Simple name of target property
    Class type = null; // Java type of target property
    int index = resolver.getIndex(name); // Indexed subscript value (if any)
    String key = resolver.getKey(name); // Mapped key value (if any)

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else if (target instanceof Map) {
        type = Object.class;
    } else if (target != null && target.getClass().isArray() && index >= 0) {
        type = Array.get(target, index).getClass();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else if (key != null) {
            if (descriptor.getReadMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = (value == null) ? Object.class : value.getClass();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String[] values = new String[1];
            values[0] = null;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            newValue = getConvertUtils().convert(value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = convert(value, type);
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String || value == null) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = convert(value, type.getComponentType());
        }
    } else { // Value into scalar
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else {
            newValue = convert(value, type);
        }
    }

    // Invoke the setter method
    try {
        getPropertyUtils().setProperty(target, name, newValue);
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}