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:com.hihsoft.baseclass.web.controller.BaseController.java

/**
 * ???(xiaojf?)//from   ww w .j  a  v  a2  s .c  om
 */
@Override
protected void bind(final HttpServletRequest request, final Object command) {
    final PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(command.getClass());
    for (final PropertyDescriptor pd : pds) {
        final Class<?> clas = pd.getPropertyType();// ?class
        final boolean isSimpleProperty = BeanUtils.isSimpleProperty(clas);
        final boolean isInterface = clas.isInterface();
        final boolean hasConstruct = clas.getConstructors().length == 0 ? false : true;
        if (!isSimpleProperty && !isInterface && hasConstruct) {
            // 
            try {
                pd.getWriteMethod().invoke(command, clas.newInstance());
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    try {
        super.bind(request, command);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:ca.sqlpower.dao.SPPersisterListener.java

public void propertyChanged(PropertyChangeEvent evt) {
    SPObject source = (SPObject) evt.getSource();
    String uuid = source.getUUID();
    String propertyName = evt.getPropertyName();
    Object oldValue = evt.getOldValue();
    Object newValue = evt.getNewValue();

    try {/*w w  w  .  j  a  v  a2s .  co m*/
        if (!PersisterHelperFinder.findPersister(source.getClass()).getPersistedProperties()
                .contains(propertyName)) {
            logger.debug(
                    "Tried to persist a property that shouldn't be. Ignoring the property: " + propertyName);
            return;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (!((SPObject) evt.getSource()).getRunnableDispatcher().isForegroundThread()) {
        throw new RuntimeException("Property change " + evt + " not fired on the foreground.");
    }

    Object oldBasicType = converter.convertToBasicType(oldValue);
    Object newBasicType = converter.convertToBasicType(newValue);

    PersistedSPOProperty property = null;
    for (PersistedSPOProperty p : persistedProperties.get(uuid)) {
        if (p.getPropertyName().equals(propertyName)) {
            property = p;
            break;
        }
    }
    if (property != null) {
        boolean valuesMatch;
        if (property.getNewValue() == null) {
            valuesMatch = oldBasicType == null;
        } else {
            // Check that the old property's new value is equal to the new change's old value.
            // Also, accept the change if it is the same as the last one.
            valuesMatch = property.getNewValue().equals(oldBasicType)
                    || (property.getOldValue().equals(oldBasicType)
                            && property.getNewValue().equals(newBasicType));
        }
        if (!valuesMatch) {
            try {
                throw new RuntimeException("Multiple property changes do not follow after each other properly. "
                        + "Property " + property.getPropertyName() + ", on object " + source + " of type "
                        + source.getClass() + ", Old " + oldBasicType + ", new " + property.getNewValue());
            } finally {
                this.rollback();
            }
        }
    }

    if (wouldEcho()) {
        //The persisted property was changed by a persist call received from the server.
        //The property is removed from the persist calls as it now matchs what is
        //in the server.
        persistedProperties.remove(uuid, property);
        return;
    }

    transactionStarted(TransactionEvent.createStartTransactionEvent(this,
            "Creating start transaction event from propertyChange on object "
                    + evt.getSource().getClass().getSimpleName() + " and property name "
                    + evt.getPropertyName()));

    //Not persisting non-settable properties.
    //TODO A method in the persister helpers would make more sense than
    //using reflection here.
    PropertyDescriptor propertyDescriptor;
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(source, propertyName);
    } catch (Exception ex) {
        this.rollback();
        throw new RuntimeException(ex);
    }

    if (propertyDescriptor == null || propertyDescriptor.getWriteMethod() == null) {
        transactionEnded(TransactionEvent.createEndTransactionEvent(this));
        return;
    }

    DataType typeForClass = PersisterUtils.getDataType(newValue == null ? Void.class : newValue.getClass());

    boolean unconditional = false;
    if (property != null) {
        // Hang on to the old value
        oldBasicType = property.getOldValue();
        // If an object was created, and unconditional properties are being sent,
        // this will maintain that flag in the event of additional property changes
        // to the same property in the same transaction.
        unconditional = property.isUnconditional();
        persistedProperties.remove(uuid, property);
    }
    logger.debug("persistProperty(" + uuid + ", " + propertyName + ", " + typeForClass.name() + ", " + oldValue
            + ", " + newValue + ")");
    persistedProperties.put(uuid, new PersistedSPOProperty(uuid, propertyName, typeForClass, oldBasicType,
            newBasicType, unconditional));

    this.transactionEnded(TransactionEvent.createEndTransactionEvent(this));
}

From source file:org.openspotlight.persist.support.SimplePersistImpl.java

private void fillBeanParent(final List<PropertyDescriptor> parentPropertyDescriptors, final Object bean,
        final Object beanParent) throws Exception {
    if (beanParent != null) {
        final Class<?> parentType = beanParent.getClass();
        for (final PropertyDescriptor descriptor : parentPropertyDescriptors) {
            if (descriptor.getPropertyType().isAssignableFrom(parentType)) {
                descriptor.getWriteMethod().invoke(bean, beanParent);
                break;
            }//from   w  w  w .  ja  v  a 2 s .  co m
        }
    }
}

From source file:org.pentaho.reporting.engine.classic.core.util.beans.BeanUtility.java

private void setProperty(final PropertySpecification name, final Object o) throws BeanException {
    final PropertyDescriptor pd = properties.get(name.getName());
    if (pd == null) {
        throw new BeanException("No such property:" + name);
    }//  www.j a v a  2s .  c  o m

    if (pd instanceof IndexedPropertyDescriptor && name.getIndex() != null) {
        final IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
        final Method writeMethod = ipd.getIndexedWriteMethod();
        if (writeMethod != null) {
            try {
                writeMethod.invoke(bean, new Integer(name.getIndex()), o);
            } catch (Exception e) {
                throw BeanException.getInstance("InvokationError", e);
            }
            // we've done the job ...
            return;
        }
    }

    final Method writeMethod = pd.getWriteMethod();
    if (writeMethod == null) {
        throw BeanException.getInstance("Property is not writeable: " + name, null);
    }

    if (name.getIndex() != null) {
        // this is a indexed access, but no indexWrite method was found ...
        updateArrayProperty(pd, name, o);
    } else {
        try {
            writeMethod.invoke(bean, o);
        } catch (Exception e) {
            throw BeanException.getInstance(
                    "InvokationError on property '" + name + "' on bean type " + bean.getClass(), e);
        }
    }
}

From source file:org.etudes.ambrosia.impl.UiPropertyReference.java

/**
 * Write the value.//from   www.  j a v a 2  s. c  o  m
 * 
 * @param entity
 *        The entity to write to.
 * @param property
 *        The property to set.
 * @param value
 *        The value to write.
 */
protected void setValue(Object entity, String property, String[] valueSource) {
    // form a "setFoo()" based setter method name
    StringBuffer setter = new StringBuffer("set" + property);
    setter.setCharAt(3, setter.substring(3, 4).toUpperCase().charAt(0));

    // unformat the values - in any are invalid, give up
    String[] value = null;
    try {
        if (valueSource != null) {
            value = new String[valueSource.length];
            for (int i = 0; i < valueSource.length; i++) {
                value[i] = StringUtil.trimToNull(unFormat(valueSource[i]));
            }
        }
    } catch (IllegalArgumentException e) {
        return;
    }

    try {
        // use this form, providing the setter name and no getter, so we can support properties that are write-only
        PropertyDescriptor pd = new PropertyDescriptor(property, entity.getClass(), null, setter.toString());
        Method write = pd.getWriteMethod();
        Object[] params = new Object[1];
        params[0] = null;

        Class[] paramTypes = write.getParameterTypes();
        if ((paramTypes != null) && (paramTypes.length == 1)) {
            // single value boolean
            if (paramTypes[0] == Boolean.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Boolean.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value boolean
            else if (paramTypes[0] == Boolean[].class) {
                if (value != null) {
                    Boolean[] values = new Boolean[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Boolean.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value long
            else if (paramTypes[0] == Long.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Long.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value long
            else if (paramTypes[0] == Long[].class) {
                if (value != null) {
                    Long[] values = new Long[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Long.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value int
            else if (paramTypes[0] == Integer.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Integer.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value int
            else if (paramTypes[0] == Integer[].class) {
                if (value != null) {
                    Integer[] values = new Integer[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Integer.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value Date
            else if (paramTypes[0] == Date.class) {
                // assume a long ms format
                params[0] = ((value != null) && (value[0] != null)) ? new Date(Long.parseLong(value[0])) : null;
            }

            // multiple value Date
            else if (paramTypes[0] == Date[].class) {
                if (value != null) {
                    Date[] values = new Date[value.length];
                    for (int i = 0; i < value.length; i++) {
                        // assume a long ms format
                        values[i] = new Date(Long.parseLong(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value string
            else if (paramTypes[0] == String.class) {
                params[0] = ((value != null) && (value[0] != null)) ? StringUtil.trimToNull(value[0]) : null;
            }

            // multiple value string
            else if (paramTypes[0] == String[].class) {
                // trim it
                if (value != null) {
                    for (int i = 0; i < value.length; i++) {
                        value[i] = StringUtil.trimToNull(value[i]);
                    }
                }

                params[0] = value;
            }

            // single value enum
            else if (paramTypes[0].isEnum()) {
                if ((value == null) || (value[0] == null)) {
                    params[0] = null;
                } else {
                    Object[] constants = paramTypes[0].getEnumConstants();
                    if (constants != null) {
                        // see if value matches any of these
                        for (Object o : constants) {
                            if (o.toString().equals(value[0])) {
                                params[0] = o;
                                break;
                            }
                        }
                    }
                }
            }

            // single value float
            else if (paramTypes[0] == Float.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Float.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value float
            else if (paramTypes[0] == Float[].class) {
                if (value != null) {
                    Float[] values = new Float[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Float.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // multiple value string in list
            else if (paramTypes[0] == List.class) {
                if (value != null) {
                    // trim it into a List
                    List valueList = new ArrayList(value.length);
                    if (value != null) {
                        for (int i = 0; i < value.length; i++) {
                            String v = StringUtil.trimToNull(value[i]);
                            if (v != null) {
                                valueList.add(v);
                            }
                        }
                    }

                    params[0] = valueList;
                }
            }

            // multiple value string in set
            else if (paramTypes[0] == Set.class) {
                if (value != null) {
                    // trim it into a List
                    Set valueSet = new HashSet(value.length);
                    for (int i = 0; i < value.length; i++) {
                        String v = StringUtil.trimToNull(value[i]);
                        if (v != null) {
                            valueSet.add(v);
                        }
                    }

                    params[0] = valueSet;
                }
            }

            // TODO: other types
            else {
                M_log.warn("setValue: unhandled setter parameter type - not set: " + paramTypes[0]);
                return;
            }

            write.invoke(entity, params);
        } else {
            M_log.warn("setValue: method: " + property + " object: " + entity.getClass()
                    + " : no one parameter setter method defined");
        }
    } catch (NumberFormatException ie) {
    } catch (IntrospectionException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (IllegalAccessException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (IllegalArgumentException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (InvocationTargetException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    }
}

From source file:nl.strohalm.cyclos.services.customization.BaseCustomFieldServiceImpl.java

@SuppressWarnings("unchecked")
private void copyParentProperties(final CustomField parent, final CustomField child) {
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(parent);
    for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final String name = propertyDescriptor.getName();
        final boolean isWritable = propertyDescriptor.getWriteMethod() != null;
        final boolean isReadable = propertyDescriptor.getReadMethod() != null;
        if (isReadable && isWritable && !EXCLUDED_PROPERTIES_FOR_DEPENDENT_FIELDS.contains(name)) {
            Object value = PropertyHelper.get(parent, name);
            if (value instanceof Collection) {
                value = new ArrayList<Object>((Collection<Object>) value);
            }//from   ww  w . j av a 2 s . c om
            PropertyHelper.set(child, name, value);
        }
    }
}

From source file:org.oddjob.framework.WrapDynaClass.java

/**
 * Introspect our bean class to identify the supported properties.
 *///  w  w  w.j  a va 2 s. c  o m
protected void introspect(Class<?> beanClass) {
    Set<String> mismatched = new HashSet<String>();

    // first find simple and indexed properties via usual means.
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    for (int i = 0; i < descriptors.length; ++i) {
        PropertyDescriptor descriptor = descriptors[i];

        String propertyName = descriptor.getName();

        DynaProperty dynaProperty;
        // indexed property?
        if (descriptor instanceof IndexedPropertyDescriptor) {
            dynaProperty = new DynaProperty(propertyName, descriptor.getPropertyType(),
                    ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType());
        }
        // else a simple property.
        else {
            dynaProperty = new DynaProperty(propertyName, descriptor.getPropertyType());
        }

        propertiesMap.put(propertyName, dynaProperty);

        // update readable writable
        if (MethodUtils.getAccessibleMethod(descriptor.getReadMethod()) != null) {
            readableProperties.add(propertyName);
        }
        if (MethodUtils.getAccessibleMethod(descriptor.getWriteMethod()) != null) {
            writableProperties.add(propertyName);
        }
    }

    // now find mapped properties.
    Method[] methods = beanClass.getMethods();
    for (int i = 0; i < methods.length; ++i) {
        Method method = methods[i];

        // methods beginning with get could be properties.          
        if (!method.getName().startsWith("get") && !method.getName().startsWith("set")) {
            continue;
        }

        String propertyName = method.getName().substring(3);
        // get on it's own is not a property
        if (propertyName.length() == 0) {
            continue;
        }

        // lowercase first letter
        propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);

        Class<?>[] args = method.getParameterTypes();

        DynaProperty dynaProperty = null;

        boolean readable = false;
        boolean writable = false;

        // is mapped property?
        if (method.getName().startsWith("get") && Void.TYPE != method.getReturnType() && args.length == 1
                && args[0] == String.class) {
            DynaProperty existing = (DynaProperty) propertiesMap.get(propertyName);
            if (existing != null && !existing.isMapped()) {
                mismatched.add(propertyName);
                continue;
            }
            dynaProperty = new DynaProperty(propertyName, Map.class, method.getReturnType());
            readable = true;
        } else if (args.length == 2 && args[0] == String.class && Void.TYPE == method.getReturnType()) {
            DynaProperty existing = (DynaProperty) propertiesMap.get(propertyName);
            if (existing != null && !existing.isMapped()) {
                mismatched.add(propertyName);
                continue;
            }
            dynaProperty = new DynaProperty(propertyName, Map.class, args[1]);
            writable = true;
        } else {
            continue;
        }
        propertiesMap.put(propertyName, dynaProperty);

        // update readable writable
        if (readable) {
            readableProperties.add(propertyName);
        }
        if (writable) {
            writableProperties.add(propertyName);
        }
    }

    for (String element : mismatched) {
        propertiesMap.remove(element);
        readableProperties.remove(element);
        writableProperties.remove(element);
    }

    properties = (DynaProperty[]) propertiesMap.values().toArray(new DynaProperty[0]);

}

From source file:be.fgov.kszbcss.rhq.websphere.component.jdbc.db2.pool.ConnectionContextImpl.java

ConnectionContextImpl(Map<String, Object> properties) {
    dataSource = new DB2SimpleDataSource();
    BeanInfo beanInfo;/*from  ww  w .  j  av  a  2s  .  c  om*/
    try {
        beanInfo = Introspector.getBeanInfo(DB2SimpleDataSource.class);
    } catch (IntrospectionException ex) {
        throw new Error(ex);
    }
    for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
        String name = descriptor.getName();
        if (properties.containsKey(name)) {
            Object value = properties.get(name);
            Class<?> propertyType = descriptor.getPropertyType();
            if (log.isDebugEnabled()) {
                log.debug("Setting property " + name + ": propertyType=" + propertyType.getName() + ", value="
                        + value + " (class=" + (value == null ? "<N/A>" : value.getClass().getName()) + ")");
            }
            if (propertyType != String.class && value instanceof String) {
                // Need to convert value to correct type
                if (propertyType == Integer.class || propertyType == Integer.TYPE) {
                    value = Integer.valueOf((String) value);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Converted value to " + value + " (class=" + value.getClass().getName() + ")");
                }
            }
            try {
                descriptor.getWriteMethod().invoke(dataSource, value);
            } catch (IllegalArgumentException ex) {
                throw new RuntimeException("Failed to set '" + name + "' property", ex);
            } catch (IllegalAccessException ex) {
                throw new IllegalAccessError(ex.getMessage());
            } catch (InvocationTargetException ex) {
                Throwable cause = ex.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                } else if (cause instanceof Error) {
                    throw (Error) cause;
                } else {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

/**
 * Creates a new object and initializes its fields from the ResultSet.
 *
 * @param <T> The type of bean to create
 * @param rs The result set./*from  ww  w . j  a  v a 2 s .c  om*/
 * @param type The bean type (the return type of the object).
 * @param props The property descriptors.
 * @param columnToProperty The column indices in the result set.
 * @return An initialized object.
 * @throws SQLException if a database error occurs.
 */
private <T> T createBeanByASM(ResultSet rs, Class<T> mappedClass, String key) throws SQLException {

    DbBeanFactory dynamicRse = DBBEANFACTORY_CACHE.get(key);

    // 
    if (dynamicRse != null) {

        return dynamicRse.createBean(rs, mappedClass);
    }

    T bean = this.newInstance(mappedClass);

    ResultSetMetaData rsmd = rs.getMetaData();

    MethodVisitor mv = null;

    final ClassWriter cw = new ClassWriter(0);

    PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(mappedClass);

    int[] columnToProperty = this.mapColumnsToProperties(rsmd, props);

    String beanName = mappedClass.getName().replace('.', '/');

    String processorName = DynamicClassUtils.getBeanProcessorName(mappedClass);

    String internalProcessorName = processorName.replace('.', '/');

    Object[] labelArr = prepScript(cw, mv, internalProcessorName, beanName);

    mv = (MethodVisitor) labelArr[1];

    Label firstLabel = null;
    PropertyDescriptor desc = null;

    for (int i = 1; i < columnToProperty.length; i++) {

        if (columnToProperty[i] == PROPERTY_NOT_FOUND) {
            continue;
        }

        desc = props[columnToProperty[i]];
        Class<?> propType = desc.getPropertyType();

        if (null == firstLabel) {

            firstLabel = firstLabel(mv, beanName, 12);
        } else {

            visitLabel(mv, 11 + i);
        }

        //  rs.getXXX
        Object value = processColumn(rs, i, propType, desc.getWriteMethod().getName(), internalProcessorName,
                beanName, mv);

        this.callSetter(bean, desc, value);
    }

    if (firstLabel != null) {

        endScript(mv, (Label) labelArr[0], firstLabel, 12 + columnToProperty.length, internalProcessorName,
                beanName);

        cw.visitEnd();

        try {

            DynamicBeanClassLoader beanClassLoader = new DynamicBeanClassLoader(
                    ClassUtils.getDefaultClassLoader());

            Class<?> processor = beanClassLoader.defineClass(processorName, cw.toByteArray());

            DBBEANFACTORY_CACHE.put(key, (DbBeanFactory) processor.newInstance());

        } catch (Exception e) {

            throw new DynamicObjectException("ASM [ " + processorName + " ] ", e);
        }
    }

    return bean;
}