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:io.github.moosbusch.lumpi.gui.form.spi.AbstractDynamicForm.java

protected final Form.Section createSection(Class<?> beanClass, PropertyDescriptor[] propDescs)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Form.Section result = new Form.Section();
    String sectHeading = getSectionHeading();
    Map<String, Class<?>> propertyMap = new HashMap<>();
    propertyMap.setComparator(Comparator.naturalOrder());

    if ((isShowSectionHeading()) && (StringUtils.isNotBlank(sectHeading))) {
        result.setHeading(sectHeading);/*w  w  w  . j  a v  a  2  s  .  c  om*/
    }

    for (PropertyDescriptor propDesc : propDescs) {
        propertyMap.put(propDesc.getName(), propDesc.getPropertyType());
    }

    for (String propertyName : propertyMap) {
        Class<?> propertyClass = ClassUtils.primitiveToWrapper(propertyMap.get(propertyName));

        FormEditor<? extends Component> editor;

        if (!isExcludedProperty(beanClass, propertyName)) {
            editor = getEditor(beanClass.getName(), propertyClass.getName(), propertyName);

            if (editor != null) {
                Component cmp = editor.getComponent();
                PropertyUtils.setProperty(cmp, editor.getDataBindingKeyPropertyName(), propertyName);
                setLabel(cmp, StringUtils.capitalize(propertyName));

                if (editor.isScrollable()) {
                    ScrollPane scroll = Objects.requireNonNull(createScrollPane());
                    scroll.setView(cmp);
                    result.add(scroll);
                } else {
                    result.add(cmp);
                }
            }
        }
    }

    return result;
}

From source file:com.roadmap.common.util.ObjectUtil.java

/**
 * Set the value of the specified property of the specified bean, 
 * no matter which property reference format is used, with no type conversions.
 *
 * @param Object object whose property is to be modified
 * @param String possibly indexed and/or nested name of the property to be modified
 * @param Object value to which this property is to be set 
 *///from   w ww  . ja  v a 2s.c o m
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public static void setPropertyValue(Object vo, String prop, Object value) {
    try {
        if (vo instanceof Map) {
            ((Map) vo).put(prop, value);
        } else {
            PropertyUtils.setProperty(vo, prop, value);
        }
    } catch (IllegalArgumentException iae) {
        try {
            Class cl = PropertyUtils.getPropertyType(vo, prop);
            String clName = cl.getName();
            if (LONG.equalsIgnoreCase(clName)) {
                PropertyUtils.setProperty(vo, prop, Long.valueOf(RoadmapConstants.EMPTY_STRING + value));
            } else if (INT.equalsIgnoreCase(clName) || INTEGER.equalsIgnoreCase(clName)) {
                PropertyUtils.setProperty(vo, prop, Integer.valueOf(RoadmapConstants.EMPTY_STRING + value));
            } else if (BOOLEAN.equalsIgnoreCase(clName)) {
                PropertyUtils.setProperty(vo, prop, Boolean.valueOf(RoadmapConstants.EMPTY_STRING + value));
            } else if (value != null && !value.getClass().getName().equals(clName)) {
                Constructor ctr = cl.getConstructor(value.getClass());
                if (ctr != null) {
                    PropertyUtils.setProperty(vo, prop, ctr.newInstance(value));
                }
            } else {
                PropertyUtils.setProperty(vo, prop, value);
            }
        } catch (Exception e1) {
            // Supress errors
            // LoggingUtil.logError(logger,
            // "PayrollObjectUtility.setPropertyValue for object:"
            // + vo.getClass() + "|property:" + prop
            // + "|value:" + value, e1);
        }
    } catch (Exception e1) {
        // Supress errors
        // LoggingUtil.logError(logger,
        // "PayrollObjectUtility.setPropertyValue for object:"
        // + vo.getClass() + "|property:" + prop + "|value:"
        // + value, e1);
    }

}

From source file:com.fengduo.bee.commons.util.StringFormatter.java

