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

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

Introduction

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

Prototype

public static void copyProperties(Object dest, Object orig)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Copy property values from the "origin" bean to the "destination" bean for all cases where the property names are the same (even though the actual getter and setter methods might have been customized via BeanInfo classes).

For more details see PropertyUtilsBean.

Usage

From source file:com.npower.dm.setup.task.ModelFamilyManager.java

/**
 * Merge family informations into ModelItem
 * @param item//from  w ww. j  a  v  a 2 s.c  o m
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
public void merge(ModelItem item)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    ModelFamilyItem familyItem = this.findModelFamily(item);
    List<ModelFamilyItem> familyItems = new ArrayList<ModelFamilyItem>();
    while (familyItem != null) {
        familyItems.add(0, familyItem);
        familyItem = this.findModelFamily(familyItem.getParentID());
    }
    familyItem = new ModelFamilyItem();
    for (ModelFamilyItem family : familyItems) {
        PropertyUtils.copyProperties(familyItem, family);
    }
    this.copy(familyItem, item);
}

From source file:gov.nih.nci.system.webservice.WSQuery.java

private Object copyValueToImpl(Object obj) {
    Class objKlass;//  w  w  w  .jav  a 2  s . c  o m
    Object newObject;
    try {
        objKlass = obj.getClass();
        log.debug("WSQuery.copyValue: objKlass.getName = " + objKlass.getName());
        String objFullName = objKlass.getName();
        String newObjectName = objFullName.replaceAll(".ws.", ".");
        if (newObjectName.endsWith("Impl")) {
            newObjectName = newObjectName.substring(0, newObjectName.length() - 4);
        }
        Class newObjClass = Class.forName(newObjectName);
        newObject = newObjClass.newInstance();

        log.debug("copying properties from ws object to impl object......");
        PropertyUtils.copyProperties(newObject, obj);
    } catch (Exception e) {
        log.error("WS Error" + e.getMessage());
        //System.out.println("WS Error"+ e);
        return null;
    }
    return newObject;
}

From source file:clearUp.Collections3.java

/**
  * mapbean//  www. j  ava  2  s  .  co  m
  *
  * @param map
  * @param beanClass
  * @return
  */
public static Object map2Bean(Map map, Class<?> beanClass) {
    try {
        Object bean = beanClass.newInstance();
        PropertyUtils.copyProperties(bean, map);
        return bean;
    } catch (Exception e) {
        throw new RuntimeException(beanClass.getCanonicalName() + "!");
    }
}

From source file:br.gov.jfrj.siga.dp.dao.CpDaoTest.java

public void testGravarGrupoEAtualizar() throws AplicacaoException, Exception, IllegalAccessException {

    CpTipoGrupo tpGrp = dao.consultar(CpTipoGrupo.TIPO_GRUPO_GRUPO_DE_DISTRIBUICAO, CpTipoGrupo.class, false);
    dao.iniciarTransacao();//  www. j a  v a2s  . c o m

    CpGrupo grpNovo = new CpGrupoDeEmail();
    grpNovo.setCpTipoGrupo(tpGrp);
    grpNovo.setOrgaoUsuario(dao.consultar(1L, CpOrgaoUsuario.class, false));
    grpNovo.setCpGrupoPai(null);
    grpNovo.setDscGrupo("Teste");
    grpNovo.setSiglaGrupo("TESTE");
    grpNovo = (CpGrupo) dao.gravarComHistorico(grpNovo, null, null, null);
    Long idCpGrupo = grpNovo.getIdGrupo();

    // dao.commitTransacao();

    CpGrupo grp = grpNovo;
    grpNovo = grp.getClass().newInstance();
    PropertyUtils.copyProperties(grpNovo, grp);
    grpNovo.setIdGrupo(null);
    grpNovo.setCpGrupoPai(null);
    grpNovo.setDscGrupo("Teste");
    grpNovo.setSiglaGrupo("TESTE");

    // dao.iniciarTransacao();
    grp = (CpGrupo) dao.gravarComHistorico(grpNovo, grp, null, null);

}

From source file:com.gohuinuo.common.utils.Collections3.java

/**
  * map?bean/*from   www . j a v  a  2s . c  o m*/
  *
  * @param map
  * @param beanClass
  * @return
  */
public static Object map2Bean(Map map, Class<?> beanClass) {
    try {
        Object bean = beanClass.newInstance();
        PropertyUtils.copyProperties(bean, map);
        return bean;
    } catch (Exception e) {
        throw new RuntimeException(beanClass.getCanonicalName() + "!");
    }
}

