org.springframework.beans.BeanUtils Java Examples

The following examples show how to use org.springframework.beans.BeanUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PmsPatientServiceImpl.java    From HIS with Apache License 2.0 6 votes vote down vote up
@Override
public PmsPatientResult patientLogin(String identificationNo, String medicalRecordNo) {
   PmsPatientExample pmsPatientExample=new PmsPatientExample();
   pmsPatientExample.createCriteria().andIdentificationNoEqualTo(identificationNo).andMedicalRecordNoEqualTo(medicalRecordNo);
   List<PmsPatient> pmsPatientList = pmsPatientMapper.selectByExample(pmsPatientExample);
    if(CollectionUtil.isEmpty(pmsPatientList)||pmsPatientList.size()>1){
        return null;
    }

    //数据正常的情况下,只会返回一个病人
    PmsPatientResult pmsPatientResult=new PmsPatientResult();
    BeanUtils.copyProperties(pmsPatientList.get(0),pmsPatientResult);

    return pmsPatientResult;

}
 
Example #2
Source File: DelegatingSmartContextLoader.java    From java-technology-stack with MIT License 6 votes vote down vote up
public DelegatingSmartContextLoader() {
	if (groovyPresent) {
		try {
			Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME,
				DelegatingSmartContextLoader.class.getClassLoader());
			this.xmlLoader = (SmartContextLoader) BeanUtils.instantiateClass(loaderClass);
		}
		catch (Throwable ex) {
			throw new IllegalStateException("Failed to enable support for Groovy scripts; "
					+ "could not load class: " + GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, ex);
		}
	}
	else {
		this.xmlLoader = new GenericXmlContextLoader();
	}

	this.annotationConfigLoader = new AnnotationConfigContextLoader();
}
 
Example #3
Source File: AssertionEvaluation.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate() throws EvaluationException {
    try {
        final ExpressionParser parser = new SpelExpressionParser();
        final Expression expr = parser.parseExpression(assertion);

        final StandardEvaluationContext context = new StandardEvaluationContext();
        context.registerFunction("jsonPath",
                BeanUtils.resolveSignature("evaluate", JsonPathFunction.class));
        context.setVariables(variables);

        return expr.getValue(context, boolean.class);
    } catch (SpelEvaluationException spelex) {
        throw new EvaluationException("Assertion can not be verified : " + assertion, spelex);
    }
}
 
Example #4
Source File: OmsPromotionServiceImpl.java    From mall-swarm with Apache License 2.0 6 votes vote down vote up
/**
 * 对没满足优惠条件的商品进行处理
 */
private void handleNoReduce(List<CartPromotionItem> cartPromotionItemList, List<OmsCartItem> itemList,PromotionProduct promotionProduct) {
    for (OmsCartItem item : itemList) {
        CartPromotionItem cartPromotionItem = new CartPromotionItem();
        BeanUtils.copyProperties(item,cartPromotionItem);
        cartPromotionItem.setPromotionMessage("无优惠");
        cartPromotionItem.setReduceAmount(new BigDecimal(0));
        PmsSkuStock skuStock = getOriginalPrice(promotionProduct,item.getProductSkuId());
        if(skuStock!=null){
            cartPromotionItem.setRealStock(skuStock.getStock()-skuStock.getLockStock());
        }
        cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
        cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
        cartPromotionItemList.add(cartPromotionItem);
    }
}
 
Example #5
Source File: AbiService.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
@Transactional
public void updateAbiInfo(ReqImportAbi param) {
	Integer abiId = param.getAbiId();
	// check id exists
	checkAbiIdExist(abiId);
	// update
	AbiInfo updateAbi = new AbiInfo();
	BeanUtils.copyProperties(param, updateAbi);
	String contractAbiStr;
	try {
		contractAbiStr = JsonTools.toJSONString(param.getContractAbi());
	} catch (Exception e) {
		log.warn("abi parse string error:{}", param.getContractAbi());
		throw new NodeMgrException(ConstantCode.PARAM_FAIL_ABI_INVALID);
	}
	// check address
	String contractBin = getAddressRuntimeBin(param.getGroupId(), param.getContractAddress());
	updateAbi.setContractAbi(contractAbiStr);
	updateAbi.setContractBin(contractBin);
	updateAbi.setModifyTime(LocalDateTime.now());
	abiMapper.update(updateAbi);
}
 
