通过数据库配置实现一个策略模式

1、策略思想

List<String> sortPolicyCode = getSortPolicyCode(orderType,warehouseId);
        if(CollectionUtil.isEmpty(sortPolicyCode)){
            return level2Inventory;
        }

        
        level2Inventory.sort((a,b)->{
            int ret = 0;
            for (String s : sortPolicyCode) {
                //其中s是spring的IOC的注解
                ILevel2InventorySorter sorter = SpringBeanFactory.getBean(s,ILevel2InventorySorter.class);
                ret = sorter.calculateSortNumber(a, b, orderType, warehouseId);
                if(ret != 0){
                    break;
                }
            }
            return ret;
        });

        return level2Inventory;
        
    /**
        通过
    **/
    private List<String>  getSortPolicyCode(String orderType,Long warehouseId) {
        String format = String.format(formatKey, warehouseId, orderType);
        List<String> policyCodes = orderTypeWithPolicyCode.get(format);
        if(CollectionUtil.isEmpty(policyCodes)){
            List<PolicyDTO> policyDTOS = policyService.selectByGroupCode(warehouseId, PickingPolicyCodes.LEVEL2_INVENTORY_SORT_GROUP_CODE);
            if(CollectionUtil.isEmpty(policyDTOS)){
                throw new WesPickingException(WesPickingErrorCode.POLICY_GROUP_CAN_NOT_FIND_POLICY.getCode(),WesPickingErrorCode.POLICY_GROUP_CAN_NOT_FIND_POLICY.getDesc(),PickingPolicyCodes.LEVEL2_INVENTORY_SORT_GROUP_CODE);
            }
            policyCodes = policyDTOS.stream().map(PolicyDTO::getPolicyCode).collect(Collectors.toList());
            orderTypeWithPolicyCode.putIfAbsent(format,policyCodes);
        }
        return policyCodes;
    }
    
    @Override
    public List<PolicyDTO> selectByGroupCode(Long warehouseId, String policyGroupCode) {
        return DozerBeanUtil.mapList(this.policyManager.selectByGroupCode(warehouseId, policyGroupCode), PolicyDTO.class);
    }
    
    public List<PolicyDO> selectByGroupCode(Long warehouseId, String policyGroupCode) {
        return this.mapper.selectByGroupCode(warehouseId, policyGroupCode);
    }
    
    
    <select id="selectByGroupCode" resultType="PolicyDO">
        SELECT p.* from evo_wes_basic.policy p , evo_wes_basic.policy_group g, evo_wes_basic.policy_group_item i
        where g.id = i.policy_group_id and i.policy_id = p.id 
        and g.warehouse_id = #{warehouseId} and g.policy_group_code = #{policyGroupCode}
        order by i.sort_num asc
    </select>
    
    //比如按日期的排序
    
    @Override
    public int calculateSortNumber(Level2InventoryFlatDTO a, Level2InventoryFlatDTO b, String orderType, Long warehouseId) {
        LotCompareReceivedDate input = new LotCompareReceivedDate();
        input.setOrderType(orderType);
        List<LotCompareReceivedDatePolicyResult> results = (List<LotCompareReceivedDatePolicyResult>) policyEngineProxy.applyPolicy(warehouseId, PickingPolicyCodes.LOT_COMPARE_RECEIVED_DATE_SORTER, input, LotCompareReceivedDatePolicyResult.class);
        int ret = 0;
        if(CollectionUtil.isNotEmpty(results)){
            for (LotCompareReceivedDatePolicyResult result : results) {
                //收货日期
                Object af1 = FiledValueHelper.getFieldByClass(result.getFiledName(), a);
                Object af2 = FiledValueHelper.getFieldByClass(result.getFiledName(), b); //>7 -1
                try {
                    if(af1 !=null && af2 != null){
                        //取到收货日期1,和收货日期2
                        Date dateOne = DateUtil.str2DateTime(af1.toString(),DateUtil.DEFAULT_DATE_TIME_FORMAT);
                        Date dateTwo = DateUtil.str2DateTime(af2.toString(),DateUtil.DEFAULT_DATE_TIME_FORMAT);
                        Long timeOne = DateUtil.diffMilli(dateOne);
                        Long timeTwo = DateUtil.diffMilli(dateTwo);
                        long receivedDate = result.getReceivedDate()*86400000L;
                        LOGGER.info("inventoryLevel2 sort by lotAtt8 ");
                        ret = compareTo(timeTwo,timeOne,receivedDate);
                    }else{
                        LOGGER.warn("date1:{} and date1:{}",af1,af2);
                    }
                } catch (Exception e) {
                    LOGGER.error("date convert  is error :{} ",e.getMessage());
                }
            }
        }
        return ret;
    }
    
    @Override
    public <T> Object applyPolicy(Long warehouseId, String policyCode, Object inputObj, Class<T> resultType) {
        
        PolicyDTO policyDTO = policyEngine.applyPolicy(warehouseId, policyCode, inputObj);
        return PolicyUtil.convertResult(policyDTO, resultType);
    }
    
    /**
     *
     * @param warehouseId 仓库ID
     * @param policyCode 策略代码
     * @param inputObj 出库单类型
     * @return
     */
    @SuppressWarnings({ "unchecked" })
    public PolicyDTO applyPolicy(Long warehouseId, String policyCode, Object inputObj) {
        if (inputObj == null) {
            throw new WesException(WesErrorCode.METHOD_ARGUMENT_CANNOT_NULL, "inputObj");
        }
        PolicyDTO policyDTO = policyCache.get(policyCode);
        if (policyDTO == null) {
            policyDTO = policyService.selectOneWithRuleByCode(warehouseId, policyCode);
            if (policyDTO == null) {
                throw new WesException(PolicyErrorCode.POLICY_NOT_FOUND, policyCode);
            }
            this.cachePolicy(policyDTO);
        }
        this.validateInput(policyDTO, inputObj);
        KieBase kieBase = kieBaseCache.get(policyCode);
        StatelessKieSession kSession = kieBase.newStatelessKieSession();

        List<Command<?>> commands = new ArrayList<>();
        BatchExecutionCommand batchCommand = CommandFactory.newBatchExecution(commands);
        Object input = this.convertInput(policyDTO, inputObj);
        log.info("drools.input: " + input);
        commands.add(CommandFactory.newInsert(new Pair<Object, Object>(input, null), RESULT_IDENTIFIER));
        try {
            ExecutionResults results = kSession.execute(batchCommand);
            Object resultObj = ((Pair<Object, Object>) results.getValue(RESULT_IDENTIFIER)).getSecond();
            if (resultObj == null) {
                policyDTO.setResult(null);
                return policyDTO;
            }
            this.validateResult(policyDTO, resultObj);
            policyDTO.setResult(resultObj);
        } catch (Exception e) {
            log.error("policy apply error, auto reload policy-'" + policyCode + "'...", e);
            this.reloadPolicy(warehouseId, policyCode);
        }
        return policyDTO;
    }
    
    
    @Override
    public PolicyDTO selectOneWithRuleByCode(Long warehouseId, String policyCode) {
        PolicyDO policyDO = policyManager.selectOneByCode(warehouseId, policyCode);
        if (policyDO != null) {
            List<PolicyRuleDO> policyRuleDOS = policyRuleManager.selectByPolicyId(warehouseId, policyDO.getId());
            policyDO.setPolicyRules(policyRuleDOS);
        }
        return DozerBeanUtil.map(policyDO, PolicyDTO.class);
    }
    
    
    @SuppressWarnings("rawtypes")
    private void validateResult(PolicyDTO policyDTO, Object resultObj) {
        if (Boolean.TRUE.equals(policyDTO.getResultMultipleFlag())) {
            if (!(resultObj instanceof List)) {
                throw new WesException(PolicyErrorCode.POLICY_RESULT_DATA_TYPE_INCONSISTENT, List.class.getName(),
                        resultObj.getClass().getName());
            }
            if (((List) resultObj).isEmpty()) {
                // throw new WesException(WesErrorCode.METHOD_ARGUMENT_CANNOT_NULL,
                // "resultObj");
                return;
            }
            resultObj = ((List) resultObj).get(0);
        }
        switch (policyDTO.getResultDataType()) {
        case Object:
            if (!(resultObj instanceof Map)) {
                throw new WesException(PolicyErrorCode.POLICY_RESULT_DATA_TYPE_INCONSISTENT,
                        policyDTO.getPolicyCode(),policyDTO.getResultDataType(), resultObj.getClass().getName());
            }
            break;
        default:
            if (resultObj instanceof Map) {
                throw new WesException(PolicyErrorCode.POLICY_RESULT_DATA_TYPE_INCONSISTENT,
                        policyDTO.getResultDataType(), resultObj.getClass().getName());
            }
            break;
        }
    }
    
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值