public static Object objectFieldBr(Object ob) {
    Field[] fields = BeanUtils.getAllFields(null, ob.getClass());
    for (Field field : fields) {
        if (field == null || field.getName() == null || field.getType() == null) {
            continue;
        }/*from  www .j  a  va 2 s  .  com*/
        if (StringUtils.equals("serialVersionUID", field.getName())) {
            continue;
        }
        if (!StringUtils.equals(field.getType().getSimpleName(), "String")) {
            continue;
        }
        try {
            Object fieldVal = PropertyUtils.getProperty(ob, field.getName());
            if (null == fieldVal) {
                continue;
            }
            field.setAccessible(true);
            String value = (String) fieldVal;
            PropertyUtils.setProperty(ob, field.getName(), value.replaceAll("\r\n", "<br/>"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return ob;
}

From source file:cn.fql.utility.ClassUtility.java

/**
 * Import specified and property name to a specified object
 *
 * @param obj          object instance/*from   w w  w. j a  v  a  2s . c  o m*/
 * @param propertyName name of property
 * @param value        property value
 */
public static void setValue(Object obj, String propertyName, Object value) {
    try {
        String _pName = StringUtility.recoverIllegalPropertyName(propertyName);
        PropertyUtils.setProperty(obj, _pName, value);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.feilong.commons.core.bean.PropertyUtil.java

/**
 *  {@link PropertyUtils#setProperty(Object, String, Object)} ?(<b>??</b>).
 * /*ww  w . j  a  va  2 s . com*/
 * <pre>
 * 
 * BeanUtils.setProperty(pt1, &quot;x&quot;, &quot;9&quot;); // 9String
 * PropertyUtils.setProperty(pt1, &quot;x&quot;, 9); // int
 * // BeanUtilsPropertyUtils,?int??
 * </pre>
 * 
 * 
 * <pre>
 * {@code
 * getPropertysetProperty,?2?JavaBean????.
 * Company c = new Company();
 * c.setName("Simple");
 * 
 * Simple?????
 * //Simple
 * log.debug(BeanUtils.getProperty(c, "name"));
 * 
 * Map???key??
 * //Map
 *     log.debug(BeanUtils.getProperty(c, "address (A2)"));
 *     HashMap am = new HashMap();
 *     am.put("1","234-222-1222211");
 *     am.put("2","021-086-1232323");
 *     BeanUtils.setProperty(c,"telephone",am);
 * log.debug(BeanUtils.getProperty(c, "telephone (2)"));
 * 
 * Indexed??[]??ArrayList???.
 * //index
 *     log.debug(BeanUtils.getProperty(c, "otherInfo[2]"));
 *     BeanUtils.setProperty(c, "product[1]", "NOTES SERVER");
 *     log.debug(BeanUtils.getProperty(c, "product[1]"));
 * 
 * 3????
 * //nest
 *     log.debug(BeanUtils.getProperty(c, "employee[1].name"));
 * 
 * }
 * </pre>
 * 
 * @param bean
 *            Bean whose property is to be modified
 * @param name
 *            Possibly indexed and/or nested name of the property to be modified
 * @param value
 *            Value to which this property is to be set
 * @throws BeanUtilException
 *             if IllegalAccessException | InvocationTargetException | NoSuchMethodException
 * @see org.apache.commons.beanutils.BeanUtils#setProperty(Object, String, Object)
 * @see org.apache.commons.beanutils.PropertyUtils#setProperty(Object, String, Object)
 * @see com.feilong.commons.core.bean.BeanUtil#setProperty(Object, String, Object)
 */
public static void setProperty(Object bean, String name, Object value) throws BeanUtilException {
    try {
        //Set the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

        // PropertyUtilsBeanUtils,?????
        PropertyUtils.setProperty(bean, name, value);
    } catch (Exception e) {
        log.error(e.getClass().getName(), e);
        throw new BeanUtilException(e);
    }
}

From source file:com.feilong.commons.core.bean.BeanUtilTest.java

/**
 * Demo normal java beans./* www  . j  a  va  2s  .  c  o m*/
 *
 * @throws Exception
 *             the exception
 */
@Test
public void testDemoNormalJavaBeans() throws Exception {

    log.debug(StringUtils.center(" demoNormalJavaBeans ", 40, "="));

    // data setup  
    Address addr1 = new Address("CA1234", "xxx", "Los Angeles", "USA");
    Address addr2 = new Address("100000", "xxx", "Beijing", "China");
    Address[] addrs = new Address[2];
    addrs[0] = addr1;
    addrs[1] = addr2;
    Customer cust = new Customer(123, "John Smith", addrs);

    // accessing the city of first address  
    String cityPattern = "addresses[0].city";
    String name = (String) PropertyUtils.getSimpleProperty(cust, "name");
    String city = (String) PropertyUtils.getProperty(cust, cityPattern);
    Object[] rawOutput1 = new Object[] { "The city of customer ", name, "'s first address is ", city, "." };
    log.debug(StringUtils.join(rawOutput1));

    // setting the zipcode of customer's second address  
    String zipPattern = "addresses[1].zipCode";
    if (PropertyUtils.isWriteable(cust, zipPattern)) {//PropertyUtils  
        log.debug("Setting zipcode ...");
        PropertyUtils.setProperty(cust, zipPattern, "200000");//PropertyUtils  
    }
    String zip = (String) PropertyUtils.getProperty(cust, zipPattern);//PropertyUtils  
    Object[] rawOutput2 = new Object[] { "The zipcode of customer ", name, "'s second address is now ", zip,
            "." };
    log.debug(StringUtils.join(rawOutput2));
}

From source file:com.esofthead.mycollab.module.crm.ui.components.RelatedEditItemField.java

public RelatedEditItemField(String[] types, Object bean) {
    this.bean = bean;

    relatedItemComboBox = new RelatedItemComboBox(types);
    itemField = new TextField();
    itemField.setEnabled(true);//from   www .  j  av a  2s. co  m

    browseBtn = new Button(null, FontAwesome.ELLIPSIS_H);
    browseBtn.addStyleName(UIConstants.THEME_GRAY_LINK);
    browseBtn.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            String type = (String) relatedItemComboBox.getValue();
            if ("Account".equals(type)) {
                AccountSelectionWindow accountWindow = new AccountSelectionWindow(RelatedEditItemField.this);
                UI.getCurrent().addWindow(accountWindow);
                accountWindow.show();
            } else if ("Campaign".equals(type)) {
                CampaignSelectionWindow campaignWindow = new CampaignSelectionWindow(RelatedEditItemField.this);
                UI.getCurrent().addWindow(campaignWindow);
                campaignWindow.show();
            } else if ("Contact".equals(type)) {
                ContactSelectionWindow contactWindow = new ContactSelectionWindow(RelatedEditItemField.this);
                UI.getCurrent().addWindow(contactWindow);
                contactWindow.show();
            } else if ("Lead".equals(type)) {
                LeadSelectionWindow leadWindow = new LeadSelectionWindow(RelatedEditItemField.this);
                UI.getCurrent().addWindow(leadWindow);
                leadWindow.show();
            } else if ("Opportunity".equals(type)) {
                OpportunitySelectionWindow opportunityWindow = new OpportunitySelectionWindow(
                        RelatedEditItemField.this);
                UI.getCurrent().addWindow(opportunityWindow);
                opportunityWindow.show();
            } else if ("Case".equals(type)) {
                CaseSelectionWindow caseWindow = new CaseSelectionWindow(RelatedEditItemField.this);
                UI.getCurrent().addWindow(caseWindow);
                caseWindow.show();
            } else {
                relatedItemComboBox.focus();
            }
        }
    });

    clearBtn = new Button(null, FontAwesome.TRASH_O);
    clearBtn.addStyleName(UIConstants.THEME_GRAY_LINK);
    clearBtn.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            try {
                PropertyUtils.setProperty(RelatedEditItemField.this.bean, "typeid", null);
            } catch (Exception e) {
                LOG.error("Error while saving type", e);
            }
        }
    });
}