Example #6
Source File: SmsStaffServiceImpl.java    From HIS with Apache License 2.0 6 votes vote down vote up
@Override//不完善--20190601-赵煜注
public int create(SmsStaffParam smsStaffParam){
    SmsStaff smsStaff = new SmsStaff();
    BeanUtils.copyProperties(smsStaffParam, smsStaff);
    smsStaff.setStatus(1);
    //查询是否有同名字
    SmsStaffExample example = new SmsStaffExample();
    example.createCriteria().andUsernameEqualTo(smsStaff.getName());
    List<SmsStaff> lists = smsStaffMapper.selectByExample(example);
    if (lists.size() > 0) {
        return 0;
    }

    //插入成功,在redis修改flag
    redisUtil.setObj("staffChangeStatus","1");

    //没有则插入数据
    return smsStaffMapper.insert(smsStaff);
}
 
Example #7
Source File: AbstractAutowireCapableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Perform a dependency check that all properties exposed have been set,
 * if desired. Dependency checks can be objects (collaborating beans),
 * simple (primitives and String), or all (both).
 * @param beanName the name of the bean
 * @param mbd the merged bean definition the bean was created with
 * @param pds the relevant property descriptors for the target bean
 * @param pvs the property values to be applied to the bean
 * @see #isExcludedFromDependencyCheck(java.beans.PropertyDescriptor)
 */
protected void checkDependencies(
		String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, @Nullable PropertyValues pvs)
		throws UnsatisfiedDependencyException {

	int dependencyCheck = mbd.getDependencyCheck();
	for (PropertyDescriptor pd : pds) {
		if (pd.getWriteMethod() != null && (pvs == null || !pvs.contains(pd.getName()))) {
			boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType());
			boolean unsatisfied = (dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_ALL) ||
					(isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
					(!isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
			if (unsatisfied) {
				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(),
						"Set this property value or disable dependency checking for this bean.");
			}
		}
	}
}
 
Example #8
Source File: GlobalVarService.java    From server with MIT License 6 votes vote down vote up
private List<GlobalVarVo> convertGlobalVarsToGlobalVarVos(List<GlobalVar> globalVars) {
    if (CollectionUtils.isEmpty(globalVars)) {
        return new ArrayList<>();
    }

    List<Integer> creatorUids = globalVars.stream()
            .map(GlobalVar::getCreatorUid)
            .filter(Objects::nonNull)
            .distinct()
            .collect(Collectors.toList());
    Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids);

    return globalVars.stream().map(globalVar -> {
        GlobalVarVo globalVarVo = new GlobalVarVo();
        BeanUtils.copyProperties(globalVar, globalVarVo);

        if (globalVar.getCreatorUid() != null) {
            User user = userMap.get(globalVar.getCreatorUid());
            if (user != null) {
                globalVarVo.setCreatorNickName(user.getNickName());
            }
        }

        return globalVarVo;
    }).collect(Collectors.toList());
}
 
Example #9
Source File: UmsAdminServiceImpl.java    From macrozheng with Apache License 2.0 6 votes vote down vote up
@Override
public UmsAdmin register(UmsAdminParam umsAdminParam) {
    UmsAdmin umsAdmin = new UmsAdmin();
    BeanUtils.copyProperties(umsAdminParam, umsAdmin);
    umsAdmin.setCreateTime(new Date());
    umsAdmin.setStatus(1);
    //查询是否有相同用户名的用户
    UmsAdminExample example = new UmsAdminExample();
    example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername());
    List<UmsAdmin> umsAdminList = adminMapper.selectByExample(example);
    if (umsAdminList.size() > 0) {
        return null;
    }
    //将密码进行加密操作
    String encodePassword = passwordEncoder.encode(umsAdmin.getPassword());
    umsAdmin.setPassword(encodePassword);
    adminMapper.insert(umsAdmin);
    return umsAdmin;
}
 
