Example usage for org.springframework.beans BeanWrapper setPropertyValue

List of usage examples for org.springframework.beans BeanWrapper setPropertyValue

Introduction

In this page you can find the example usage for org.springframework.beans BeanWrapper setPropertyValue.

Prototype

void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException;

Source Link

Document

Set the specified value as current property value.

Usage

From source file:net.sf.juffrou.reflect.spring.BeanWrapperGenericsTests.java

@Test
public void testGenericMapElementWithCollectionValue() {
    GenericBean<?> gb = new GenericBean<Object>();
    gb.setCollectionMap(new HashMap<Number, Collection<? extends Object>>());
    BeanWrapper bw = new JuffrouSpringBeanWrapper(gb);
    bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
    HashSet<Integer> value1 = new HashSet<Integer>();
    value1.add(new Integer(1));
    bw.setPropertyValue("collectionMap[1]", value1);
    assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet);
}

From source file:net.sf.juffrou.reflect.spring.BeanWrapperGenericsTests.java

@Test
public void testGenericLowerBoundedSet() {
    GenericBean<?> gb = new GenericBean<Object>();
    BeanWrapper bw = new JuffrouSpringBeanWrapper(gb);
    bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, true));
    Set<String> input = new HashSet<String>();
    input.add("4");
    input.add("5");
    bw.setPropertyValue("numberSet", input);
    assertTrue(gb.getNumberSet().contains(new Integer(4)));
    assertTrue(gb.getNumberSet().contains(new Integer(5)));
}

From source file:com.alibaba.citrus.service.form.impl.GroupImpl.java

/**
 * group//ww  w .  j a  va 2s.  c o m
 * <p>
 * <code>isValidated()</code><code>false</code>group
 * </p>
 */
public void setProperties(Object object) {
    if (!isValidated() || object == null) {
        return;
    }

    if (isValid()) {
        if (log.isDebugEnabled()) {
            log.debug("Set validated properties of group \"" + getName() + "\" to object "
                    + ObjectUtil.identityToString(object));
        }

        BeanWrapper bean = new BeanWrapperImpl(object);
        getForm().getFormConfig().getPropertyEditorRegistrar().registerCustomEditors(bean);

        for (Field field : getFields()) {
            String propertyName = field.getFieldConfig().getPropertyName();

            if (bean.isWritableProperty(propertyName)) {
                PropertyDescriptor pd = bean.getPropertyDescriptor(propertyName);
                MethodParameter mp = BeanUtils.getWriteMethodParameter(pd);
                Object value = field.getValueOfType(pd.getPropertyType(), mp, null);

                bean.setPropertyValue(propertyName, value);
            } else {
                log.debug("No writable property \"{}\" found in type {}", propertyName,
                        object.getClass().getName());
            }
        }
    } else {
        throw new InvalidGroupStateException("Attempted to call setProperties from an invalid input");
    }
}

From source file:org.jdal.swing.ListTableModel.java

/**
 * {@inheritDoc}/*w w  w .  j  ava  2  s  .c  o m*/
 */
public void setValueAt(Object value, int rowIndex, int columnIndex) {
    if (isCheckColum(columnIndex)) {
        checks.set(rowIndex, (Boolean) value);
        // sync selectedRowSet
        Object row = list.get(rowIndex);

        if (Boolean.TRUE.equals(value))
            selectedRowSet.add((Serializable) getPrimaryKey(row));
        else
            selectedRowSet.remove(getPrimaryKey(row));

    } else if (isPropertyColumn(columnIndex)) {
        int index = columnToPropertyIndex(columnIndex);
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(list.get(rowIndex));
        bw.setPropertyValue(columnNames.get(index), value);
        fireTableCellUpdated(rowIndex, columnIndex);
    }
}

From source file:net.sourceforge.vulcan.web.struts.actions.ManagePluginAction.java

public final ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    final PluginConfigForm configForm = (PluginConfigForm) form;
    final String target = configForm.getTarget();

    final BeanWrapper bw = new BeanWrapperImpl(form);

    final Class<?> type = PropertyUtils.getPropertyType(form, target).getComponentType();
    final int i;

    Object[] array = (Object[]) bw.getPropertyValue(target);

    if (array == null) {
        array = (Object[]) Array.newInstance(type, 1);
        i = 0;//from www . j a  v  a  2 s. c  om
    } else {
        i = array.length;
        Object[] tmp = (Object[]) Array.newInstance(type, i + 1);
        System.arraycopy(array, 0, tmp, 0, i);
        array = tmp;
    }

    array[i] = stateManager.getPluginManager().createObject(configForm.getPluginId(), type.getName());

    bw.setPropertyValue(target, array);

    configForm.setFocus(target + "[" + i + "]");
    configForm.introspect(request);

    setHelpAttributes(request, configForm);

    return mapping.findForward("configure");
}