From source file:com.glweb.module.forum.ForumManager.java

public boolean updateMessage(Message newMessage) {
    Message _message = null;/*from  w  w  w  . j av  a  2s  .c o m*/

    try {
        _message = getMessage(newMessage.getId());

        PropertyUtils.copyProperties(_message, newMessage);

        _message.setModifiedDate(new Date());

        getMessageDAO().updateMessage(_message);
    } catch (GLWebPersistenceException e) {
        getLogger().error(e);
        return false;
    } catch (Exception e) {
        getLogger().error(e);
        return false;
    }

    return true;
}

From source file:com.sunchenbin.store.feilong.core.bean.PropertyUtil.java

/**
 * ? {@code fromObj-->toObj}./*from ww w.  ja  v a  2s.  c o  m*/
 * 
 * <p>
 * ?:?copy?,??2Bean???ref, ??, .
 * </p>
 * 
 * <h3>?:</h3>
 * 
 * <blockquote>
 * 
 * <ol>
 * <li>includePropertyNames,? <code>fromObj</code>??,</li>
 * <li>includePropertyNames,? <code>fromObj</code>, <code>toObj</code>??,??,see
 * {@link org.apache.commons.beanutils.BeanUtilsBean#copyProperty(Object, String, Object)} Line391</li>
 * <li>Date,??converter</li>
 * </ol>
 * </blockquote>
 * 
 * 
 * <h3>:</h3>
 * 
 * <blockquote>
 * 
 * <code>
 * <pre>
User oldUser = new User();
oldUser.setId(5L);
oldUser.setMoney(new BigDecimal(500000));
oldUser.setDate(new Date());
String[] nickName = { "feilong", "", "venusdrogon" };
oldUser.setNickName(nickName);
        
User newUser = new User();
        
String[] strs = { "date", "money", "nickName" };
PropertyUtil.copyProperties(newUser, oldUser, strs);
LOGGER.info(JsonUtil.format(newUser));s(enterpriseSales,enterpriseSales_form,new String[]{&quot;enterpriseName&quot;,&quot;linkMan&quot;,&quot;phone&quot;});
 *
 * 
 *  :
 * 
 * {
"userAddresseList": [],
"userAddresses": [],
"date": "2015-09-06 13:27:43",
"password": "",
"id": 0,
"nickName":         [
    "feilong",
    "",
    "venusdrogon"
],
"age": 0,
"name": "feilong",
"money": 500000,
"attrMap": null,
"userInfo": {"age": 0},
"loves": []
}
 * 
 * </pre>
 * </code>
 * 
 * </blockquote>
 * 
 * 
 * <h3>{@link BeanUtils#copyProperties(Object, Object)} {@link PropertyUtils#copyProperties(Object, Object)}</h3>
 * 
 * <blockquote>
 * <ul>
 * <li>{@link BeanUtils#copyProperties(Object, Object)}??????,????</li>
 * <li>{@link PropertyUtils#copyProperties(Object, Object)} ???,??JavaBean?????,???,???,.</li>
 * <li>commons-beanutils v1.9.0? BeanUtils?? null,PropertyUtils?? null.<br>
 * (<b>:</b>commons-beanutils v1.9.0+?,BeanUtilsBean.copyProperties() no longer throws a ConversionException for null properties
 * of certain data types),?,??commons-beanutils
 * {@link <a href="http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/RELEASE-NOTES.txt">RELEASE-NOTES.txt</a>}</li>
 * </ul>
 * </blockquote>
 *
 * @param toObj
 *            
 * @param fromObj
 *            
 * @param includePropertyNames
 *            ???,(can be nested/indexed/mapped/combo)<br>
 *             null or empty , {@link PropertyUtils#copyProperties(Object, Object)}
 * @see #setProperty(Object, String, Object)
 * 
 * @see com.sunchenbin.store.feilong.core.bean.BeanUtil#copyProperties(Object, Object, String...)
 * 
 * @see org.apache.commons.beanutils.PropertyUtilsBean#copyProperties(Object, Object)
 * @see <a href="http://www.cnblogs.com/kaka/archive/2013/03/06/2945514.html">Bean??(Apache BeanUtils?PropertyUtils,Spring
 *      BeanUtils,Cglib BeanCopier)</a>
 * @since 1.4.1
 */
public static void copyProperties(Object toObj, Object fromObj, String... includePropertyNames) {
    if (null == toObj) {
        throw new NullPointerException("No destination bean/toObj specified");
    }
    if (null == fromObj) {
        throw new NullPointerException("No origin bean/fromObj specified");
    }

    if (Validator.isNullOrEmpty(includePropertyNames)) {
        try {
            PropertyUtils.copyProperties(toObj, fromObj);
            return;
        } catch (Exception e) {
            LOGGER.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }
    for (String propertyName : includePropertyNames) {
        Object value = getProperty(fromObj, propertyName);
        setProperty(toObj, propertyName, value);
    }
}

From source file:com.jdon.model.ModelHandler.java

/**
 * Model object's data transfer to ModelForm object
 * /*from  w ww  . ja v  a 2  s .c o m*/
 * default implemention is copy mapping between with them; another
 * implemention is : PropertyUtils.setProperty extends this class , and
 * override this method
 * 
 * @param model
 * @param form
 * @throws java.lang.Exception
 */
public void modelIFCopyToForm(Object model, ModelForm form) throws Exception {
    if (model == null || form == null)
        return;
    if (model instanceof Model) { // for below 1.4 version
        modelCopyToForm((Model) model, form);
        return;
    }
    try {
        PropertyUtils.copyProperties(form, model);
    } catch (Exception e) {
        String error = "error happend:" + e + " in copy Model:" + model.getClass().getName() + " To ModelForm:"
                + form.getClass().getName()
                + " there maybe are exceptions in setter/getter method of your ModelForm or Model, add try..catch in them. ";
        Debug.logError(error, module);
        throw new Exception(error);
    }
}

From source file:com.floreantpos.bo.ui.explorer.QuickMaintenanceExplorer.java

private static void quickMaintainMenuGroup(MenuGroup menuGroup) {
    try {//from  w w  w. ja va2s.c  om
        if (menuGroup.getId() != null) {
            if (btnCopy.isSelected()) {
                MenuGroup newMenuGroup = new MenuGroup();
                PropertyUtils.copyProperties(newMenuGroup, menuGroup);
                newMenuGroup.setId(null);
                menuGroup = newMenuGroup;
            } else if (btnDelete.isSelected()) {
                if (POSMessageDialog.showYesNoQuestionDialog(POSUtil.getFocusedWindow(),
                        POSConstants.CONFIRM_DELETE, POSConstants.DELETE) != JOptionPane.YES_OPTION) {
                    return;
                }
                MenuItemDAO menuItemDao = new MenuItemDAO();
                List<MenuItem> menuItems = menuItemDao.findByParent(null, menuGroup, true);

                if (menuItems.size() > 0) {
                    if (POSMessageDialog.showYesNoQuestionDialog(POSUtil.getFocusedWindow(),
                            Messages.getString("MenuGroupExplorer.0"), //$NON-NLS-1$
                            POSConstants.DELETE) != JOptionPane.YES_OPTION) {
                        return;
                    }
                    menuItemDao.releaseParent(menuItems);
                }
                MenuGroupDAO foodGroupDAO = new MenuGroupDAO();
                foodGroupDAO.delete(menuGroup);
                OrderView.getInstance().getGroupView().updateView(menuGroup);
                return;
            }
        }
        MenuGroupForm editor = new MenuGroupForm(menuGroup);
        BeanEditorDialog dialog = new BeanEditorDialog(Application.getPosWindow(), editor);
        dialog.open();
        if (dialog.isCanceled())
            return;
        OrderView.getInstance().getGroupView().updateView(menuGroup);
        return;
    } catch (Exception e) {
        return;
    }
}

From source file:br.gov.jfrj.siga.dp.dao.CpDaoTest.java

public void testAtualizarGrupoSemAlteracao() throws AplicacaoException, Exception, IllegalAccessException {

    dao.iniciarTransacao();/*  ww w. j a  va  2 s .c o  m*/

    CpGrupo grpIni = dao.listarGruposDeEmail().get(0);

    CpGrupo grp = (CpGrupo) Objeto.getImplementation(dao.consultar(grpIni.getId(), CpGrupo.class, false));
    CpGrupo grpNovo = ((CpGrupo) Objeto.getImplementation(grp)).getClass().newInstance();
    PropertyUtils.copyProperties(grpNovo, grp);
    grpNovo.setIdGrupo(null);
    CpGrupo grpRecebido = (CpGrupo) dao.gravarComHistorico(grpNovo, grp, null, null);

    assertEquals(grpRecebido, grp);
}