Example #10
Source File: RuleEngineService.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Transactional(rollbackFor = Throwable.class)
public boolean updateRuleEngineStatus(RuleEngineEntity ruleEngineEntity, HttpServletRequest request, HttpServletResponse response)
        throws GovernanceException {
    RuleEngineEntity rule = ruleEngineRepository.findById(ruleEngineEntity.getId());
    BeanUtils.copyProperties(rule, ruleEngineEntity, "status");
    try {
        //set payload
        ruleEngineEntity.setLastUpdate(new Date());

        //set ruleDataBaseUrl
        setRuleDataBaseUrl(ruleEngineEntity);
        //stop process
        this.stopProcessRule(request, ruleEngineEntity, rule);
        ruleEngineRepository.save(ruleEngineEntity);
        log.info("update status end");
        return true;
    } catch (Exception e) {
        log.error("update status fail", e);
        throw new GovernanceException("update status fail", e);

    }

}
 
Example #11
Source File: ExtendPropertyAccess.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
public ExtendPropertyAccess(PropertyAccessStrategy strategy,
		Class containerJavaType, String propertyName) {
	this.strategy = strategy;
	PropertyDescriptor desc = BeanUtils
			.getPropertyDescriptor(containerJavaType, propertyName);
	Class<?> returnType = null;
	MetaEntity entity = MetaEntity.localEntity(containerJavaType.getName());
	MetaProperty property = entity == null ? null
			: entity.getProperty(propertyName);
	if (property != null) {
		returnType = EntityUtil.getPropertyType(property.getType());
	}
	if (returnType == null) {
		returnType = Object.class;
	}
	this.getter = new DynamicPropertyGetterSetter(propertyName, returnType,
			desc == null ? null : desc.getReadMethod());
	this.setter = new DynamicPropertyGetterSetter(propertyName, returnType,
			desc == null ? null : desc.getWriteMethod());
}
 
Example #12
Source File: PreparationUtils.java    From data-prep with Apache License 2.0 6 votes vote down vote up
private static void walk(Object object, Predicate<Object> callback) {
    if (object == null) {
        return;
    }
    if (!callback.test(object)) {
        return;
    }
    final PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(object.getClass());
    for (PropertyDescriptor descriptor : descriptors) {
        if (!descriptor.getPropertyType().isPrimitive()) {
            try {
                final Object value = descriptor.getReadMethod().invoke(object);
                if (value instanceof Iterable) {
                    for (Object o : (Iterable) value) {
                        walk(o, callback);
                    }
                } else {
                    walk(value, callback);
                }
            } catch (Exception e) {
                LOGGER.debug("Unable to visit property '{}'.", descriptor, e);
            }
        }
    }

}
 
Example #13
Source File: AbiService.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Transactional
public void updateAbiInfo(ReqImportAbi param) {
	Long abiId = param.getAbiId();
	// check id exists
	checkAbiIdExist(abiId);
	// update
	AbiInfo updateAbi = new AbiInfo();
	BeanUtils.copyProperties(param, updateAbi);
	String contractAbiStr;
	try {
		contractAbiStr = JsonUtils.toJSONString(param.getContractAbi());
	} catch (Exception e) {
		log.warn("abi parse string error:{}", param.getContractAbi());
		throw new FrontException(ConstantCode.PARAM_FAIL_ABI_INVALID);
	}
	// check address
	String contractBin = getAddressRuntimeBin(param.getGroupId(), param.getContractAddress());
	updateAbi.setContractAbi(contractAbiStr);
	updateAbi.setContractBin(contractBin);
	updateAbi.setModifyTime(LocalDateTime.now());
	abiRepository.save(updateAbi);
}
 
