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:de.xwic.appkit.core.transport.xml.XmlBeanSerializer.java

/**
 * Deserializes an element into a bean.//from w w w . j ava2  s.c  o m
 * 
 * @param elm
 * @param context
 * @return
 * @throws TransportException
 */
public void deserializeBean(Object bean, Element elm, Map<EntityKey, Integer> context,
        boolean forceLoadCollection) throws TransportException {
    // now read the properties
    try {
        BeanInfo bi = Introspector.getBeanInfo(bean.getClass());
        for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
            Method mWrite = pd.getWriteMethod();
            if (!"class".equals(pd.getName()) && mWrite != null && !skipPropertyNames.contains(pd.getName())) {
                Element elmProp = elm.element(pd.getName());
                if (elmProp != null) {
                    Object value = readValue(context, elmProp, pd, forceLoadCollection);
                    mWrite.invoke(bean, new Object[] { value });
                } else {
                    log.warn("The property " + pd.getName()
                            + " is not specified in the xml document. The bean may not be restored completly");
                }
            }
        }
    } catch (Exception e) {
        throw new TransportException("Error deserializing bean: " + e, e);
    }
}

From source file:io.lightlink.dao.mapping.BeanMapper.java

private boolean populateListObjects(Object bean, Map<String, Object> map) {
    boolean lineAdded = false;

    for (Map.Entry<String, BeanMapper> entry : childListMappers.entrySet()) {
        String originalKey = entry.getKey();
        String key = normalizePropertyName(entry.getKey());
        PropertyDescriptor propertyDescriptor = descriptorMap.get(key);
        if (propertyDescriptor == null) {

            LOG.info("Cannot find property for " + entry.getKey() + " in class "
                    + paramClass.getCanonicalName());

        } else {/*w ww  . j  a v a2  s .c o m*/

            Map<String, Object> childData = prepareChildData(originalKey, map);
            try {
                Object childObject = entry.getValue().convertObject(childData, true);

                List list = (List) propertyDescriptor.getReadMethod().invoke(bean);

                if (list == null)
                    propertyDescriptor.getWriteMethod().invoke(bean, list = new ArrayList());

                if (childObject != null)
                    list.add(childObject);

                lineAdded = true;

            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }

    }
    return lineAdded;
}

From source file:org.kuali.rice.kns.web.struts.form.pojo.PojoPropertyUtilsBean.java

@Override
public boolean isWriteable(Object bean, String name) {
    // Validate method parameters
    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }//from ww  w  .  j  a  v a 2 s .c  o  m
    if (name == null) {
        throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'");
    }

    // Remove any subscript from the final name value
    name = getResolver().getProperty(name);

    // Treat WrapDynaBean as special case - may be a read-only property
    // (see Jira issue# BEANUTILS-61)
    if (bean instanceof WrapDynaBean) {
        bean = ((WrapDynaBean) bean).getInstance();
    }

    // Return the requested result
    if (bean instanceof DynaBean) {
        // All DynaBean properties are writeable
        return (((DynaBean) bean).getDynaClass().getDynaProperty(name) != null);
    } else {
        try {
            PropertyDescriptor desc = getPropertyDescriptor(bean, name);
            if (desc != null) {
                Method writeMethod = desc.getWriteMethod();
                if (writeMethod == null) {
                    if (desc instanceof IndexedPropertyDescriptor) {
                        writeMethod = ((IndexedPropertyDescriptor) desc).getIndexedWriteMethod();
                    } else if (desc instanceof MappedPropertyDescriptor) {
                        writeMethod = ((MappedPropertyDescriptor) desc).getMappedWriteMethod();
                    }
                    writeMethod = MethodUtils.getAccessibleMethod(bean.getClass(), writeMethod);
                }
                return (writeMethod != null);
            } else {
                return (false);
            }
        } catch (IllegalAccessException e) {
            return (false);
        } catch (InvocationTargetException e) {
            return (false);
        } catch (NoSuchMethodException e) {
            return (false);
        }
    }

}

From source file:com.interface21.beans.BeanWrapperImpl.java

/**
 * Set an individual field.//from www .j  a va2 s  . c  o m
 * All other setters go through this.
 * @param pv property value to use for update
 * @throws PropertyVetoException if a listeners throws a JavaBeans API veto
 * @throws BeansException if there's a low-level, fatal error
 */
