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

【通过数据库配置实现一个策略模式】1、策略思想
List 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 ListgetSortPolicyCode(String orderType,Long warehouseId) {
String format = String.format(formatKey, warehouseId, orderType);
List policyCodes = orderTypeWithPolicyCode.get(format);
if(CollectionUtil.isEmpty(policyCodes)){
List 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 selectByGroupCode(Long warehouseId, String policyGroupCode) {
return DozerBeanUtil.mapList(this.policyManager.selectByGroupCode(warehouseId, policyGroupCode), PolicyDTO.class);
}

public List selectByGroupCode(Long warehouseId, String policyGroupCode) {
return this.mapper.selectByGroupCode(warehouseId, policyGroupCode);
}



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


//比如按日期的排序

@Override
public int calculateSortNumber(Level2InventoryFlatDTO a, Level2InventoryFlatDTO b, String orderType, Long warehouseId) {
LotCompareReceivedDate input = new LotCompareReceivedDate();
input.setOrderType(orderType);
List results = (List) 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 convertis error :{} ",e.getMessage());
}
}
}
return ret;
}

@Override
public Object applyPolicy(Long warehouseId, String policyCode, Object inputObj, Class 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> 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(input, null), RESULT_IDENTIFIER));
try {
ExecutionResults results = kSession.execute(batchCommand);
Object resultObj = ((Pair) 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 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;
}
}


    推荐阅读