Example #14
Source File: AbstractTestContextBootstrapper.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve the {@link ContextLoader} {@linkplain Class class} to use for the
 * supplied list of {@link ContextConfigurationAttributes} and then instantiate
 * and return that {@code ContextLoader}.
 * <p>If the user has not explicitly declared which loader to use, the value
 * returned from {@link #getDefaultContextLoaderClass} will be used as the
 * default context loader class. For details on the class resolution process,
 * see {@link #resolveExplicitContextLoaderClass} and
 * {@link #getDefaultContextLoaderClass}.
 * @param testClass the test class for which the {@code ContextLoader} should be
 * resolved; must not be {@code null}
 * @param configAttributesList the list of configuration attributes to process; must
 * not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em>
 * (i.e., as if we were traversing up the class hierarchy)
 * @return the resolved {@code ContextLoader} for the supplied {@code testClass}
 * (never {@code null})
 * @throws IllegalStateException if {@link #getDefaultContextLoaderClass(Class)}
 * returns {@code null}
 */
protected ContextLoader resolveContextLoader(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributesList) {

	Assert.notNull(testClass, "Class must not be null");
	Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty");

	Class<? extends ContextLoader> contextLoaderClass = resolveExplicitContextLoaderClass(configAttributesList);
	if (contextLoaderClass == null) {
		contextLoaderClass = getDefaultContextLoaderClass(testClass);
		if (contextLoaderClass == null) {
			throw new IllegalStateException("getDefaultContextLoaderClass() must not return null");
		}
	}
	if (logger.isTraceEnabled()) {
		logger.trace(String.format("Using ContextLoader class [%s] for test class [%s]",
			contextLoaderClass.getName(), testClass.getName()));
	}
	return BeanUtils.instantiateClass(contextLoaderClass, ContextLoader.class);
}
 
Example #15
Source File: NettyHandler.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
public void handleMessage(RealTimeChatMessage message){
    if(message.getMessageType()==MessageTypeEnum.NOTICE){
        Order order =  orderService.findOneByOrderId(message.getOrderId());
        ConfirmResult result = new ConfirmResult(message.getContent(),order.getStatus().getOrdinal());
        result.setUidFrom(message.getUidFrom());
        result.setOrderId(message.getOrderId());
        result.setNameFrom(message.getNameFrom());
        //push(message.getOrderId() + "-" + message.getUidTo(),result,NettyCommand.PUSH_CHAT);
        push(message.getUidTo(),result,NettyCommand.PUSH_GROUP_CHAT);
        messagingTemplate.convertAndSendToUser(message.getUidTo(),"/order-notice/"+message.getOrderId(),result);
    }
    else if(message.getMessageType() == MessageTypeEnum.NORMAL_CHAT) {
        ChatMessageRecord chatMessageRecord = new ChatMessageRecord();
        BeanUtils.copyProperties(message, chatMessageRecord);
        chatMessageRecord.setSendTime(DateUtils.getCurrentDate().getTime());
        chatMessageRecord.setFromAvatar(message.getAvatar());
        //聊天消息保存到mogondb
        chatMessageHandler.handleMessage(chatMessageRecord);
        chatMessageRecord.setSendTimeStr(DateUtils.getDateStr(chatMessageRecord.getSendTime()));
        //发送给指定用户(客户端订阅路径:/user/+uid+/+key)
        push(message.getUidTo(),chatMessageRecord,NettyCommand.PUSH_GROUP_CHAT);
        //push(message.getOrderId() + "-" + message.getUidTo(),chatMessageRecord,NettyCommand.PUSH_CHAT);
        apnsHandler.handleMessage(message.getUidTo(),chatMessageRecord);
        messagingTemplate.convertAndSendToUser(message.getUidTo(), "/" + message.getOrderId(), chatMessageRecord);
    }
}
 
Example #16
Source File: CustomApiController.java    From app-version with Apache License 2.0 6 votes vote down vote up
@ApiOperation(
        value = "添加自定义接口",
        notes = "添加自定义接口"
)
@ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "用户登录凭证", paramType = "header", dataType = "string", defaultValue = "Bearer ", required = true),
})
@PostMapping("/add")
@OperationRecord(type = OperationRecordLog.OperationType.CREATE, resource = OperationRecordLog.OperationResource.CUSTOM_API, description = OperationRecordLog.OperationDescription.CREATE_CUSTOM_API)
public ServiceResult addCustomApi(@Valid @RequestBody CustomApiRequestDTO customApiRequestDTO) {
    if (StringUtils.isBlank(customApiRequestDTO.getCustomKey())) {
        return ServiceResultConstants.NEED_PARAMS;
    }
    //校验版本区间
    ServiceResult serviceResult = basicService.checkVersion(customApiRequestDTO);
    if (serviceResult.getCode() != 200) {
        return serviceResult;
    }
    CustomApi customApi = new CustomApi();
    BeanUtils.copyProperties(customApiRequestDTO, customApi);
    customApi.setId(null);
    customApi.setDelFlag(null);
    return customApiService.createCustomApi(customApi);
}
 
Example #17
Source File: UserServiceImpl.java    From zhcc-server with Apache License 2.0 6 votes vote down vote up
/**
 * 更新用户信息
 * 
 * @param dto
 *            用户dto类
 * @return 更新影响的行数
 */
@Override
@Transactional
public int updateUser(UserDTO dto) {
    // 判断登录名是否重复
    User existsUser = userDAO.getByLoginName(dto.getLoginName());
    if(existsUser != null && existsUser.getId() != dto.getId()) {
        throw new ServiceException("登录名" + dto.getLoginName() + " 已存在");
    }
    
    User user = new User();
    BeanUtils.copyProperties(dto, user);
    int rows = userDAO.updateUser(user);
    // 保存用户角色
    if(rows > 0) {
        userRoleDAO.removeByUserId(dto.getId());
        if(dto.getRoleIds() != null && dto.getRoleIds().length > 0) {
            userRoleDAO.saveUserRole(dto.getId(), dto.getRoleIds());
        }
    }
    return rows;
}
 
Example #18
Source File: MethodLocatingFactoryBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	if (!StringUtils.hasText(this.targetBeanName)) {
		throw new IllegalArgumentException("Property 'targetBeanName' is required");
	}
	if (!StringUtils.hasText(this.methodName)) {
		throw new IllegalArgumentException("Property 'methodName' is required");
	}

	Class<?> beanClass = beanFactory.getType(this.targetBeanName);
	if (beanClass == null) {
		throw new IllegalArgumentException("Can't determine type of bean with name '" + this.targetBeanName + "'");
	}
	this.method = BeanUtils.resolveSignature(this.methodName, beanClass);

	if (this.method == null) {
		throw new IllegalArgumentException("Unable to locate method [" + this.methodName +
				"] on bean [" + this.targetBeanName + "]");
	}
}
 