public void setPropertyValue(PropertyValue pv) throws PropertyVetoException, BeansException {

    if (isNestedProperty(pv.getName())) {
        try {
            BeanWrapper nestedBw = getBeanWrapperForNestedProperty(pv.getName());
            nestedBw.setPropertyValue(new PropertyValue(getFinalPath(pv.getName()), pv.getValue()));
            return;
        } catch (NullValueInNestedPathException ex) {
            // Let this through
            throw ex;
        } catch (FatalBeanException ex) {
            // Error in the nested path
            throw new NotWritablePropertyException(pv.getName(), getWrappedClass());
        }
    }

    if (!isWritableProperty(pv.getName())) {
        throw new NotWritablePropertyException(pv.getName(), getWrappedClass());
    }

    PropertyDescriptor pd = getPropertyDescriptor(pv.getName());
    Method writeMethod = pd.getWriteMethod();
    Method readMethod = pd.getReadMethod();
    Object oldValue = null; // May stay null if it's not a readable property
    PropertyChangeEvent propertyChangeEvent = null;

    try {
        if (readMethod != null && eventPropagationEnabled) {
            // Can only find existing value if it's a readable property
            try {
                oldValue = readMethod.invoke(object, new Object[] {});
            } catch (Exception ex) {
                // The getter threw an exception, so we couldn't retrieve the old value.
                // We're not really interested in any exceptions at this point,
                // so we merely log the problem and leave oldValue null
                logger.warn("Failed to invoke getter '" + readMethod.getName()
                        + "' to get old property value before property change: getter probably threw an exception",
                        ex);
            }
        }

        // Old value may still be null
        propertyChangeEvent = createPropertyChangeEventWithTypeConversionIfNecessary(object, pv.getName(),
                oldValue, pv.getValue(), pd.getPropertyType());

        // May throw PropertyVetoException: if this happens the PropertyChangeSupport
        // class fires a reversion event, and we jump out of this method, meaning
        // the change was never actually made
        if (eventPropagationEnabled) {
            vetoableChangeSupport.fireVetoableChange(propertyChangeEvent);
        }

        if (pd.getPropertyType().isPrimitive() && (pv.getValue() == null || "".equals(pv.getValue()))) {
            throw new IllegalArgumentException("Invalid value [" + pv.getValue() + "] for property ["
                    + pd.getName() + "] of primitive type [" + pd.getPropertyType() + "]");
        }

        // Make the change
        if (logger.isDebugEnabled())
            logger.debug("About to invoke write method [" + writeMethod + "] on object of class '"
                    + object.getClass().getName() + "'");
        writeMethod.invoke(object, new Object[] { propertyChangeEvent.getNewValue() });
        if (logger.isDebugEnabled())
            logger.debug("Invoked write method [" + writeMethod + "] ok");

        // If we get here we've changed the property OK and can broadcast it
        if (eventPropagationEnabled)
            propertyChangeSupport.firePropertyChange(propertyChangeEvent);
    } catch (InvocationTargetException ex) {
        if (ex.getTargetException() instanceof PropertyVetoException)
            throw (PropertyVetoException) ex.getTargetException();
        if (ex.getTargetException() instanceof ClassCastException)
            throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
        throw new MethodInvocationException(ex.getTargetException(), propertyChangeEvent);
    } catch (IllegalAccessException ex) {
        throw new FatalBeanException("illegal attempt to set property [" + pv + "] threw exception", ex);
    } catch (IllegalArgumentException ex) {
        throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex);
    }
}

From source file:org.wings.STransferHandler.java

/**
 * Imports the data specified in the Transferable into the given component
 * @param component//from  w w  w .ja  v  a  2 s.co m
 * @param transferable
 * @return
 */