From source file:org.brushingbits.jnap.common.bean.cloning.BeanCloner.java

private Object cloneBean(Object bean, Class<?> type) {
    BeanWrapper source = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    BeanWrapper copy = PropertyAccessorFactory.forBeanPropertyAccess(BeanUtils.instantiate(type));

    // keep instance for circular and multiple references
    context.setAsVisited(bean);/*from ww  w. j  ava  2 s .c om*/
    alreadyCloned.put(bean, copy.getWrappedInstance());

    PropertyDescriptor[] beanProperties = copy.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : beanProperties) {
        String name = propertyDescriptor.getName();
        context.pushPath(name);
        if (copy.isReadableProperty(name) && copy.isWritableProperty(name)) {
            Object value = source.getPropertyValue(name);
            copy.setPropertyValue(name, clone(value));
        }
        context.popPath();
    }
    Object beanCopy = copy.getWrappedInstance();
    source = null;
    copy = null;
    return beanCopy;
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
  * Overwrites the values of the bean in parameter with the form values
  * @param source//from  ww  w. ja  v a 2s.  c  o  m
  * @return
  */
public <R> void mergeInto(R source) {

    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        BeanWrapper beanWrapper = new BeanWrapperImpl(source);
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                beanWrapper.setPropertyValue(fieldName, field.value());
            }
        } catch (InvalidPropertyException ex) {
            logger.log(Level.WARNING, "Form property not in source");
        }
    }
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
 * Creates a Bean of the given class type from the form values
 * @param cls class of the result bean/*from   w w w  . j a  va  2s.  co m*/
 * @param <R> type of the bean
 * @return
 */
public <R> R deriveBean(Class<R> cls) {

    R result = null;
    try {
        result = cls.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        logger.log(Level.WARNING, "Could not instantiate derived bean", e);
        return null;
    }

    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        BeanWrapper beanWrapper = new BeanWrapperImpl(result);
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                beanWrapper.setPropertyValue(fieldName, field.value());
            }
        } catch (InvalidPropertyException ex) {
            logger.log(Level.WARNING, "Form property not in bean");
        }

    }

    return result;
}

From source file:org.jdto.spring.BeanWrapperBeanModifier.java

/**
 * Set a property using the property path invoking a spring framework {@link BeanWrapper}.
 * @param propertyPath//from w  w w  . j a  va2s.  c  om
 * @param value
 * @param instance 
 */
@Override
public void doWritePropertyValue(String propertyPath, Object value, Object instance) {
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(instance);

    //check and make up for missing association parts.
    StringBuilder builder = new StringBuilder();

    String[] subProps = StringUtils.split(propertyPath, '.');

    //go through all the parts but one
    for (int i = 0; i < subProps.length - 1; i++) {
        String prop = subProps[i];

        if (i > 0) {
            builder.append(".");
        }

        builder.append(prop);

        Object partialValue = beanWrapper.getPropertyValue(builder.toString());
        if (partialValue == null) {
            //make up for it
            Class propCls = beanWrapper.getPropertyType(builder.toString());
            Object madeUpValue = BeanClassUtils.createInstance(propCls);
            if (madeUpValue != null) {
                if (beanWrapper.isWritableProperty(builder.toString())) {
                    beanWrapper.setPropertyValue(builder.toString(), madeUpValue);
                }
            }
        }
    }

    if (!beanWrapper.isWritableProperty(propertyPath)) {
        logger.info("Cannot write property path " + propertyPath + " of bean", instance);
        return;
    }

    //this can be improved by registering property editors on the bean wrapper
    //at moment this approach is not so simple as the current functionality.
    //nevertheless on the future this situation may change.
    Class expectedType = beanWrapper.getPropertyType(propertyPath);
    value = ValueConversionHelper.applyCompatibilityLogic(expectedType, value);

    beanWrapper.setPropertyValue(propertyPath, value);
}

From source file:net.sf.juffrou.reflect.spring.BeanWrapperGenericsTests.java

@Test
public void testGenericMapWithCollectionValue() {
    GenericBean<?> gb = new GenericBean<Object>();
    BeanWrapper bw = new JuffrouSpringBeanWrapper(gb);
    bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
    @SuppressWarnings("unchecked")
    Map<String, Collection> input = new HashMap<String, Collection>();
    HashSet<Integer> value1 = new HashSet<Integer>();
    value1.add(new Integer(1));
    input.put("1", value1);
    ArrayList<Boolean> value2 = new ArrayList<Boolean>();
    value2.add(Boolean.TRUE);//w  ww  .  j  a  v a  2 s  .  c om
    input.put("2", value2);
    bw.setPropertyValue("collectionMap", input);
    assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet);
    assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList);
}