Example #19
Source File: PmsBrandServiceImpl.java    From mall with Apache License 2.0 6 votes vote down vote up
@Override
public int updateBrand(Long id, PmsBrandParam pmsBrandParam) {
    PmsBrand pmsBrand = new PmsBrand();
    BeanUtils.copyProperties(pmsBrandParam, pmsBrand);
    pmsBrand.setId(id);
    //如果创建时首字母为空,取名称的第一个为首字母
    if (StringUtils.isEmpty(pmsBrand.getFirstLetter())) {
        pmsBrand.setFirstLetter(pmsBrand.getName().substring(0, 1));
    }
    //更新品牌时要更新商品中的品牌名称
    PmsProduct product = new PmsProduct();
    product.setBrandName(pmsBrand.getName());
    PmsProductExample example = new PmsProductExample();
    example.createCriteria().andBrandIdEqualTo(id);
    productMapper.updateByExampleSelective(product,example);
    return brandMapper.updateByPrimaryKeySelective(pmsBrand);
}
 
Example #20
Source File: PaymentExtensionConfServiceImpl.java    From payment with Apache License 2.0 6 votes vote down vote up
@Override
public PaymentExtensionConf getPaymentExtensionByBizTypeAndAccountType(
		Integer accountType, String bizType) {
	Assert.isNotNull(accountType, "account type is empty");
	logger.info("start get payment extension conf");
	logger.debug("[accountType = {}, bizType = {}]", accountType, bizType);
	PaymentExtensionConf conf = null;
	PaymentExtensionConfPO po = confDao.findByBizTypeAndAccountType(
			accountType, bizType);
	if (po != null) {
		conf = new PaymentExtensionConf();
		BeanUtils.copyProperties(po, conf);
	}

	logger.debug("finished get payment extension conf");
	logger.debug("[queried payment conf : {}]", conf);

	return conf;
}
 