public boolean importData(SComponent component, Transferable transferable) {
    PropertyDescriptor propertyDecsriptor = getPropertyDescriptor(this.propertyName, component);
    if (propertyDecsriptor == null)
        return false;
    Method writeMethod = propertyDecsriptor.getWriteMethod();
    if (writeMethod == null)
        return false;
    Class<?>[] arguments = writeMethod.getParameterTypes();
    if (arguments == null || arguments.length != 1) {
        return false;
    }

    DataFlavor flavor = getPropertyDataFlavor(arguments[0], transferable.getTransferDataFlavors());
    if (flavor != null) {
        try {
            Object value = transferable.getTransferData(flavor);

            STransferHandler.invoke(writeMethod, component, new Object[] { value });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

private <T> T copyResultSetToObject(ResultSet resultSet, Class<T> kind)
        throws SQLException, WPBSerializerException {
    try {/*from   ww  w.j  av  a2  s .c om*/
        T result = kind.newInstance();
        Field[] fields = kind.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            boolean storeField = (field.getAnnotation(WPBAdminFieldKey.class) != null)
                    || (field.getAnnotation(WPBAdminFieldStore.class) != null)
                    || (field.getAnnotation(WPBAdminFieldTextStore.class) != null);
            if (storeField) {
                String fieldName = field.getName();
                String fieldNameUpperCase = field.getName().toUpperCase();
                PropertyDescriptor pd = new PropertyDescriptor(fieldName, kind);
                // get the field type
                if (field.getType() == Long.class) {
                    Long value = resultSet.getLong(fieldNameUpperCase);
                    pd.getWriteMethod().invoke(result, value);
                } else if (field.getType() == String.class) {
                    String value = resultSet.getString(fieldNameUpperCase);
                    pd.getWriteMethod().invoke(result, value);
                } else if (field.getType() == Integer.class) {
                    Integer value = resultSet.getInt(fieldNameUpperCase);
                    pd.getWriteMethod().invoke(result, value);
                } else if (field.getType() == Date.class) {
                    Timestamp ts = resultSet.getTimestamp(fieldNameUpperCase);
                    Date value = new Date(ts.getTime());
                    pd.getWriteMethod().invoke(result, value);

                }
            }
        }
        return result;
    } catch (Exception e) {
        throw new WPBSerializerException("Cannot deserialize from Result Set", e);
    }
}

From source file:org.kuali.kfs.module.cam.document.service.impl.AssetPaymentServiceImpl.java

/**
 * @see org.kuali.kfs.module.cam.document.service.AssetPaymentService#adjustPaymentAmounts(org.kuali.kfs.module.cam.businessobject.AssetPayment,
 *      boolean, boolean)//w  ww.ja  va 2  s.  c  om
 */
public void adjustPaymentAmounts(AssetPayment assetPayment, boolean reverseAmount,
        boolean nullPeriodDepreciation) throws IllegalAccessException, InvocationTargetException {
    LOG.debug("Starting - adjustAmounts() ");
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(AssetPayment.class);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && propertyDescriptor.getPropertyType() != null
                && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
            KualiDecimal amount = (KualiDecimal) readMethod.invoke(assetPayment);
            Method writeMethod = propertyDescriptor.getWriteMethod();
            if (writeMethod != null && amount != null) {
                // Reset periodic depreciation expenses
                if (nullPeriodDepreciation
                        && Pattern.matches(CamsConstants.SET_PERIOD_DEPRECIATION_AMOUNT_REGEX,
                                writeMethod.getName().toLowerCase())) {
                    Object[] nullVal = new Object[] { null };
                    writeMethod.invoke(assetPayment, nullVal);
                } else if (reverseAmount) {
                    // reverse the amounts
                    writeMethod.invoke(assetPayment, (amount.negated()));
                }
            }

        }
    }
    LOG.debug("Finished - adjustAmounts()");
}

From source file:org.wings.STransferHandler.java

/**
 * Returns whether if this component can import one of the Transfers DataFlavors  
 * @param component/*www.  j a  v  a2  s .  c om*/
 * @param transferFlavors
 * @return
 */
public boolean canImport(SComponent component, DataFlavor[] transferFlavors) {
    PropertyDescriptor propertyDescriptor = getPropertyDescriptor(propertyName, component);

    if (propertyDescriptor == null)
        return false;

    // get the writer Method
    Method writeMethod = propertyDescriptor.getWriteMethod();
    if (writeMethod == null)
        return false;

    // get arguments of writeMethod
    Class<?>[] arguments = writeMethod.getParameterTypes();
    if (arguments == null || arguments.length != 1)
        return false;

    // check if the argument type matches one of the transferflavors
    DataFlavor flavor = getPropertyDataFlavor(arguments[0], transferFlavors);
    if (flavor == null)
        return false;

    return true;
}

