Example usage for org.apache.commons.beanutils PropertyUtils setProperty

List of usage examples for org.apache.commons.beanutils PropertyUtils setProperty

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils setProperty.

Prototype

public static void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Set the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:org.objectstyle.cayenne.modeler.editor.SelectPropertiesPanel.java

void setQueryProperty(String property, Object value) {
    Query query = getQuery();/* w  ww .  ja v a  2 s .co  m*/
    if (query != null) {
        try {
            PropertyUtils.setProperty(query, property, value);
            mediator.fireQueryEvent(new QueryEvent(this, query));
        } catch (Exception ex) {
            logObj.warn("Error setting property: " + property, ex);
        }
    }
}

From source file:org.objectstyle.cayenne.modeler.pref.ComponentGeometry.java

void updateIntProperty(Component c, String property, int defaultValue) {
    int i = getIntProperty(property, defaultValue);
    try {/* w ww .  j  a  v  a  2 s  .  co m*/
        PropertyUtils.setProperty(c, property, new Integer(i));
    } catch (Throwable th) {
        throw new PreferenceException("Error setting property: " + property, th);
    }
}

From source file:org.obm.sync.metadata.DatabaseTruncationServiceImpl.java

@Override
public <T> T getTruncatingEntity(T entity) throws SQLException {
    if (entity == null) {
        return null;
    }//w  w  w. j  a v  a  2 s . c  om

    try {
        T newInstance = (T) entity.getClass().newInstance();
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(entity.getClass());

        for (PropertyDescriptor descriptor : descriptors) {
            Method writeMethod = descriptor.getWriteMethod(), readMethod = descriptor.getReadMethod();

            if (writeMethod != null) {
                String propertyName = descriptor.getName();
                Object value = PropertyUtils.getProperty(entity, propertyName);

                if (readMethod.isAnnotationPresent(DatabaseEntity.class)) {
                    if (value instanceof Collection) {
                        value = copyEntityCollection(value);
                    } else if (value instanceof Map) {
                        value = copyEntityMap(value);
                    } else {
                        value = copyEntity(value);
                    }
                } else {
                    DatabaseField dbField = readMethod.getAnnotation(DatabaseField.class);

                    if (dbField != null && value instanceof String) {
                        value = truncate((String) value, dbField.table(), dbField.column());
                    }
                }

                PropertyUtils.setProperty(newInstance, propertyName, value);
            }
        }

        return newInstance;
    } catch (Exception e) {
        Throwables.propagateIfInstanceOf(e, SQLException.class);

        throw Throwables.propagate(e);
    }
}

From source file:org.openbp.common.property.PropertyAccessUtil.java

/**
 * Sets the value of the specified property of an object.
 * In order to access the property, the method uses the following strategy.
 * We assume the name of the property is "Sample"
 * <ol>// w w w . ja  v a  2  s .  c  o  m
 * <li>Search for a method named get\iSample\i</li>
 * <li>Try direct field access on the member \isample\i</li>
 * <li>Try to use map-style access to properties by calling the method get("Sample")</li>
 * </ol>
 *
 * @param base Object to invoke the method on
 * @param property Property name<br>
 * @param value Property value
 * Property chains of the form "prop1.prop2" are *not* supported.
 * @throws PropertyException If no appropriate access method could be found or if the invocation
 * of one of the property access methods failed.<br>
 * The nested exception describes the error in detail.
 */
public static void setProperty(Object base, String property, Object value) throws PropertyException {
    // TODO Doesn't work for property chains; actually, decapitalization should be removed and the descriptors should be corrected.
    property = StringUtil.decapitalize(property);

    if (base == null)
        throw new PropertyException("Cannot access property '" + property + "' with null base object.");

    Exception ex = null;
    try {
        PropertyUtils.setProperty(base, property, value);
    } catch (NestedNullException e) {
        ex = e;
    } catch (IllegalAccessException e) {
        ex = e;
    } catch (IllegalArgumentException e) {
        ex = e;
    } catch (InvocationTargetException e) {
        ex = e;
    } catch (NoSuchMethodException e) {
        ex = e;
    }
    if (ex != null) {
        String valueType = value != null ? value.getClass().getName() : null;
        throw new PropertyException("Error setting property '" + property + "' of object of type '"
                + base.getClass().getName() + "' to value of type '" + valueType + "'.", ex);
    }
}

From source file:org.openeos.services.ui.vaadin.internal.BlueprintUIVaadinApplicationFactory.java