Example #21
Source File: DmsDiseServiceImpl.java    From HIS with Apache License 2.0 6 votes vote down vote up
@Override
public List<DmsDiseResult> parseList( String idsStr) {
    //解析ids->list<Id>
    List<Long> idList = strToList(idsStr);
   //根据list<Id>查询并封装诊断简单对象
    DmsDiseExample dmsDiseExample=new DmsDiseExample();
    dmsDiseExample.createCriteria().andIdIn(idList);
    List<DmsDise> dmsDiseList=dmsDiseMapper.selectByExample(dmsDiseExample);
    List<DmsDiseResult> dmsDiseResultList = new ArrayList<>();

    if(CollectionUtil.isEmpty(dmsDiseList)){
       return null;
    }

    //封装dto
    for(DmsDise dmsDise: dmsDiseList){
        DmsDiseResult dmsDiseResult=new DmsDiseResult();
        BeanUtils.copyProperties(dmsDise,dmsDiseResult);
        dmsDiseResultList.add(dmsDiseResult);
    }
    return dmsDiseResultList;
}
 
Example #22
Source File: CommentAdminController.java    From Roothub with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected Function<? super CommentDTO, ? extends CommentVO> getDTO2VO() {
	return commentDTO -> {
		CommentVO commentVO = new CommentVO();
		BeanUtils.copyProperties(commentDTO, commentVO);
		commentVO.setPostId(commentDTO.getPostDTO().getPostId());
		commentVO.setPostName(commentDTO.getPostDTO().getTitle());
		commentVO.setPostAvatar(commentDTO.getPostDTO().getAvatar());
		commentVO.setUserId(commentDTO.getUserDTO().getUserId());
		commentVO.setUserName(commentDTO.getUserDTO().getUserName());
		commentVO.setUserAvatar(commentDTO.getUserDTO().getAvatar());
		commentVO.setCreateDate(DateUtils.formatDateTime(commentDTO.getCreateDate()));
		commentVO.setUpdateDate(DateUtils.formatDateTime(commentDTO.getUpdateDate()));
		return commentVO;
	};
}
 
Example #23
Source File: PmsPatientServiceImpl.java    From HIS with Apache License 2.0 6 votes vote down vote up
@Override
public PmsPatientResult patientLogin(String identificationNo, String medicalRecordNo) {
   PmsPatientExample pmsPatientExample=new PmsPatientExample();
   pmsPatientExample.createCriteria().andIdentificationNoEqualTo(identificationNo).andMedicalRecordNoEqualTo(medicalRecordNo);
   List<PmsPatient> pmsPatientList = pmsPatientMapper.selectByExample(pmsPatientExample);
    if(CollectionUtil.isEmpty(pmsPatientList)||pmsPatientList.size()>1){
        return null;
    }

    //数据正常的情况下,只会返回一个病人
    PmsPatientResult pmsPatientResult=new PmsPatientResult();
    BeanUtils.copyProperties(pmsPatientList.get(0),pmsPatientResult);

    return pmsPatientResult;

}
 
Example #24
Source File: AbstractNameValueExpressionTest.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
protected T createExpression(String expression) {
	ResolvableType resolvableType = ResolvableType
			.forType(getClass().getGenericSuperclass());
	Class<T> firstGenericType = (Class<T>) resolvableType.resolveGeneric(0);
	Constructor<T> constructor = null;
	try {
		constructor = firstGenericType.getDeclaredConstructor(String.class);
	}
	catch (NoSuchMethodException e) {
		throw new RuntimeException(e);
	}
	return BeanUtils.instantiateClass(constructor, expression);
}
 