From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java

/**
 * Writes bean description recursively.//from  w  w  w  .j a v  a2 s . co  m
 *
 * @param jgen
 *         to write to
 * @param currentVocab
 *         in context
 * @param valueType
 *         class of value
 * @param allRootParameters
 *         of the method that receives the request body
 * @param rootParameter
 *         the request body
 * @param currentCallValue
 *         the value at the current recursion level
 * @param propertyPath
 *         of the current recursion level
 * @throws IntrospectionException
 * @throws IOException
 */
private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType,
        ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue,
        String propertyPath) throws IntrospectionException, IOException {

    Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>();

    // collect supported properties from ctor

    Constructor[] constructors = valueType.getConstructors();
    // find default ctor
    Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
    // find ctor with JsonCreator ann
    if (constructor == null) {
        constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
    }
    if (constructor == null) {
        // TODO this can be a generic collection, find a way to describe it
        LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type "
                + valueType.getName());
        return;
    }

    int parameterCount = constructor.getParameterTypes().length;
    if (parameterCount > 0) {
        Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

        Class[] parameters = constructor.getParameterTypes();
        int paramIndex = 0;
        for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
            for (Annotation annotation : annotationsOnParameter) {
                if (JsonProperty.class == annotation.annotationType()) {
                    JsonProperty jsonProperty = (JsonProperty) annotation;
                    // TODO use required attribute of JsonProperty
                    String paramName = jsonProperty.value();

                    Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName);

                    ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter(
                            new MethodParameter(constructor, paramIndex), propertyValue);

                    // TODO collect ctor params, setter params and process
                    // TODO then handle single, collection and bean for both
                    properties.put(paramName, constructorParamInputParameter);
                    paramIndex++; // increase for each @JsonProperty
                }
            }
        }
        Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                + constructor.getName() + " are annotated with @JsonProperty");
    }

    // collect supported properties from setters

    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(valueType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map
    // TODO distinguish which properties should be printed as supported - now just setters
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);

        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                propertyDescriptor.getName());

        MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);
        ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter,
                propertyValue);

        properties.put(propertyName, propertySetterInputParameter);
    }

    // write all supported properties
    // TODO we are using the annotatedParameter.parameterName but should use the key of properties here:
    for (ActionInputParameter annotatedParameter : properties.values()) {
        String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName()
                : propertyPath + '.' + annotatedParameter.getParameterName();
        if (DataType.isSingleValueType(annotatedParameter.getParameterType())) {

            final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters);

            if (rootParameter.isIncluded(nextPropertyPathLevel)
                    && !rootParameter.isExcluded(nextPropertyPathLevel)) {
                writeSupportedProperty(jgen, currentVocab, annotatedParameter,
                        annotatedParameter.getParameterName(), possiblePropertyValues);
            }
            // TODO collections?
            //                        } else if (DataType.isArrayOrCollection(parameterType)) {
            //                            Object[] callValues = rootParameter.getValues();
            //                            int items = callValues.length;
            //                            for (int i = 0; i < items; i++) {
            //                                Object value;
            //                                if (i < callValues.length) {
            //                                    value = callValues[i];
            //                                } else {
            //                                    value = null;
            //                                }
            //                                recurseSupportedProperties(jgen, currentVocab, rootParameter
            // .getParameterType(),
            //                                        allRootParameters, rootParameter, value);
            //                            }
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", annotatedParameter.getParameterName());
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = annotatedParameter.getParameterType().getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                    annotatedParameter.getParameterName());

            recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(),
                    allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

From source file:org.carewebframework.shell.designer.PropertyEditorCustomTree.java

/**
 * Returns true if the class has a writable label property.
 * /*  w w  w  . j a v  a 2 s . co m*/
 * @param clazz The class to check.
 * @return True if a writable label property exists.
 */
private boolean hasLabelProperty(Class<?> clazz) {
    try {
        PropertyDescriptor pd = labelProperty == null ? null
                : BeanUtils.getPropertyDescriptor(clazz, labelProperty);
        return pd != null && pd.getWriteMethod() != null;
    } catch (Exception e) {
        return false;
    }
}