Java Code Examples for org.apache.commons.beanutils.BeanUtils.copyProperties()

The following are Jave code examples for showing how to use copyProperties() of the org.apache.commons.beanutils.BeanUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: OMIPlatform   File: TzUserDetailsService.java   View Source Code Vote up 6 votes
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

    User user = this.userService.findByName(name);
    TzUserDetails userDetails = new TzUserDetails();

    if(user == null){
        throw new UsernameNotFoundException("用户不存在");
    }

    try {
        BeanUtils.copyProperties(userDetails,user);
    } catch (Exception e) {
        e.printStackTrace();
    }

    logger.info("---->身份验证:"+userDetails.getUsername()+":"+userDetails.getPassword());

   return userDetails;
}
 
Example 2
Project: OMIPlatform   File: ShopProductDto.java   View Source Code Vote up 6 votes
public static List<ShopProductDto> convert(List<ShopProduct> products,ObjectMapper objectMapper) throws InvocationTargetException, IllegalAccessException {
    if (products == null) {
        return null;
    }
    List<ShopProductDto> productDtos = new ArrayList();
    for (int i = 0; i < products.size(); i++) {
        ShopProductDto tmp = new ShopProductDto();
        BeanUtils.copyProperties(tmp, products.get(i));
        try {
            /*处理图片信息转换*/
           tmp.setImgs(tmp.parseImageList(objectMapper)) ;
            /*处理基础信息转换*/
            tmp.parseBaseProperty(objectMapper);
            /*其他转换操作*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        productDtos.add(tmp);
    }
    return productDtos;
}
 
Example 3
Project: JRediClients   File: EntityProxyFactory.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
public <T extends IEntity> T createProxyEntity(T entity) throws Exception {
	EntityProxy entityProxy = createProxy(entity);
	if (entityProxy != null) {
		EntityProxyWrapper entityProxyWrapper = new EntityProxyWrapper(entityProxy);			
		AbstractEntity proxyEntity = createProxyEntity(entityProxy);
		if(proxyEntity!=null) {
			// 注入对象 数值
			BeanUtils.copyProperties(proxyEntity, entity);
			entityProxy.setCollectFlag(true);
			if(entityProxyWrapper != null) {
				proxyEntity.setEntityProxyWrapper(entityProxyWrapper);
				return (T) proxyEntity;
			}
		}
	}
	return null;
}
 
Example 4
Project: lams   File: LtiConsumerManagementAction.java   View Source Code Vote up 6 votes
/**
    * Edits specified LTI tool consumer
    */
   public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

initServices();

DynaActionForm ltiConsumerForm = (DynaActionForm) form;
Integer sid = WebUtil.readIntParam(request, "sid", true);

// editing a tool consumer
if (sid != null) {
    ExtServer ltiConsumer = integrationService.getExtServer(sid);
    BeanUtils.copyProperties(ltiConsumerForm, ltiConsumer);
    String lessonFinishUrl = ltiConsumer.getLessonFinishUrl() == null ? "-" : ltiConsumer.getLessonFinishUrl();
    request.setAttribute("lessonFinishUrl", lessonFinishUrl);

// create a tool consumer
} else { 
    //do nothing
}

return mapping.findForward("ltiConsumer");	
   }
 
Example 5
Project: bdf2   File: DbService.java   View Source Code Vote up 6 votes
/**
 * 插入表新列
 * 
 * @param dbInfoId
 * @param columnInfo
 * @throws Exception
 */
public void insertColumn(String dbInfoId, ColumnInfo columnInfo) throws Exception {
	com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo dbColumnInfo = new com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo();
	BeanUtils.copyProperties(dbColumnInfo, columnInfo);
	String tableName = columnInfo.getTableName();
	String columnName = columnInfo.getColumnName();
	boolean isprimaryKey = columnInfo.isIsprimaryKey();
	List<String> primaryKeys = findTablePrimaryKeys(dbInfoId, tableName);
	if (isprimaryKey) {
		primaryKeys.add(columnName);
		dbColumnInfo.setListPrimaryKey(primaryKeys);
		String pkName = this.findSqlServerPKIndex(dbInfoId, tableName);
		log.debug("pkName:" + pkName);
		if (StringUtils.hasText(pkName)) {
			dbColumnInfo.setPkName(pkName);
		}
	}
	IDialect dBDialect = getDBDialectByDbInfoId(dbInfoId);
	String sql = dBDialect.getNewColumnSql(dbColumnInfo);
	String[] sqls = sql.split(";");
	this.updateSql(dbInfoId, sqls);

}
 
Example 6
Project: demo   File: ConverterApp.java   View Source Code Vote up 6 votes
private static void entity2Dto() {
	EUser u = new EUser();
	u.setId(1l);
	u.setUsername("yoking");
	u.setCreationDate(new Date(System.currentTimeMillis()));
	
	UserDTO user = new UserDTO();
	
	ConvertUtils.register(new DateStringConverter(), String.class);
	try {
		BeanUtils.copyProperties(user, u);
	} catch (IllegalAccessException | InvocationTargetException e) {
		e.printStackTrace();
	}
	
	System.out.println(user);
}
 
Example 7
Project: demo   File: ConverterApp.java   View Source Code Vote up 6 votes
private static void dto2Entity() {
	UserDTO user = new UserDTO();
	user.setId(1l);
	user.setUsername("joking");
	user.setCreationDate("2016-04-20");
	
	EUser u = new EUser();
	ConvertUtils.register(new DateStringConverter(), Date.class);
	try {
		BeanUtils.copyProperties(u, user);
	} catch (IllegalAccessException | InvocationTargetException e) {
		e.printStackTrace();
	}
	
	System.out.println(u);
}
 
Example 8
Project: elastic-jobx   File: JobExecutionMultipleShardingContext.java   View Source Code Vote up 6 votes
/**
     * 根据分片项获取单分片作业运行时上下文.
     * 
     * @param item 分片项
     * @return 单分片作业运行时上下文
     */
    public JobExecutionSingleShardingContext createJobExecutionSingleShardingContext(final int item) {
        JobExecutionSingleShardingContext result = new JobExecutionSingleShardingContext();
        try {
            BeanUtils.copyProperties(result, this);
//        } catch (final IllegalAccessException | InvocationTargetException ex) {
//            throw new JobException(ex);
//        }
        } catch (final IllegalAccessException ex1) {
            throw new JobException(ex1);
        } catch (final InvocationTargetException ex2) {
            throw new JobException(ex2);
        }
        result.setShardingItem(item);
        result.setShardingItemParameter(shardingItemParameters.get(item));
        result.setOffset(offsets.get(item));
        return result;
    }
 
Example 9
Project: sistra   File: TramitePersistenteFacadeEJB.java   View Source Code Vote up 6 votes
/**
  * @ejb.interface-method
  * @ejb.permission role-name="${role.auto}"
  * @ejb.permission role-name="${role.todos}"
  * @param tramitePersistente
  * @return
  */
 public void backupTramitePersistente( TramitePersistente tramitePersistente )
 {
 	try
 	{
     	TramitePersistenteBackup result = new TramitePersistenteBackup();
  	BeanUtils.copyProperties( result, tramitePersistente );
Set setDocumentos = tramitePersistente.getDocumentos(); 
for ( Iterator it = setDocumentos.iterator(); it.hasNext(); )
{
	DocumentoPersistente documento = ( DocumentoPersistente ) it.next();
   	DocumentoPersistenteBackup backup = new DocumentoPersistenteBackup();
   	BeanUtils.copyProperties( backup, documento );
   	result.addDocumentoBackup( backup );
}
grabarBackupTramitePersistente ( result );
 	}
 	catch( Exception exc )
 	{
 		throw new EJBException( exc );
 	}
 }
 
Example 10
Project: sistra   File: NotificacionTelematicaFacadeEJB.java   View Source Code Vote up 6 votes
/**
    * Devuelve notificacion con informacion exclusiva de aviso
    * @param notificacionTelematica
    * @return
    */
   private NotificacionTelematica notificacionSinAbrir(NotificacionTelematica notificacionTelematica) throws Exception {
	
   	NotificacionTelematica not = new NotificacionTelematica();
   	BeanUtils.copyProperties(not,notificacionTelematica);

   	// Eliminamos referencia rds a oficio
   	not.setCodigoRdsOficio(0);
   	not.setClaveRdsOficio(null);
   	
   	// Eliminamos documentos
   	not.getDocumentos().clear();
   	
   	// Eliminamos tramite de subsanacion
   	not.setTramiteSubsanacionDescripcion(null);
   	not.setTramiteSubsanacionIdentificador(null);
   	not.setTramiteSubsanacionVersion(null);
   	not.setTramiteSubsanacionParametros(null);
   	
	return not;
}
 
Example 11
Project: dhis2-core   File: KeyJsonValueController.java   View Source Code Vote up 6 votes
/**
 * Retrieves the KeyJsonValue represented by the given key from the given namespace.
 */
@RequestMapping( value = "/{namespace}/{key}/metaData", method = RequestMethod.GET, produces = "application/json" )
public @ResponseBody KeyJsonValue getKeyJsonValueMetaData(
    @PathVariable String namespace, @PathVariable String key, HttpServletResponse response )
    throws Exception
{
    if ( !hasAccess( namespace ) )
    {
        throw new WebMessageException( WebMessageUtils.forbidden( "The namespace '" + namespace +
            "' is protected, and you don't have the right authority to access it." ) );
    }

    KeyJsonValue keyJsonValue = keyJsonValueService.getKeyJsonValue( namespace, key );

    if ( keyJsonValue == null )
    {
        throw new WebMessageException( WebMessageUtils
            .notFound( "The key '" + key + "' was not found in the namespace '" + namespace + "'." ) );
    }

    KeyJsonValue metaDataValue = new KeyJsonValue();
    BeanUtils.copyProperties( metaDataValue, keyJsonValue );
    metaDataValue.setValue( null );

    return metaDataValue;
}
 
Example 12
Project: dtsopensource   File: DTSAdmin.java   View Source Code Vote up 6 votes
/**
 * @param activityRuleVO
 * @return
 */
@ResponseBody
@RequestMapping(value = "/queryActivity", method = RequestMethod.POST)
public Map<String, Object> queryActivity(ActivityRuleVO activityRuleVO) {
    Map<String, Object> result = Maps.newHashMap();
    result.put("result", DTSResultCode.SUCCESS);
    try {
        ActivityRuleEntity activityRuleEntity = new ActivityRuleEntity();
        BeanUtils.copyProperties(activityRuleEntity, activityRuleVO);
        List<ActivityRuleEntity> list = acticityRuleApplication.queryActivityRule(activityRuleEntity);
        result.put("list", list);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        result.put("result", DTSResultCode.FAIL);
        result.put("message", e.getMessage());
    }
    return result;
}
 
Example 13
Project: OMIPlatform   File: ShopProductController.java   View Source Code Vote up 5 votes
@PostMapping("addProduct")
@Transactional(propagation = Propagation.REQUIRED)
public String insertProduct(@RequestBody EditShopProductDto productDto) throws JsonProcessingException, InvocationTargetException, IllegalAccessException {
    /*将商品基础详情转换为json串*/
    String baseProperty = "";
    baseProperty = objectMapper.writeValueAsString(productDto.getBaseProperty());
    productDto.setProBaseProperty(baseProperty);

    /*设置销量*/
    productDto.setProSalveNumber(0);
    /*设置商品为下架*/
    productDto.setProSalve(0);
    /*将图片转为字符串*/
    String proImgs = objectMapper.writeValueAsString(productDto.getImgs());
    productDto.setProImage(proImgs);
    /*存储商品*/
    this.productService.insert(productDto);

    List<ShopProductVersion> spvs = new ArrayList<>();
    for (EditShopProductVersionDto vers : productDto.getProVersion()) {
        ShopProductVersion spv = new ShopProductVersion();
        /*将商品系列中的两个详情转换为json串*/
        String dp = objectMapper.writeValueAsString(vers.getDetailProperty());
        vers.setProDetailProperty(dp);
        vers.setProId(productDto.getProId());
        /*将Dto映射到pojo*/
        BeanUtils.copyProperties(spv, vers);
        spvs.add(spv);
    }
    System.out.println(productDto.getProId());

    /*批量添加到商品系列表中*/
    this.shopProductVersionService.insertList(spvs);

    return "{\"status\":true}";
}
 
Example 14
Project: OMIPlatform   File: ShopProductController.java   View Source Code Vote up 5 votes
@GetMapping("findEditProduct/{proid}")
public EditShopProductDto findEditProduct(@PathVariable Integer proid) throws InvocationTargetException, IllegalAccessException, IOException {
    EditShopProductDto result = new EditShopProductDto();
    ShopProduct product = this.productService.findByProId(proid);
    /*映射到dto对象*/
    BeanUtils.copyProperties(result, product);
    /*转换为图片信息*/
    JavaType type2 = objectMapper.getTypeFactory().constructParametricType(List.class, FileDto.class);
    List<FileDto> list2 = (ArrayList) objectMapper.readValue(product.getProImage(), type2);
    result.setImgs(list2);

    /*设置基础属性*/
    JavaType type1 = objectMapper.getTypeFactory().constructParametricType(List.class, PropertyPairDto.class);
    List<PropertyPairDto> list1 = (ArrayList) objectMapper.readValue(product.getProBaseProperty(), type1);
    result.setBaseProperty(list1);
    List<ShopProductVersion> versions = product.getMutiProduct();
    /*设置产品系列信息*/
    if (versions != null) {
        List<EditShopProductVersionDto> editVers = new ArrayList<>();
        for (ShopProductVersion ver : versions) {
            EditShopProductVersionDto editVersion = new EditShopProductVersionDto();
            BeanUtils.copyProperties(editVersion, ver);

            /*设置产品详细属性*/
            List<PropertyPairDto> list3 = (ArrayList) objectMapper.readValue(ver.getProDetailProperty(), type1);
            editVersion.setDetailProperty(list3);
            editVers.add(editVersion);
        }
        result.setProVersion(editVers);
    }
    return result;
}
 
Example 15
Project: OMIPlatform   File: ShopProductController.java   View Source Code Vote up 5 votes
/***
    * 更改商品信息
    * @param productDto
    * @return
    */
   @PostMapping("modifyProduct")
   @Transactional(propagation = Propagation.REQUIRED)
   public String modifyProduct(@RequestBody EditShopProductDto productDto) throws JsonProcessingException, InvocationTargetException, IllegalAccessException {
/*将商品基础详情转换为json串*/
       String baseProperty = "";
       baseProperty = objectMapper.writeValueAsString(productDto.getBaseProperty());
       productDto.setProBaseProperty(baseProperty);

       /*设置销量*/
       //productDto.setProSalveNumber(0);
       /*将图片转为字符串*/
       String proImgs = objectMapper.writeValueAsString(productDto.getImgs());
       productDto.setProImage(proImgs);
       /*存储商品*/
       this.productService.update(productDto);

       for (EditShopProductVersionDto vers : productDto.getProVersion()) {
           ShopProductVersion spv = new ShopProductVersion();
           /*将商品系列中的两个详情转换为json串*/
           String dp = objectMapper.writeValueAsString(vers.getDetailProperty());
           vers.setProDetailProperty(dp);
           vers.setProId(productDto.getProId());
           /*将Dto映射到pojo*/
           BeanUtils.copyProperties(spv, vers);
           /*批量添加到商品系列表中*/
           this.shopProductVersionService.update(spv);
       }
       System.out.println(productDto.getProId());
       return "{\"status\":true}";
   }
 
Example 16
Project: zhkuas_ssm_maven   File: WebUtils.java   View Source Code Vote up 5 votes
public static void coypBean(Object src ,Object dest){
	try {
		BeanUtils.copyProperties(dest, src);
	} catch (Exception e) {
		
		throw new RuntimeException(e);
	}
}
 
Example 17
Project: atlas   File: AtlasExtensionOutput.java   View Source Code Vote up 5 votes
private void copyProps(Object dest, Object orig) {
    if (orig == null) {
        return;
    }
    try {
        BeanUtils.copyProperties(dest, orig);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: lams   File: ServerMaintainAction.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
   public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {
DynaActionForm extServerForm = (DynaActionForm) form;
Integer sid = WebUtil.readIntParam(request, "sid", true);
if (sid != null) {
    ExtServer map = AdminServiceProxy.getIntegrationService(getServlet().getServletContext())
	    .getExtServer(sid);
    BeanUtils.copyProperties(extServerForm, map);
}
return mapping.findForward("servermaintain");
   }
 
Example 19
Project: bdf2   File: DbService.java   View Source Code Vote up 5 votes
/**
 * 更新表列
 * 
 * @param dbInfoId
 * @param oldColumnInfo
 * @param newColumnInfo
 * @throws Exception
 */
public void updateColumn(String dbInfoId, ColumnInfo oldColumnInfo, ColumnInfo newColumnInfo) throws Exception {
	com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo oldDbColumnInfo = new com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo();
	BeanUtils.copyProperties(oldDbColumnInfo, oldColumnInfo);
	com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo newDbColumnInfo = new com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo();
	BeanUtils.copyProperties(newDbColumnInfo, newColumnInfo);
	String tableName = oldColumnInfo.getTableName();
	boolean oldPrimaryKey = oldColumnInfo.isIsprimaryKey();
	boolean newPrimaryKey = newColumnInfo.isIsprimaryKey();
	List<String> primaryKeys = null;
	if (oldPrimaryKey != newPrimaryKey) {
		primaryKeys = findTablePrimaryKeys(dbInfoId, tableName);
		if (newPrimaryKey && !oldPrimaryKey) {
			primaryKeys.add(newDbColumnInfo.getColumnName().toUpperCase());
		} else if (!newPrimaryKey && oldPrimaryKey) {
			primaryKeys.remove(newDbColumnInfo.getColumnName().toUpperCase());
		}
		newDbColumnInfo.setListPrimaryKey(primaryKeys);
		String pkName = this.findSqlServerPKIndex(dbInfoId, tableName);
		if (StringUtils.hasText(pkName)) {
			newDbColumnInfo.setPkName(pkName);
		}
	}
	IDialect dBDialect = getDBDialectByDbInfoId(dbInfoId);
	String sql = dBDialect.getUpdateColumnSql(oldDbColumnInfo, newDbColumnInfo);
	String[] sqls = sql.split(";");
	this.updateSql(dbInfoId, sqls);
}
 
Example 20
Project: otter-G   File: PipelineParameter.java   View Source Code Vote up 5 votes
/**
 * 合并system参数设置
 */
public void merge(SystemParameter globalParmeter) {
    try {
        BeanUtils.copyProperties(this, globalParmeter);
    } catch (Exception e) {
        // ignore
    }
}
 
Example 21
Project: otter-G   File: PipelineParameter.java   View Source Code Vote up 5 votes
/**
 * 合并channel参数设置
 */
public void merge(ChannelParameter channelParameter) {
    try {
        BeanUtils.copyProperties(this, channelParameter);
    } catch (Exception e) {
        // ignore
    }
}
 
Example 22
Project: otter-G   File: AuthenticationInfoUtils.java   View Source Code Vote up 5 votes
public static AuthenticationInfo createFrom(DatasourceInfo datasourceInfo) {
    AuthenticationInfo authenticationInfo = new AuthenticationInfo();
    try {
        BeanUtils.copyProperties(authenticationInfo, datasourceInfo);
    } catch (Exception e) {
        throw new CanalException(e);
    }
    return authenticationInfo;
}
 
Example 23
Project: FCat   File: ObjectUtil.java   View Source Code Vote up 5 votes
public static <T> T copyProperties(Object srcObj, Class<T> toClass) {
	try {
		ConvertUtils.register(new DateConverter(null), Date.class);
		T instance = toClass.newInstance();
		BeanUtils.copyProperties(instance, srcObj);
		return instance;
	} catch (Exception e) {
		throw new RuntimeException("拷贝对象属性值异常", e);
	}
}
 
Example 24
Project: sistra   File: PluginDominio.java   View Source Code Vote up 5 votes
private ValoresDominio resuelveDominioFuenteDatos(Dominio dominio,
		List parametros, String url) throws Exception {
	ValoresFuenteDatosBTE vfd = DelegateBTEUtil.getBteSistraDelegate().consultaFuenteDatos(dominio.getSql(), parametros);
	ValoresDominio vd = new ValoresDominio();
	BeanUtils.copyProperties(vd, vfd);
	return vd;		
}
 
Example 25
Project: sistra   File: EntradaPreregistroFacadeEJB.java   View Source Code Vote up 5 votes
/**
  * @ejb.interface-method
  * @ejb.permission role-name="${role.auto}"
  * @param entradaPreregistro
  */
 public void backupEntradaPreregistro( EntradaPreregistro entradaPreregistro )
 {
 	Session session = getSession();
 	try
 	{
  	EntradaPreregistroBackup entradaBackup = new EntradaPreregistroBackup();
  	BeanUtils.copyProperties( entradaBackup, entradaPreregistro );
Set setDocumentos = entradaPreregistro.getDocumentos(); 
for ( Iterator it = setDocumentos.iterator(); it.hasNext(); )
{
	DocumentoEntradaPreregistro documento = ( DocumentoEntradaPreregistro ) it.next();
	DocumentoEntradaPreregistroBackup docBackup = new DocumentoEntradaPreregistroBackup();
	BeanUtils.copyProperties( docBackup, documento );
	entradaBackup.addDocumentoBackup( docBackup );
}
session.save( entradaBackup );
 	}
 	catch( Exception exc )
 	{
 		throw new EJBException( exc );
 	}
 	finally
 	{
 		close( session );
 	}
 }
 
Example 26
Project: sistra   File: ActualizarDatosPersonalesAction.java   View Source Code Vote up 5 votes
public ActionForward execute(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception
{
	
	// TODO DE MOMENTO SOLO DEJAMOS MODIFICAR AL PROPIO USUARIO, MAS ADELANTE TB AL REPR
	DatosSesion datosSesion = this.getDatosSesion(request);
	if (ConstantesZPE.DELEGACION_PERFIL_ACCESO_DELEGADO.equals(datosSesion.getPerfilAcceso())){
		throw new Exception("Solo puede modificar los datos el propio usuario");
	}
	
	
	ActualizarDatosPersonalesForm formulario = ( ActualizarDatosPersonalesForm ) form;
	
	// Realizamos validaciones sobre los datos
	Principal seyconPrincipal = request.getUserPrincipal();
	if ( _log.isDebugEnabled() ) _log.debug( "Actualizando datos PAD para el usuario " + seyconPrincipal.getName() );
	
	// Ajustamos textos 
	formulario.setNombre(formulario.getNombre().trim().replaceAll( "\\s+", " " ));
	formulario.setApellido1(formulario.getApellido1() != null ? formulario.getApellido1().trim().replaceAll( "\\s+", " " ) : formulario.getApellido1());
	formulario.setApellido2(formulario.getApellido2() != null ? formulario.getApellido2().trim().replaceAll( "\\s+", " " ) : formulario.getApellido2());
	
	// Actualizamos datos
	PadAplicacionDelegate delegate = DelegateUtil.getPadAplicacionDelegate();		
	PersonaPAD personaPAD = delegate.obtenerDatosPersonaPADporUsuario(this.getDatosSesion(request).getCodigoUsuario());
	String nifOriginal = personaPAD.getNif();
	BeanUtils.copyProperties(personaPAD,formulario);
	personaPAD.setNif(nifOriginal);
			
	delegate.modificarPersona(personaPAD);
	
	return mapping.findForward("success");
}
 
Example 27
Project: OSCAR-ConCert   File: DrilldownBeanFactory.java   View Source Code Vote up 5 votes
private void setDrilldownBean(DrilldownBean drilldownBean) {
	// copy what is available in the entity bean
	try {
		BeanUtils.copyProperties( drilldownBean, getIndicatorTemplate() );
	} catch (Exception e) {
		logger.error("Error while copying IndicatorTemplate entity id " + getIndicatorTemplate().getId() , e);
	}
	
	List<?> queryResultList = null;
	
	if( getDrilldownQueryHandler() != null ) {	
		getDrilldownQueryHandler().setQuery( getIndicatorTemplateXML().getDrilldownQuery() );
		queryResultList = getDrilldownQueryHandler().execute();
	}
	
	if( queryResultList != null ) {
		
		drilldownBean.setQueryResult( queryResultList );
		drilldownBean.setQueryString( getDrilldownQueryHandler().getQuery() );
		drilldownBean.setDisplayColumns( getDrilldownQueryHandler().getColumns() );
		drilldownBean.setParameters( getDrilldownQueryHandler().getParameters() );
		drilldownBean.setRanges( getDrilldownQueryHandler().getRanges() );
		drilldownBean.setTable( getDrilldownQueryHandler().getTable() );
		
	} else {
		logger.warn(" The query results and-or the Indicator Query handler were null for Drilldown Indicator ID: " 
				+ drilldownBean.getId() + " Was this expected?");
	}

	this.drilldownBean = drilldownBean;
}
 
Example 28
Project: ElasticJob   File: JobExecutionMultipleShardingContext.java   View Source Code Vote up 5 votes
/**
 * 根据分片项获取单分片作业运行时上下文.
 * 
 * @param item 分片项
 * @return 单分片作业运行时上下文
 */
public JobExecutionSingleShardingContext createJobExecutionSingleShardingContext(final int item) {
    JobExecutionSingleShardingContext result = new JobExecutionSingleShardingContext();
    try {
        BeanUtils.copyProperties(result, this);
    } catch (final IllegalAccessException | InvocationTargetException ex) {
        throw new JobException(ex);
    }
    result.setShardingItem(item);
    result.setShardingItemParameter(shardingItemParameters.get(item));
    result.setOffset(offsets.get(item));
    return result;
}
 
Example 29
Project: HuobiRobot   File: ConvertUtil.java   View Source Code Vote up 5 votes
public static OrderInfo convertOrderIno(OrderInfoVo orderInfoVo){
	OrderInfo orderInfo = new OrderInfo();
	try {
		BeanUtils.copyProperties(orderInfo, orderInfoVo);
	} catch (IllegalAccessException | InvocationTargetException e) {
		e.printStackTrace();
	}
	return orderInfo;
}
 
Example 30
Project: sonar-scanner-maven   File: FormBeanConfig.java   View Source Code Vote up 5 votes
/**
 * <p>Compare the form properties of this bean with that of the given and
 * copy those that are not present.</p>
 *
 * @param config The form bean config to copy properties from.
 * @see #inheritFrom(FormBeanConfig)
 */
protected void inheritFormProperties(FormBeanConfig config)
    throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, InvocationTargetException {
    throwIfConfigured();

    // Inherit form property configs
    FormPropertyConfig[] baseFpcs = config.findFormPropertyConfigs();

    for (int i = 0; i < baseFpcs.length; i++) {
        FormPropertyConfig baseFpc = baseFpcs[i];

        // Do we have this prop?
        FormPropertyConfig prop =
            this.findFormPropertyConfig(baseFpc.getName());

        if (prop == null) {
            // We don't have this, so let's copy it
            prop =
                (FormPropertyConfig) RequestUtils.applicationInstance(baseFpc.getClass()
                                                                             .getName());

            BeanUtils.copyProperties(prop, baseFpc);
            this.addFormPropertyConfig(prop);
            prop.setProperties(baseFpc.copyProperties());
        }
    }
}
 
Example 31
Project: sonar-scanner-maven   File: ActionConfig.java   View Source Code Vote up 5 votes
/**
 * <p>Compare the forwards of this action with that of the given and copy
 * those that are not present.</p>
 *
 * @param baseConfig The action config to copy forwards from.
 * @see #inheritFrom(ActionConfig)
 */
protected void inheritForwards(ActionConfig baseConfig)
    throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, InvocationTargetException {
    if (configured) {
        throw new IllegalStateException("Configuration is frozen");
    }

    // Inherit forward configs
    ForwardConfig[] baseForwards = baseConfig.findForwardConfigs();

    for (int i = 0; i < baseForwards.length; i++) {
        ForwardConfig baseForward = baseForwards[i];

        // Do we have this forward?
        ForwardConfig copy = this.findForwardConfig(baseForward.getName());

        if (copy == null) {
            // We don't have this, so let's copy it
            copy =
                (ForwardConfig) RequestUtils.applicationInstance(baseForward.getClass()
                                                                            .getName());
            BeanUtils.copyProperties(copy, baseForward);

            this.addForwardConfig(copy);
            copy.setProperties(baseForward.copyProperties());
        } else {
            // process any extension for this forward
            copy.processExtends(getModuleConfig(), this);
        }
    }
}
 
Example 32
Project: OMIPlatform   File: ShopProductController.java   View Source Code Vote up 4 votes
/**
 * 获取商品详情
 *
 * @param proId 商品id
 * @param ver   商品中的第几个系列
 * @param model
 * @return
 * @throws IOException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 */
@GetMapping("productDetail/{proId}/{ver}")
public String productDetail(@PathVariable int proId, @PathVariable int ver, Model model) throws IOException, InvocationTargetException, IllegalAccessException {

    ShopProduct product = this.shopProductService.findByProId(proId);

    ShopProductDto productDto = new ShopProductDto();

    /*进行属性copy*/
    BeanUtils.copyProperties(productDto, product);
    /*
     * 解析图片路径
     *
     * 设置基础属性*/
    productDto.parse(objectMapper);
    model.addAttribute("product", productDto);


    /*获得商品中系列的属性*/
    List<Object> list2 = null;
    if (product.getMutiProduct().size() > ver && ver >= 0) {
        ver = ver;
    } else {
        ver = 0;
    }
    list2 = ShopProductDto.Json2Object(objectMapper, product.getMutiProduct().get(ver).getProDetailProperty(), PropertyPairDto.class);
    model.addAttribute("list2", list2);
    model.addAttribute("ver", ver);

    /*查询同类型热销商品三条*/
    List<ShopProduct> similarHotProducts = this.shopProductService.findHotProductByCateId(product.getCateId(), 3);
    List<ShopProductDto> similarHotProductDtos = ShopProductDto.convert(similarHotProducts, objectMapper);
    model.addAttribute("similarHotProducts", similarHotProductDtos);

    /*查询同类型最新商品三条*/
    List<ShopProduct> similarNewProducts = this.shopProductService.findNewProductByCategory(product.getCateId(), 3);
    List<ShopProductDto> similarNewProductDtos = ShopProductDto.convert(similarNewProducts, objectMapper);
    model.addAttribute("similarNewProducts", similarNewProductDtos);

    /*转换导航路径*/
    List<ShopCategory> path = CategoryUtils.convertPath(product.getCategory());
    model.addAttribute("path", path);

    /*查询评论总数*/
    int commentCount = this.shopProductCommentService.countContentByPid(proId);
    PageAndSorted page = new PageAndSorted();
    page.setCount(commentCount);
    model.addAttribute("page", page);

    /*查询用户信息*/
    model.addAttribute("user", new TzUserDetails());
    AddCartInput cartDto = new AddCartInput();
    cartDto.setNumber(1);
    cartDto.setPid(product.getProId());
    cartDto.setTid(product.getMutiProduct().get(ver).getProVerId());
    model.addAttribute("cartDto", cartDto);
    return "productDetail";
}
 
Example 33
Project: JRediClients   File: EntityServiceProxyFactory.java   View Source Code Vote up 4 votes
public <T extends EntityService> T createProxyService(T entityService) throws Exception {
	T proxyEntityService = (T) createProxyService(entityService, createProxy(entityService));
	BeanUtils.copyProperties(proxyEntityService, entityService);
	return proxyEntityService;
}
 
Example 34
Project: lams   File: OrganisationAction.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
   public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {
OrganisationAction.service = AdminServiceProxy.getService(getServlet().getServletContext());
initLocalesAndStatus();
DynaActionForm orgForm = (DynaActionForm) form;
Integer orgId = WebUtil.readIntParam(request, "orgId", true);

HttpSession session = SessionManager.getSession();
if (session != null) {
    UserDTO userDto = (UserDTO) session.getAttribute(AttributeNames.USER);
    if (userDto != null) {
	Integer userId = userDto.getUserID();
	// sysadmin, global group admin, group manager, group admin can edit group
	if (OrganisationAction.service.canEditGroup(userId, orgId)) {
	    // edit existing organisation
	    if (orgId != null) {
		Organisation org = (Organisation) OrganisationAction.service.findById(Organisation.class,
			orgId);
		BeanUtils.copyProperties(orgForm, org);
		orgForm.set("parentId", org.getParentOrganisation().getOrganisationId());
		orgForm.set("parentName", org.getParentOrganisation().getName());
		orgForm.set("typeId", org.getOrganisationType().getOrganisationTypeId());
		orgForm.set("stateId", org.getOrganisationState().getOrganisationStateId());
		SupportedLocale locale = org.getLocale();
		orgForm.set("localeId", locale != null ? locale.getLocaleId() : null);

		// find a course or subcourse with any lessons, so we warn user when he tries to delete the course
		Integer courseToDeleteLessons = org.getLessons().size() > 0 ? orgId : null;
		if (courseToDeleteLessons == null) {
		    for (Organisation subcourse : (Set<Organisation>) org.getChildOrganisations()) {
			if (subcourse.getLessons().size() > 0) {
			    courseToDeleteLessons = subcourse.getOrganisationId();
			    break;
			}
		    }
		}
		request.setAttribute("courseToDeleteLessons", courseToDeleteLessons);
	    }
	    request.getSession().setAttribute("locales", OrganisationAction.locales);
	    request.getSession().setAttribute("status", OrganisationAction.status);
	    if (OrganisationAction.service.isUserSysAdmin()
		    || OrganisationAction.service.isUserGlobalGroupAdmin()) {
		return mapping.findForward("organisation");
	    } else {
		return mapping.findForward("organisationCourseAdmin");
	    }
	}
    }
}

return error(mapping, request);
   }
 
Example 35
Project: sistra   File: EditarCuadernoCargaAction.java   View Source Code Vote up 4 votes
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
{
	log.debug( "Entramos en EditarCuadernoCarga" );
	CuadernoCargaForm cuadernoCargaForm = ( CuadernoCargaForm ) form;
	
    if (isCancelled(request)) 
    {
        log.debug("isCancelled");
        return mapping.findForward("cancel");
    }
    if (isAlta(request) || isModificacion(request)) 
    {
        log.info("isAlta || isModificacio");
        CuadernoCargaDelegate delegate = DelegateUtil.getCuadernoCargaDelegate();
        CuadernoCarga cuadernoCarga = null;
        
        if ( isModificacion( request ) )
        {
        	cuadernoCarga = delegate.obtenerCuadernoCarga( cuadernoCargaForm.getCodigo() );
        	// Si se pasa a no auditado, cambiamos tambien la fecha de auditoria
        	if ( CuadernoCarga.AUDITADO == cuadernoCarga.getEstadoAuditoria() && CuadernoCarga.AUDITADO != cuadernoCargaForm.getEstadoAuditoria () )
        	{
        		cuadernoCarga.setFechaAuditoria( null );
        	}
        	
        }
        else
        {
        	cuadernoCarga = new CuadernoCarga();
        	cuadernoCarga.setFechaAlta( new java.sql.Timestamp( new java.util.Date().getTime()  ) );
        	cuadernoCargaForm.setEstadoAuditoria( CuadernoCarga.PENDIENTE_ENVIO );
        }

        if ( CuadernoCarga.AUDITADO == cuadernoCargaForm.getEstadoAuditoria () && CuadernoCarga.AUDITADO != cuadernoCarga.getEstadoAuditoria () )
        {
        	cuadernoCarga.setFechaAuditoria( new java.sql.Timestamp( new java.util.Date().getTime()  ) );
        }
        BeanUtils.copyProperties( cuadernoCarga, cuadernoCargaForm );
        // Ponemos fecha de auditoria cuando es necesario            
        cuadernoCarga.setFechaCarga( new Timestamp ( StringUtil.cadenaAFecha( cuadernoCargaForm.getRawFechaCarga() ).getTime() ));
        if ( !isModificacion( request )) 
        {
        	cuadernoCarga.setEstadoAuditoria( CuadernoCarga.PENDIENTE_ENVIO );
        }
        
        cuadernoCargaForm.setCodigo( delegate.grabarCuadernoCarga( cuadernoCarga ) );
        
        request.setAttribute( "cuadernoCarga", cuadernoCarga );
        
    }
    
    // Establecemos si se trata de auditor o administrador a trav�s de la acci�n a realizar
    // y el estado al que se quiere pasar
    if ( isAlta( request ) )
    {
    	Util.setDevelopperMode( request );
    }
    else if ( isModificacion( request )  )
    {
    	if ( ( CuadernoCarga.AUDITADO == cuadernoCargaForm.getEstadoAuditoria() || CuadernoCarga.RECHAZADO == cuadernoCargaForm.getEstadoAuditoria() ) )
    	{
    		Util.setAuditorMode( request );
    	}
    	else
    	{
    		Util.setDevelopperMode( request );
    	}
    }
    
    
    return mapping.findForward( "success" );
}
 
Example 36
Project: sistra   File: TramitePersistenteFacadeEJB.java   View Source Code Vote up 4 votes
/**
 * Obtiene la lista de tramites en persistencia en backup pasando el nivel de autenticacion como par�metro y 
 * que su fecha de ultima modificacion este comprendida en el rango pasado como paramtros
 * 
 * @ejb.interface-method
 * @ejb.permission role-name="${role.helpdesk}"
 */
public List listarTramitesPersistentesBackup(Date fechaInicial, Date fechaFinal, String modelo, String nivelAutenticacion) {
    Session session = getSession();
    try {       	
        Query query = session
        .createQuery("FROM TramitePersistenteBackup AS m WHERE " +
   		     ((nivelAutenticacion != null) ? "m.nivelAutenticacion = :nivel and " : "") +
   		     "m.fechaModificacion <= :fechaFinal and m.fechaModificacion >= :fechaInicial" +
   		     ((modelo != null) ? " and m.tramite = :modelo" : ""));
        query.setParameter("fechaInicial",fechaInicial);
        query.setParameter("fechaFinal",fechaFinal);
        if(modelo != null) query.setParameter("modelo",modelo);
        if(nivelAutenticacion != null) query.setParameter("nivel",nivelAutenticacion);
        
        List tramites = query.list();
        
        List lstTramites = new ArrayList();
        
        // Cargamos documentos
        for (Iterator it=tramites.iterator();it.hasNext();){
        	TramitePersistenteBackup tramitePersistenteBackup = (TramitePersistenteBackup) it.next();
        	Hibernate.initialize(tramitePersistenteBackup.getDocumentosBackup());
        	// Copiamos TramitePersistenteBackup a TramitePersistente
        	{
            	TramitePersistente result = new TramitePersistente();
    	    	BeanUtils.copyProperties( result, tramitePersistenteBackup );
    			Set setDocumentos = tramitePersistenteBackup.getDocumentosBackup(); 
    			for ( Iterator itTP = setDocumentos.iterator(); itTP.hasNext(); )
    			{
    				DocumentoPersistenteBackup backup = ( DocumentoPersistenteBackup ) itTP.next();
    		    	DocumentoPersistente doc = new DocumentoPersistente();
    		    	BeanUtils.copyProperties( doc, backup );
    		    	result.addDocumento( doc );
    			}
    			lstTramites.add(result);
        	}

        }
        
        
        return lstTramites;
        
    } catch (HibernateException he) {
        throw new EJBException(he);
    }
	catch( Exception exc )
	{
		throw new EJBException( exc );
	}finally {
        close(session);
    }
}
 
Example 37
Project: OSCAR-ConCert   File: TicklerHandler.java   View Source Code Vote up 4 votes
/**
 * Adds a copy of the master tickler to each demographic id in the given Collection.
 */
public boolean addTickler( Integer[] demographicArray ) {

	if( demographicArray == null || demographicArray.length == 0 ) {
		return Boolean.FALSE;
	}

	boolean success = Boolean.TRUE;
	int i = 0;

	while( success && i < demographicArray.length ) {

		if( getTicklerList() == null ) {
			setTicklerList( new ArrayList<Tickler>() );
		}

		Integer demographicNo = demographicArray[i];
		Tickler ticklerCopy = new Tickler();

		try {
			BeanUtils.copyProperties( ticklerCopy, getMasterTickler() );
		} catch (Exception e) {
			MiscUtils.getLogger().error("Failed to create Tickler for demographicNo: " + demographicNo, e);
			success = Boolean.FALSE;
		} 

		ticklerCopy.setId( null );
		ticklerCopy.setDemographicNo( demographicNo );	

		success = getTicklerList().add( ticklerCopy );

		i++;
	}

	if( ! success ) {
		getTicklerList().clear();
		setTicklerList( null );
	}

	return addTickler( getTicklerList() );
}
 
Example 38
Project: haven-platform   File: ConfigsTest.java   View Source Code Vote up 4 votes
@Test
public void testMap() throws InvocationTargetException, IllegalAccessException {
    ContainerSource createContainerArg = new ContainerSource();

    BeanUtils.populate(createContainerArg, Collections.singletonMap("cpuShares", "23"));

    createContainerArg.getCpuShares();
    Assert.assertNotNull(createContainerArg.getCpuShares());

    ContainerSource createContainerArg2 = new ContainerSource();
    BeanUtils.populate(createContainerArg2, Collections.singletonMap("blkioWeight", "15"));

    BeanUtils.copyProperties(createContainerArg, createContainerArg2);

    Assert.assertNotNull(createContainerArg.getBlkioWeight());

}
 
Example 39
Project: oscm   File: BaseBean.java   View Source Code Vote up 3 votes
/**
 * Invoke the BeanUtils.copyProperties() method and convert the possible
 * exceptions into SaaSSystemExceptions
 * 
 * @param dest
 *            the destination object
 * @param orig
 *            the source object
 */
public void copyProperties(final Object dest, final Object orig) {
    try {
        BeanUtils.copyProperties(dest, orig);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new SaaSSystemException(e);
    }
}
 
Example 40
Project: spring-boot-jpa   File: PatientController.java   View Source Code Vote up 3 votes
/**
 * FYI - It is important that there are no setter methods for fields on the objTo that you don't
 * want to be changed (e.g. ids).
 * <p>
 * TODO - move to EntityUtils?  Needs a little more design work...
 *
 * @param id the resource Id
 * @param objTo the object to merge copy to
 * @param objFrom the object to merge copy from
 * @param <T> the resource type
 * @param <ID> the resource id type
 */
static <T, ID extends Serializable> void updateProperties(ID id, T objTo, Object objFrom) {
	try {
		BeanUtils.copyProperties(objTo, objFrom);
	}
	catch (Exception ex) {
		throw new ConflictException(Patient.RESOURCE_PATH,
				String.format("Unable to update resource %s", id.toString()), ex);
	}
}