Example #25
Source File: TopicOrderBo.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static TopicOrderBo<AcceptTopicConfBo> buildTopicOrderBo(Topic topic, List<TopicConf> confs) {
    TopicOrderBo<AcceptTopicConfBo> topicOrderBo = new TopicOrderBo<>();
    BeanUtils.copyProperties(topic, topicOrderBo);
    topicOrderBo.setTopicId(topic.getId());
    topicOrderBo.setAlarmGroup(topic.getTopicAlarmGroup());
    topicOrderBo.setExtraParams(topic.getTopicExtraParams());
    topicOrderBo.setSchema(topic.getTopicSchema());
    topicOrderBo.setDefaultPass(DefaultPassType.CONDITION_PASS.getIndex());
    // operationParams
    if (MapUtils.isEmpty(topicOrderBo.getOperationParams())) {
        topicOrderBo.setOperationParams(Maps.newHashMap());
    }
    TopicConfig config = topic.getTopicConfig();
    topicOrderBo.getOperationParams().put(TopicConfig.key_autoBatch, String.valueOf(config.isAutoBatch()));
    topicOrderBo.getOperationParams().put(TopicConfig.key_useCache, String.valueOf(config.isUseCache()));
    topicOrderBo.getOperationParams().put(TopicConfig.key_compressionType, String.valueOf(config.getCompressionType()));

    List<AcceptTopicConfBo> conf = Lists.newArrayListWithCapacity(confs.size());
    confs.forEach(c -> {
        AcceptTopicConfBo acceptTopicConfBo = new AcceptTopicConfBo();
        BeanUtils.copyProperties(c, acceptTopicConfBo);
        acceptTopicConfBo.setClientIdcMap(c.getTopicConfClientIdc());
        // operationParams
        if (MapUtils.isEmpty(acceptTopicConfBo.getOperationParams())) {
            acceptTopicConfBo.setOperationParams(Maps.newHashMap());
        }
        TopicConfConfig conConfig = c.getTopicConfConfig();
        if (conConfig == null || MapUtils.isEmpty(conConfig.getProxies())) {
            acceptTopicConfBo.getOperationParams().put(TopicConfConfig.key_proxies, "");
        } else {
            acceptTopicConfBo.getOperationParams().put(TopicConfConfig.key_proxies, FastJsonUtils.toJson(conConfig.getProxies()));
        }
        conf.add(acceptTopicConfBo);
    });
    topicOrderBo.setConf(conf);
    return topicOrderBo;
}
 
Example #26
Source File: WebOfficeServiceImpl.java    From jeewx with Apache License 2.0 5 votes vote down vote up
public void saveObj(WebOfficeEntity docObj, MultipartFile file) {
	WebOfficeEntity obj = null;
	if (StringUtil.isNotEmpty(docObj.getId())) {
		obj = commonDao.getEntity(WebOfficeEntity.class, docObj.getId());
		if (obj == null) {
			return;//fail
		}
	} else {
		obj = new WebOfficeEntity();
		BeanUtils.copyProperties(docObj, obj);
		String sFileName = file.getOriginalFilename();
		int iPos = sFileName.lastIndexOf('.');
		if (iPos >= 0) {
			obj.setDoctype(sFileName.substring(iPos+1));
		}
	}
	obj.setDocdate(new Date());
	LobHelper lobHelper = commonDao.getSession().getLobHelper();
	Blob data;
	try {
		data = lobHelper.createBlob(file.getInputStream(), 0);
		obj.setDoccontent(data);
	} catch (IOException e) {
		e.printStackTrace();
	}
	super.save(obj);
}
 
Example #27
Source File: PostNewsServiceImpl.java    From ChengFeng1.5 with MIT License 5 votes vote down vote up
private List<PostNewsVo> getAllPostNews(Integer pageNum,Integer pageSize) throws InterruptedException, MemcachedException, TimeoutException {
    List<PostNewsVo> postNewsVoList= Lists.newArrayList();
    User user = AuthenticationInfoUtil.getUser(userMapper, memcachedClient);
    redisTemplate.opsForZSet().reverseRange(RedisConstant.POST_NEWS_COMMUNITY_ORDER
            +user.getCommunityId(), pageNum - 1, pageSize).stream().forEach(e->{
        postNewsVoList.add((PostNewsVo) e);
    });
    if (CollectionUtils.isEmpty(postNewsVoList)){
        PostNews postNews=postNewsMapper.selectByCommunityId(user.getCommunityId());
        PostNewsVo postNewsVo=new PostNewsVo();
        BeanUtils.copyProperties(postNews,postNewsVo);
        postNewsVoList.add(postNewsVo);
    }
    return postNewsVoList;
}
 