@SuppressWarnings("unchecked")
@Override//  w w  w  .j a  v  a2 s .  c  o m
public UIApplication<IUnoVaadinApplication> createApplication(IUnoVaadinApplication application) {
    UIApplication<IUnoVaadinApplication> result = (UIApplication<IUnoVaadinApplication>) blueprintContainer
            .getComponentInstance(beanName);
    if (vaadinApplicationPropertyName != null) {
        try {
            PropertyUtils.setProperty(result, vaadinApplicationPropertyName, application);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
    return result;
}

From source file:org.openeos.usertask.ui.internal.notification.UsertaskNotificationFactoryBlueprint.java

@Override
public Notification createUsertaskNotification(NotificationManager notificationManager) {
    Notification notification = (Notification) blueprintContainer.getComponentInstance(beanName);
    try {//from w w  w. j a v  a2 s .com
        PropertyUtils.setProperty(notification, "notificationManager", notificationManager);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        LOG.warn("Impossible set notification manager to notification object", e);
    }
    return notification;

}

From source file:org.openhie.openempi.service.impl.PersonCommonServiceImpl.java

public void populateCustomFields(Person person) {
    List<CustomField> customFields = Context.getConfiguration().getCustomFields();
    TransformationService transformationService = Context.getTransformationService();
    for (CustomField customField : customFields) {
        log.trace("Need to generate a value for field " + customField.getSourceFieldName() + " using function "
                + customField.getTransformationFunctionName() + " and save it as field "
                + customField.getFieldName());
        try {//w  w  w.j a  v a  2  s.com
            Object value = PropertyUtils.getProperty(person, customField.getSourceFieldName());
            log.debug("Obtained a value of " + value + " for field " + customField.getSourceFieldName());
            if (value != null) {
                Object transformedValue = transformationService.transform(
                        customField.getTransformationFunctionName(), value,
                        customField.getConfigurationParameters());
                PropertyUtils.setProperty(person, customField.getFieldName(), transformedValue);
                log.debug("Custom field " + customField.getFieldName() + " has value "
                        + BeanUtils.getProperty(person, customField.getFieldName()));
            }
        } catch (Exception e) {
            log.error("Failed while trying to obtain property for field " + customField.getSourceFieldName()
                    + ":" + e.getMessage(), e);
        }
    }
}

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

private static <T> void generate(Class<T> clazz) {
    Object instance;//ww  w.j a  v a  2 s . c o m

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

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

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

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

    REFERENCES.put(clazz, instance);
}

From source file:org.openmobster.core.mobileObject.TestBeanSyntax.java

private Object initializeSimpleProperty(Object parentObject, String property,
        PropertyDescriptor propertyMetaData) throws Exception {
    Object propertyValue = null;/*from   w w  w.ja v  a2  s  .  co  m*/

    //A Regular Property
    propertyValue = PropertyUtils.getProperty(parentObject, property);
    if (propertyValue == null) {
        Object newlyInitialized = propertyMetaData.getPropertyType().newInstance();
        PropertyUtils.setProperty(parentObject, property, newlyInitialized);
        propertyValue = newlyInitialized;
    }

    return propertyValue;
}

From source file:org.openmobster.core.mobileObject.TestBeanSyntax.java

private Object initializeIndexedProperty(Object parentObject, String property,
        PropertyDescriptor propertyMetaData) throws Exception {
    Object element = null;/*from w  ww.j  av  a2  s .  co m*/

    //Find the Class of the elementType
    Class elementType = null;

    if (!propertyMetaData.getPropertyType().isArray()) {
        ParameterizedType returnType = (ParameterizedType) propertyMetaData.getReadMethod()
                .getGenericReturnType();
        Type[] actualTypes = returnType.getActualTypeArguments();
        for (Type actualType : actualTypes) {
            elementType = (Class) actualType;
        }
    } else {
        elementType = propertyMetaData.getPropertyType().getComponentType();
    }

    //An IndexedProperty
    Object indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());

    //Initialize the IndexedProperty (An Array or Collection)
    if (indexedProperty == null) {
        if (propertyMetaData.getPropertyType().isArray()) {
            //TODO: Remove hardcoded array size                     
            PropertyUtils.setProperty(parentObject, propertyMetaData.getName(),
                    Array.newInstance(elementType, 1));
        } else {
            //Handle Collection Construction
            PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), new ArrayList());
        }
        indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());
    }

    //Check to see if the index specified by the field requires creation of new
    //element
    try {
        element = PropertyUtils.getIndexedProperty(parentObject, property);
    } catch (IndexOutOfBoundsException iae) {
        Object newlyInitialized = elementType.newInstance();

        if (!propertyMetaData.getPropertyType().isArray()) {
            ((Collection) indexedProperty).add(newlyInitialized);
        } else {
            //TODO: Remove hardcoded array index
            Array.set(indexedProperty, 0, newlyInitialized);
        }

        element = newlyInitialized;
    }

    return element;
}