From source file:it.sample.parser.util.CommonsUtil.java

/**
 * Metodo di utilita' che copia i campi non nulli della classe sorgente in quelli della classe di destinazione
 * //w  w  w. j a  va  2  s  .  c  om
 * @param source
 * @param destination
 */
public static <K, T> void copyNotNullProperties(K source, T destination) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(source);
    if (descriptors != null) {
        for (PropertyDescriptor descriptor : descriptors) {
            try {
                String propertyName = descriptor.getName();
                Field field = getDeclaredField(propertyName, source.getClass());

                if (field != null && field.getAnnotation(IgnoreField.class) == null) {
                    boolean wasAccessible = field.isAccessible();
                    field.setAccessible(true);

                    if (PropertyUtils.getReadMethod(descriptor) != null) {
                        Object val = PropertyUtils.getSimpleProperty(source, propertyName);
                        if (val != null && descriptor.getWriteMethod() != null) {
                            PropertyUtils.setProperty(destination, propertyName, val);
                        }
                    }
                    field.setAccessible(wasAccessible);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.lioland.harmony.services.dao.ODBClass.java

private void fillObject(ODocument doc, Object ob) throws NoSuchMethodException, ClassNotFoundException,
        IllegalAccessException, InvocationTargetException {
    for (String fieldName : doc.fieldNames()) {
        Object fieldValue = doc.field(fieldName);
        if (fieldValue instanceof ODocument) {
            fieldValue = transform((ODocument) fieldValue,
                    Class.forName(PACKAGE_PREFIX + ((ODocument) fieldValue).getClassName()));
        }/*from   w  w w .j  av a 2 s.  co  m*/
        if (fieldValue != null) {
            PropertyUtils.setProperty(ob, fieldName, fieldValue);
        }
    }
}

From source file:de.topicmapslab.kuria.runtime.PropertyBinding.java

/**
 * /*from  w  w  w .  j a  v a  2  s .c  o m*/
 *  {@inheritDoc}
 */
public void setValue(Object instance, Object value) throws IllegalAccessException, InvocationTargetException,
        NoSuchMethodException, IllegalArgumentException {
    PropertyUtils.setProperty(instance, fieldName, value);
}