Example #28
Source File: CglibSubclassingInstantiationStrategy.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
Object instantiate(Constructor<?> ctor, Object[] args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);

	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiate(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception e) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), String.format(
				"Failed to invoke construcor for CGLIB enhanced subclass [%s]", subclass.getName()), e);
		}
	}

	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] { NoOp.INSTANCE,//
		new LookupOverrideMethodInterceptor(beanDefinition, owner),//
		new ReplaceOverrideMethodInterceptor(beanDefinition, owner) });

	return instance;
}
 
Example #29
Source File: RouterServiceImpl.java    From zhcc-server with Apache License 2.0 5 votes vote down vote up
/**
 * 得到所有路由
 * @param includeLocked 包括状态为已禁用的
 * @return
 */
@Override
public List<RouterDTO> listAll(boolean includeLocked) {
    List<Router> list = this.routerDAO.listAll(includeLocked);
    List<RouterDTO> dtoList = new ArrayList<RouterDTO>(list.size());
    for(Router router : list) {
        RouterDTO dto = new RouterDTO();
        BeanUtils.copyProperties(router, dto);
        dto.setParentId(router.getParent() != null ? router.getParent().getId() : 0);
        dtoList.add(dto);
    }
    return dtoList;
}
 
Example #30
Source File: MdcProductServiceImpl.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
public void saveProduct(final MdcEditProductDto mdcEditProductDto, final LoginAuthDto loginAuthDto) {
	String productCode = mdcEditProductDto.getProductCode();
	MdcProduct product = new MdcProduct();
	BeanUtils.copyProperties(mdcEditProductDto, product);
	List<Long> categoryIdList = mdcEditProductDto.getCategoryIdList();
	Long categoryId = categoryIdList.get(categoryIdList.size() - 1);
	product.setCategoryId(categoryId);
	List<Long> attachmentIdList = mdcEditProductDto.getAttachmentIdList();
	product.setUpdateInfo(loginAuthDto);
	if (PublicUtil.isNotEmpty(attachmentIdList)) {
		product.setMainImage(String.valueOf(attachmentIdList.get(0)));
		product.setSubImages(Joiner.on(GlobalConstant.Symbol.COMMA).join(attachmentIdList));
	}
	MqMessageData mqMessageData;
	if (product.isNew()) {
		productCode = String.valueOf(generateId());
	} else {
		Preconditions.checkArgument(StringUtils.isNotEmpty(productCode), ErrorCodeEnum.MDC10021024.msg());
	}
	product.setProductCode(productCode);
	UpdateAttachmentDto updateAttachmentDto = new UpdateAttachmentDto(productCode, attachmentIdList, loginAuthDto);

	String body = JSON.toJSONString(updateAttachmentDto);
	String topic = AliyunMqTopicConstants.MqTagEnum.UPDATE_ATTACHMENT.getTopic();
	String tag = AliyunMqTopicConstants.MqTagEnum.UPDATE_ATTACHMENT.getTag();
	String key = RedisKeyUtil.createMqKey(topic, tag, product.getProductCode(), body);

	if (product.isNew() && PublicUtil.isNotEmpty(attachmentIdList)) {
		product.setId(generateId());
		mqMessageData = new MqMessageData(body, topic, tag, key);
		mdcProductManager.saveProduct(mqMessageData, product, true);
	} else if (product.isNew() && PublicUtil.isEmpty(attachmentIdList)) {
		product.setId(generateId());
		mdcProductMapper.insertSelective(product);
	} else {
		mqMessageData = new MqMessageData(body, topic, tag, key);
		mdcProductManager.saveProduct(mqMessageData, product, false);
	}
}