dubbo服务传递用户信息

provider服务提供者

定义dubbo服务请求过滤器,注意这里的filter并不是Java的filter 

@Slf4j
@Activate(group = {"PROVIDER"})
public class UserInfoProviderFilter implements Filter {
    public static ThreadLocal<UserResponse> threadLocal = new ThreadLocal();
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String userInfo = RpcContext.getContext().getAttachment(Constants.SESSION_KEY);
        if (StringUtils.isBlank(userInfo)) {
            return invoker.invoke(invocation);
        }
        try {
            UserResponse user = JsonUtils.toBean(userInfo,UserResponse.class);
            threadLocal.set(user);
            return invoker.invoke(invocation);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }
}

 

 com.alibaba.dubbo.rpc.Filter中的内容是,可想而知filter是通过spi的方式来加载实例化的

userInfoProviderFilter=com.htf.iirp.report.config.UserInfoProviderFilter
package com.htf.iirp.report.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.htf.enums.RateTypeEnum;
import com.htf.exception.CommonException;
import com.htf.exception.code.CommonErrorCode;
import com.htf.iirp.report.config.UserInfoProviderFilter;
import com.htf.iirp.report.mapper.PositionModelMapper;
import com.htf.iirp.report.mapper.PositionModelShipmentMapper;
import com.htf.iirp.report.mapper.PositionModelTargetMapper;
import com.htf.iirp.report.util.DoubleUtils;
import com.htf.model.dto.iirp.report.*;
import com.htf.model.po.damp.IndexDataPo;
import com.htf.model.po.iirp.report.PositionModelPO;
import com.htf.model.po.iirp.report.PositionModelShipmentPO;
import com.htf.model.po.iirp.report.PositionModelTargetPO;
import com.htf.model.requet.PositionModelUploadReq;
import com.htf.model.requet.iirp.IndexDataQueryRequest;
import com.htf.model.requet.iirp.report.EditShipmentSpaceRequest;
import com.htf.model.requet.iirp.report.ShipmentSpaceByPageRequest;
import com.htf.model.response.iirp.IndexInfoResponse;
import com.htf.model.response.iirp.report.ShipmentSpaceByPageResponse;
import com.htf.service.iirp.database.DataCataLogService;
import com.htf.service.iirp.report.PositionModelCalculateService;
import com.htf.util.CollectionUtils;
import com.htf.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author yangcai
 * @create 2022/6/1 20:29
 */
@Service(filter = "userInfoProviderFilter",version = "${dubbo.service.version}" )
@Slf4j
public class PositionModelCalculateServiceImpl implements PositionModelCalculateService {


    @Autowired
    private PositionModelShipmentMapper positionModelShipmentMapper;

    @Autowired
    private PositionModelTargetMapper positionModelTargetMapper;

    @Autowired
    private PositionModelMapper positionModelMapper;

    @Reference(version = "${dubbo.service.version}")
    private DataCataLogService dataCataLogService;

    @Override
    public Map<String, Object> getModelCalculateData(Long modelId) {
        List<PositionAllYieldDTO> positionAllYieldDTOList = getStrategyRate(modelId);
        Map<String, Object> stringObjectMap = new HashMap<>();
        List<PositionAllYieldDTO> lineChartList = positionAllYieldDTOList.stream().filter(x -> RateTypeEnum.UNDERLYING_YIELD.getCode().equals(x.getRateType()) || RateTypeEnum.STRATEGIC_YIELD.getCode().equals(x.getRateType())).collect(Collectors.toList());
        stringObjectMap.put("lineChart", lineChartList);
        stringObjectMap.put("columnar", positionAllYieldDTOList.stream().filter(x -> RateTypeEnum.STRATEGIC_FALLBACK.getCode().equals(x.getRateType())).collect(Collectors.toList()));
        stringObjectMap.put("annualizedRate", positionAllYieldDTOList.stream().filter(x -> RateTypeEnum.STRATEGIC_ANNUALIZAD_YIELD.getCode().equals(x.getRateType())).findFirst().get().getAnnualizedRate());
        stringObjectMap.put("annualizedVolatility", positionAllYieldDTOList.stream().filter(x -> RateTypeEnum.STRATEGIC_ANNUALIZAD_VOLATILITY.getCode().equals(x.getRateType())).findFirst().get().getAnnualizedVolatility());
        stringObjectMap.put("maxWithdrawalRate", positionAllYieldDTOList.stream().filter(x -> RateTypeEnum.MAX_POLICY_FALLBACK.getCode().equals(x.getRateType())).findFirst().get().getMaxWithdrawalRate());
        List<PositionAllYieldDTO.RateEntity> rateEntityList = new ArrayList<>();
        lineChartList.forEach(x->{
            PositionAllYieldDTO.RateEntity rateEntity = new PositionAllYieldDTO.RateEntity();
            rateEntity.setName(x.getTargetVariety());
            rateEntity.setRate(x.getYields()[x.getYields().length-1]);
            rateEntityList.add(rateEntity);
        });
        stringObjectMap.put("lineChartNewest",rateEntityList);
        return stringObjectMap;
    }

    @Override
    public Boolean indexIsExists(String indexCode) {
        IndexDataQueryRequest request = new IndexDataQueryRequest();
        request.setIndexCodes(Arrays.asList(indexCode));
        request.setCurrentUserId(UserInfoProviderFilter.threadLocal.get().getId());
        try {
            List<IndexInfoResponse>  indexInfoResponses = dataCataLogService.getIndexInfo(request);
            if(CollectionUtils.isEmpty(indexInfoResponses)){
                return Boolean.FALSE;
            }
        }catch (CommonException e){
            if(CommonErrorCode.INDEX_DATA_QUERY_INFO_EMPTY.getErrorMsg().equals(e.getErrorMsg()) && CommonErrorCode.INDEX_DATA_QUERY_INFO_EMPTY.getErrorCode().equals(e.getErrorCode())){
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 计算收益率
     * @param modelId
     * @return
     */
    @Override
    public List<PositionAllYieldDTO> getStrategyRate(Long modelId) {

        PositionModelPO positionModelPO = positionModelMapper.getPositionModel(modelId);
        if(positionModelPO == null){
            throw new CommonException("130","无模型信息");
        }
        List<PositionAllYieldDTO> positionAllYieldDTOList = new ArrayList<>();
        List<PositionModelTargetPO> positionModelTargetPOS = positionModelTargetMapper.findAllByModelId(modelId);
        if (CollectionUtils.isEmpty(positionModelTargetPOS)) {
            throw new CommonException("103", positionModelPO.getModelName() + "没有关联标的品种");
        }
        Map<Long, String> targetIdToName = positionModelTargetPOS.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getTargetVariety()));
        List<Long> targetIdList = positionModelTargetPOS.stream().map(x->x.getId()).collect(Collectors.toList());
        List<PositionModelShipmentPO> positionModelShipmentPOList = positionModelShipmentMapper.findListByModelId(modelId,targetIdList);

        List<Long> newTargetIdList = positionModelShipmentPOList.stream().map(x->x.getTargetId()).collect(Collectors.toList());
        List<Long> deletedTargetIdList = targetIdList.stream().filter(x->!newTargetIdList.contains(x)).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(deletedTargetIdList)){
            List<String> deletedTargetNameList = deletedTargetIdList.stream().map(x->targetIdToName.get(x)).collect(Collectors.toList());
            String targetNames = deletedTargetNameList.stream().collect(Collectors.joining(","));
            throw new CommonException("131",String.format("标的品种(%s)缺少仓位数据",targetNames));
        }
        //开盘价
        Map<String, Set<Long>> openIndexCodeToTargetIdMap = positionModelTargetPOS.stream().collect(Collectors.groupingBy(PositionModelTargetPO::getOpeningPrice,Collectors.mapping(PositionModelTargetPO::getId,Collectors.toSet())));
        Set<PositionIndexDataDTO> openIndexDataList = getIndexDataByIndexCode(openIndexCodeToTargetIdMap);
        if (CollectionUtils.isEmpty(openIndexDataList)) {
            throw new CommonException("101", positionModelPO.getModelName() + "开盘价无指标数据");
        }
        Map<String, StrategyRateDTO> openIndexDataMap = openIndexDataList.stream().collect(Collectors.toMap(x -> x.getIndexTime().getTime() + "_" + x.getTargetId(), x -> new StrategyRateDTO(x.getIndexTime().getTime(), x.getTargetId(), x.getIndexCode(), x.getIndexData(), null, null)));

        //收盘价
        Map<String, Set<Long>> closeIndexCodeToTargetIdMap = positionModelTargetPOS.stream().collect(Collectors.groupingBy(PositionModelTargetPO::getClosingPrice,Collectors.mapping(PositionModelTargetPO::getId,Collectors.toSet())));
        Set<PositionIndexDataDTO> closeIndexDataList = getIndexDataByIndexCode(closeIndexCodeToTargetIdMap);
        if (CollectionUtils.isEmpty(closeIndexDataList)) {
            throw new CommonException("102", positionModelPO.getModelName() + "收盘价无指标数据");
        }
        Map<String, StrategyRateDTO> closeIndexDataMap = closeIndexDataList.stream().collect(Collectors.toMap(x -> x.getIndexTime().getTime() + "_" + x.getTargetId(), x -> new StrategyRateDTO(x.getIndexTime().getTime(), x.getTargetId(), null, null, x.getIndexCode(), x.getIndexData())));

        List<StrategyRateDTO> strategyRateDTOList = positionModelShipmentPOList.stream().map(x -> new StrategyRateDTO(x.getShipmentTime().getTime(), x.getTargetId(), x.getShipmentSpace())).collect(Collectors.toList());
        strategyRateDTOList.forEach(x -> {
            StrategyRateDTO open = openIndexDataMap.get(x.getShipmentTime() + "_" + x.getTargetId());
            if (open != null) {
                BeanUtils.copyProperties(open, x, getNullPropertyNames(open));
            }
            StrategyRateDTO close = closeIndexDataMap.get(x.getShipmentTime() + "_" + x.getTargetId());
            if (close != null) {
                BeanUtils.copyProperties(close, x, getNullPropertyNames(close));
            }

        });
        strategyRateDTOList = strategyRateDTOList.stream().sorted(Comparator.comparing(StrategyRateDTO::getShipmentTime)).collect(Collectors.toList());

        Map<Long, Double> closeStrategyRateMap = strategyRateDTOList.stream().collect(Collectors.groupingBy(x -> x.getShipmentTime(), Collectors.summingDouble(x -> DoubleUtils.mul(x.getClosingPrice() == null ? 0 : x.getClosingPrice(), x.getShipmentSpace() == null ? 0 : x.getShipmentSpace()))));
        Map<Long, Double> openStrategyRateMap = strategyRateDTOList.stream().collect(Collectors.groupingBy(x -> x.getShipmentTime(), Collectors.summingDouble(x -> DoubleUtils.mul(x.getOpeningPrice() == null ? 0 : x.getOpeningPrice(), x.getShipmentSpace() == null ? 0 : x.getShipmentSpace()))));

        processUnderlyingYield(strategyRateDTOList,targetIdToName,positionAllYieldDTOList);
        processStraregicYield(closeStrategyRateMap, openStrategyRateMap,positionAllYieldDTOList);
        processFallback(closeStrategyRateMap, openStrategyRateMap,positionAllYieldDTOList);
        processStrategicAnnualizadYield(closeStrategyRateMap, openStrategyRateMap,positionAllYieldDTOList);
        processStrategicAnnualizadVolatility(closeStrategyRateMap, openStrategyRateMap,positionAllYieldDTOList);

        return positionAllYieldDTOList;
    }

    /**
     * 处理各标的收益率
     * @param strategyRateDTOList
     * @param targetIdToName
     * @param positionAllYieldDTOList
     */
     void processUnderlyingYield(List<StrategyRateDTO> strategyRateDTOList,Map<Long, String> targetIdToName,List<PositionAllYieldDTO> positionAllYieldDTOList){
         Map<Long, List<StrategyRateDTO>> longListMap = strategyRateDTOList.stream().collect(Collectors.groupingBy(StrategyRateDTO::getTargetId));
         longListMap.forEach((k, v) -> {
             List<PositionTargetYieldDTO> positionTargetYieldDTOList = new ArrayList<>();
             v = v.stream().sorted(Comparator.comparing(StrategyRateDTO::getShipmentTime)).collect(Collectors.toList());
             positionTargetYieldDTOList.add(new PositionTargetYieldDTO(v.get(0).getShipmentTime(), 0.0));
             for (int i = 1; i < v.size(); i++) {
                 if (v.get(i - 1).getClosingPrice() == null || v.get(i - 1).getClosingPrice() == 0) {
                     positionTargetYieldDTOList.add(new PositionTargetYieldDTO(v.get(i).getShipmentTime(), 0.00));
                 } else {
                     Double yield;
                     if (getTodayDate().equals(v.get(i).getShipmentTime())) {
                         if (v.get(i).getOpeningPrice() != null) {
                             yield = DoubleUtils.div(DoubleUtils.sub(v.get(i).getOpeningPrice(), v.get(i - 1).getClosingPrice() == null ? 0 : v.get(i - 1).getClosingPrice()), v.get(i - 1).getClosingPrice() == null ? 0 : v.get(i - 1).getClosingPrice());
                         } else {
                             yield = 0.00;
                         }
                     } else {
                         yield = DoubleUtils.div(DoubleUtils.sub(v.get(i).getClosingPrice() == null ? 0 : v.get(i).getClosingPrice(), v.get(i - 1).getClosingPrice() == null ? 0 : v.get(i - 1).getClosingPrice()), v.get(i - 1).getClosingPrice() == null ? 0 : v.get(i - 1).getClosingPrice());
                     }
                     positionTargetYieldDTOList.add(new PositionTargetYieldDTO(v.get(i).getShipmentTime(), yield));
                 }
             }
             ConventData(positionTargetYieldDTOList, positionAllYieldDTOList, targetIdToName.get(k) + RateTypeEnum.UNDERLYING_YIELD.getValue(), RateTypeEnum.UNDERLYING_YIELD.getCode());
         });
     }

    /**
     * 处理策略收益率
     * @param closeStrategyRateMap
     * @param openStrategyRateMap
     * @param positionAllYieldDTOList
     */
     void processStraregicYield(Map<Long, Double> closeStrategyRateMap, Map<Long, Double> openStrategyRateMap,List<PositionAllYieldDTO> positionAllYieldDTOList){
         List<PositionTargetYieldDTO> positionTargetYieldDTOList = new ArrayList<>();
         TreeMap<Long, Double> strategyRateTreeMap = new TreeMap(closeStrategyRateMap);
         Set<Long> timeSet = strategyRateTreeMap.keySet();
         List<Long> timeList = new ArrayList<>(timeSet);
         positionTargetYieldDTOList.add(new PositionTargetYieldDTO(timeList.get(0), 0.0));
         for (int i = 1; i < timeList.size(); i++) {
             if (closeStrategyRateMap.get(timeList.get(i - 1)) == null || closeStrategyRateMap.get(timeList.get(i - 1)) == 0) {
                 positionTargetYieldDTOList.add(new PositionTargetYieldDTO(timeList.get(i), 0.00));
             } else {
                 Double yield;
                 if (getTodayDate().equals(timeList.get(i))) {
                     if (openStrategyRateMap.get(timeList.get(i)) != null) {
                         yield = DoubleUtils.div(DoubleUtils.sub(openStrategyRateMap.get(timeList.get(i)), closeStrategyRateMap.get(timeList.get(i - 1))), closeStrategyRateMap.get(timeList.get(i - 1)));
                     } else {
                         yield = 0.00;
                     }
                 } else {
                     yield = DoubleUtils.div(DoubleUtils.sub(closeStrategyRateMap.get(timeList.get(i)), closeStrategyRateMap.get(timeList.get(i - 1))), closeStrategyRateMap.get(timeList.get(i - 1)));
                 }
                 positionTargetYieldDTOList.add(new PositionTargetYieldDTO(timeList.get(i), yield));
             }
         }
         ConventData(positionTargetYieldDTOList, positionAllYieldDTOList, RateTypeEnum.STRATEGIC_YIELD.getValue(), RateTypeEnum.STRATEGIC_YIELD.getCode());
     }

    /**
     * 处理策略回测和最大回测
     * @param closeStrategyRateMap
     * @param openStrategyRateMap
     * @param positionAllYieldDTOList
     */
    void processFallback(Map<Long, Double> closeStrategyRateMap, Map<Long, Double> openStrategyRateMap,List<PositionAllYieldDTO> positionAllYieldDTOList){
        TreeMap<Long, Double> strategyRateTreeMap = new TreeMap(closeStrategyRateMap);
        Set<Long> timeSet = strategyRateTreeMap.keySet();
        List<Long> timeList = new ArrayList<>(timeSet);
        List<PositionTargetYieldDTO> retreatYieldList = new ArrayList<>();
        //策略回撤
        Double max = 0.0, maxWithdrawalRate = Double.MAX_VALUE;
        Iterator<Long> iterator = closeStrategyRateMap.keySet().iterator();
        while (iterator.hasNext()) {
            Long currentDate = iterator.next();
            if(getTodayDate().equals(currentDate)){
                max = Math.max(max, openStrategyRateMap.get(currentDate));
            }else{
                max = Math.max(max, closeStrategyRateMap.get(currentDate));
            }
        }
        for (int i = 0; i < timeList.size(); i++) {
            if (max == 0) {
                retreatYieldList.add(new PositionTargetYieldDTO(timeList.get(i), 0.00));
                maxWithdrawalRate = Math.min(0.00, maxWithdrawalRate);
            } else {
                Double yield;
                Double current;
                if(getTodayDate().equals(timeList.get(i))){
                     current = (openStrategyRateMap.get(timeList.get(i)) == null ? 0.0 : openStrategyRateMap.get(timeList.get(i)));
                }else {
                     current = (closeStrategyRateMap.get(timeList.get(i)) == null ? 0.0 : closeStrategyRateMap.get(timeList.get(i)));
                }
                yield = DoubleUtils.div(DoubleUtils.sub(current, max), max);
                retreatYieldList.add(new PositionTargetYieldDTO(timeList.get(i), yield));
                maxWithdrawalRate = Math.min(yield, maxWithdrawalRate);
            }
        }
        ConventData(retreatYieldList, positionAllYieldDTOList, RateTypeEnum.STRATEGIC_FALLBACK.getValue(), RateTypeEnum.STRATEGIC_FALLBACK.getCode());

        positionAllYieldDTOList.add(new PositionAllYieldDTO(RateTypeEnum.MAX_POLICY_FALLBACK.getValue(), RateTypeEnum.MAX_POLICY_FALLBACK.getCode(), DoubleUtils.getFormat(maxWithdrawalRate), null, null));

    }

    /**
     * 处理策略年化收益率
     * @param closeStrategyRateMap
     * @param openStrategyRateMap
     * @param positionAllYieldDTOList
     */
    void processStrategicAnnualizadYield( Map<Long, Double> closeStrategyRateMap, Map<Long, Double> openStrategyRateMap,List<PositionAllYieldDTO> positionAllYieldDTOList){
        Long minDate = closeStrategyRateMap.keySet().stream().min(Comparator.comparing(Long::longValue)).get();
        Long maxDate = closeStrategyRateMap.keySet().stream().max(Comparator.comparing(Long::longValue)).get();
        Double annualizedRate = 0.00;
        if (closeStrategyRateMap.get(minDate) != null && closeStrategyRateMap.get(minDate) != 0) {
            annualizedRate = DoubleUtils.mul(DoubleUtils.div(DoubleUtils.sub(openStrategyRateMap.get(maxDate), closeStrategyRateMap.get(minDate)), DoubleUtils.mul(closeStrategyRateMap.get(minDate), Double.valueOf(getDaysByDateRange(minDate, maxDate)))), 365.00);
        }
        positionAllYieldDTOList.add(new PositionAllYieldDTO(RateTypeEnum.STRATEGIC_ANNUALIZAD_YIELD.getValue(), RateTypeEnum.STRATEGIC_ANNUALIZAD_YIELD.getCode(), null, null, DoubleUtils.getFormat(annualizedRate)));
    }

    /**
     * 策略年化波动率
     * @param closeStrategyRateMap
     * @param openStrategyRateMap
     * @param positionAllYieldDTOList
     */
    void processStrategicAnnualizadVolatility(Map<Long, Double> closeStrategyRateMap, Map<Long, Double> openStrategyRateMap,List<PositionAllYieldDTO> positionAllYieldDTOList){
        Long maxDate = closeStrategyRateMap.keySet().stream().max(Comparator.comparing(Long::longValue)).get();
        TreeMap<Long, Double> strategyRateTreeMap = new TreeMap(closeStrategyRateMap);
        Set<Long> timeSet = strategyRateTreeMap.keySet();
        List<Long> timeList = new ArrayList<>(timeSet);
        if (getTodayDate().equals(maxDate) && timeList.size() >= 2) {
            Double LastDay = closeStrategyRateMap.get(timeList.get(timeList.size() - 2));
            Double today = openStrategyRateMap.get(maxDate);
            Double yield = DoubleUtils.mul(DoubleUtils.div(DoubleUtils.sub(today, LastDay), LastDay), Math.sqrt(252));
            positionAllYieldDTOList.add(new PositionAllYieldDTO(RateTypeEnum.STRATEGIC_ANNUALIZAD_VOLATILITY.getValue(), RateTypeEnum.STRATEGIC_ANNUALIZAD_VOLATILITY.getCode(), null, DoubleUtils.getFormat(yield), null));
        } else {
            positionAllYieldDTOList.add(new PositionAllYieldDTO(RateTypeEnum.STRATEGIC_ANNUALIZAD_VOLATILITY.getValue(), RateTypeEnum.STRATEGIC_ANNUALIZAD_VOLATILITY.getCode(), null, DoubleUtils.getFormat(0.00), null));
        }
    }
    void ConventData(List<PositionTargetYieldDTO> retreatYieldList, List<PositionAllYieldDTO> positionAllYieldDTOList, String targetVariety, Integer rateType) {
        PositionAllYieldDTO retreatYieldBO = new PositionAllYieldDTO();
        if (rateType != null) {
            retreatYieldBO.setRateType(rateType);
        }
        retreatYieldBO.setTargetVariety(targetVariety);
        String[] retreatDates = retreatYieldList.stream().map(x -> DateUtils.getStringByTimeStamp(x.getTargetTime())).collect(Collectors.toList()).toArray(new String[retreatYieldList.size()]);
        retreatYieldBO.setDates(retreatDates);
        String[] retreatYields = retreatYieldList.stream().map(x -> DoubleUtils.getFormat(x.getTargetYield())).collect(Collectors.toList()).toArray(new String[retreatYieldList.size()]);
        retreatYieldBO.setYields(retreatYields);
        positionAllYieldDTOList.add(retreatYieldBO);
    }

    Long getTodayDate() {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String today = simpleDateFormat.format(new Date());
            return simpleDateFormat.parse(today).getTime();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    long getDaysByDateRange(long starTime, long endTime) {
        Long num = endTime - starTime;
        Long counts = num / 24 / 60 / 60 / 1000;
        return counts+1;
    }

    /**
     * 指标数据
     */
    public Set<PositionIndexDataDTO> getIndexDataByIndexCode(Map<String, Set<Long>> map) {
        try {
            List<String> indexCodeList = new ArrayList<>(map.keySet());
            Set<PositionIndexDataDTO> positionIndexDataDTOList = new HashSet<>();
            IndexDataQueryRequest indexDataQueryRequest = new IndexDataQueryRequest();
            indexDataQueryRequest.setIndexCodes(indexCodeList);
            indexDataQueryRequest.setCurrentUserId(UserInfoProviderFilter.threadLocal.get().getId());
            List<IndexDataPo> indexDataPoList = dataCataLogService.getIndexData(indexDataQueryRequest);
            indexDataPoList.forEach(x -> {
                Set<Long> targetIdList = map.get(x.getIndexCode());
                targetIdList.forEach(y->{
                    PositionIndexDataDTO positionIndexDataDTO = new PositionIndexDataDTO();
                    positionIndexDataDTO.setIndexCode(x.getIndexCode());
                    positionIndexDataDTO.setTargetId(y);
                    positionIndexDataDTO.setIndexTime(x.getDataDate());
                    positionIndexDataDTO.setIndexData(x.getDataValue());
                    positionIndexDataDTOList.add(positionIndexDataDTO);
                });
            });
            return positionIndexDataDTOList;
        } catch (Exception e) {
           log.error(e.getMessage(),e);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsertPositionShipment(List<PositionModelUploadReq> uploadReqList, Long modelId) {
        if(CollectionUtils.isEmpty(uploadReqList)){
            throw new CommonException("131","上传信息为空");
        }
        PositionModelPO positionModelPO = positionModelMapper.getPositionModel(modelId);
        List<PositionModelShipmentPO>  existList = positionModelShipmentMapper.queryByModelId(modelId);
        List<String> existModelIdTargerTimeStr = existList.stream().map(x->x.getModelId()+"_"+x.getTargetId()+"_"+x.getShipmentTime().getTime()).collect(Collectors.toList());
        Map<String,Long> existModelIdTargerTimeMap = existList.stream().collect(Collectors.toMap(x->x.getModelId()+"_"+x.getTargetId()+"_"+x.getShipmentTime().getTime(),x->x.getId()));
        List<String> modelIdTargerTimeStr = new ArrayList<>();
        if(positionModelPO == null){
            throw new CommonException("130","无模型信息");
        }
        uploadReqList.stream().forEach(x -> {
            PositionModelShipmentPO positionModelShipmentPO = new PositionModelShipmentPO();
            Long targetId = positionModelTargetMapper.findTargetIdByModelAndTargetVariety(modelId, x.getTargetName());
            if (targetId != null) {
                BeanUtils.copyProperties(x, positionModelShipmentPO);
                positionModelShipmentPO.setCreateUserId(0L);
                positionModelShipmentPO.setUpdateUserId(0L);
                if (x.getShipmentSpace() == null) {
                    positionModelShipmentPO.setShipmentSpace(0.00);
                }
                positionModelShipmentPO.setTargetId(targetId);
                positionModelShipmentPO.setModelId(modelId);
                String key = modelId+"_"+targetId+"_"+x.getShipmentTime().getTime();
                modelIdTargerTimeStr.add(key);
                List<PositionModelShipmentPO> positionModelShipmentPOList = positionModelShipmentMapper.isExist(modelId, x.getShipmentTime(), targetId);
                if (!CollectionUtils.isEmpty(positionModelShipmentPOList)) {
                    PositionModelShipmentPO positionModelShipmentPOUpdate = new PositionModelShipmentPO();
                    positionModelShipmentPOUpdate.setId(positionModelShipmentPOList.get(0).getId());
                    positionModelShipmentPOUpdate.setShipmentSpace(x.getShipmentSpace());
                    positionModelShipmentMapper.updateByPrimaryKeySelective(positionModelShipmentPOUpdate);
                } else {
                    positionModelShipmentMapper.insert(positionModelShipmentPO);
                }
            } else {
                throw new CommonException("101", positionModelPO.getModelName() + "-" + x.getTargetName() + "没找到TARGETID");
            }
        });

        List<Long>  deleteIdList = existModelIdTargerTimeStr.stream().filter(x-> !modelIdTargerTimeStr.contains(x)).map(x->existModelIdTargerTimeMap.get(x)).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(deleteIdList)){
            positionModelShipmentMapper.deleteByIds(deleteIdList);
        }
    }

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    @Override
    public List<String> exportTemplateHeader(Long modelId) {
        List<String> headerList = new ArrayList<>();
        headerList.add("时间");
        List<PositionModelTargetPO> positionModelTargetPOList = positionModelTargetMapper.findAllByModelId(modelId);
        headerList.addAll(positionModelTargetPOList.stream().map(x -> x.getTargetVariety()).collect(Collectors.toList()));
        return headerList;
    }

    @Override
    public ExportDataDTO exportData(Long modelId) {
        ExportDataDTO exportDataDTO = new ExportDataDTO();
        List<String> headerList = new ArrayList<>();
        List<List<Object>> dataList = new ArrayList<>();
        headerList.add("时间");
        List<PositionAllYieldDTO> positionAllYieldDTOList = getStrategyRate(modelId);
        List<PositionAllYieldDTO> underlyingList = positionAllYieldDTOList.stream().filter(x -> RateTypeEnum.UNDERLYING_YIELD.getCode().equals(x.getRateType())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(underlyingList)) {
            headerList.addAll(underlyingList.stream().map(x -> x.getTargetVariety()).collect(Collectors.toList()));
        } else {
            return null;
        }
        List<PositionAllYieldDTO> strategicYieldList = positionAllYieldDTOList.stream().filter(x -> RateTypeEnum.STRATEGIC_YIELD.getCode().equals(x.getRateType())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(strategicYieldList)) {
            headerList.addAll(strategicYieldList.stream().map(x -> x.getTargetVariety()).collect(Collectors.toList()));
        }
        List<String[]> dateList = underlyingList.stream().map(x -> x.getDates()).collect(Collectors.toList());
        String[] dateArray = dateList.get(0);
        List<String[]> dateYieldList = underlyingList.stream().map(x -> x.getYields()).collect(Collectors.toList());
        dateYieldList.addAll(strategicYieldList.stream().map(x -> x.getYields()).collect(Collectors.toList()));
        for (int i = 0; i < dateArray.length; i++) {
            List<Object> list = new ArrayList<>();
            list.add(dateArray[i]);
            for (int j = 0; j < dateYieldList.size(); j++) {
                list.add(DoubleUtils.getPercentFormat(Double.valueOf(dateYieldList.get(j)[i])));
            }
            dataList.add(list);
        }
        exportDataDTO.setHeaderList(headerList);
        exportDataDTO.setDataList(dataList);
        return exportDataDTO;
    }

    @Override
    public PageInfo<ShipmentSpaceByPageResponse> findShipmentSpaceByPage(ShipmentSpaceByPageRequest shipmentSpaceByPageRequest) {
        PositionModelPO positionModelPO = positionModelMapper.getPositionModel(Math.abs(shipmentSpaceByPageRequest.getModelId()));
        if(positionModelPO == null){
            throw new CommonException("130","无模型信息");
        }
        shipmentSpaceByPageRequest.setModelId(Math.abs(shipmentSpaceByPageRequest.getModelId()));
        List<PositionModelTargetPO>  positionModelTargetPOS = positionModelTargetMapper.findAllByModelId(shipmentSpaceByPageRequest.getModelId());
        if (CollectionUtils.isEmpty(positionModelTargetPOS)) {
            throw new CommonException("103", positionModelPO.getModelName() + "没有关联标的品种");
        }
        List<Long> targetIdList = positionModelTargetPOS.stream().map(x->x.getId()).collect(Collectors.toList());
        Map<Long,String>  targetIdToName = positionModelTargetPOS.stream().collect(Collectors.toMap(x->x.getId(),x->x.getTargetVariety()));
        PageMethod.startPage(shipmentSpaceByPageRequest.getPageNum(), shipmentSpaceByPageRequest.getPageSize());
        List<ShipmentSpaceByPageDTO> shipmentSpaceByPageRsps = positionModelShipmentMapper.findShipmentSpaceByPage(shipmentSpaceByPageRequest.getModelId(),targetIdList);
        PageInfo<ShipmentSpaceByPageDTO> responses = new PageInfo(shipmentSpaceByPageRsps);

        PageInfo<ShipmentSpaceByPageResponse> shipmentSpaceByPageRspPageInfo = new PageInfo<>();
        BeanUtils.copyProperties(responses, shipmentSpaceByPageRspPageInfo);
        List<ShipmentSpaceByPageResponse> shipmentSpaceByPageRspList = new ArrayList<>();
        responses.getList().forEach(x -> {
            List<ShipmentSpaceByPageResponse.PositionModelShipment> positionModelShipmentPOList = new ArrayList<>();
            ShipmentSpaceByPageResponse shipmentSpaceByPageRsp = new ShipmentSpaceByPageResponse();
            BeanUtils.copyProperties(x, shipmentSpaceByPageRsp);
            shipmentSpaceByPageRsp.setShipmentTime(DateUtils.getDateLong(x.getShipmentTime()));
            String[] targetIds = x.getTargetIds().split("-");
            String[] shipmentSpaces = x.getShipmentSpaces().split("-");
            String[] ids = x.getIds().split("-");
            int len = ids.length;
            for (int i = 0; i < len; i++) {
                ShipmentSpaceByPageResponse.PositionModelShipment positionModelShipment = new ShipmentSpaceByPageResponse.PositionModelShipment();
                positionModelShipment.setId(Long.valueOf(ids[i]));
                positionModelShipment.setModelId(shipmentSpaceByPageRequest.getModelId());
                positionModelShipment.setTargetId(Long.valueOf(targetIds[i]));
                String targetName =  targetIdToName.get(positionModelShipment.getTargetId());
                if(!StringUtils.isEmpty(targetName)){
                    positionModelShipment.setTargetName(targetName);
                }
                positionModelShipment.setShipmentSpace(Double.valueOf(shipmentSpaces[i]));
                positionModelShipmentPOList.add(positionModelShipment);
            }
            shipmentSpaceByPageRsp.setPositionModelShipmentPOS(positionModelShipmentPOList);
            shipmentSpaceByPageRspList.add(shipmentSpaceByPageRsp);
        });
        shipmentSpaceByPageRspPageInfo.setList(shipmentSpaceByPageRspList);
        return shipmentSpaceByPageRspPageInfo;
    }

    @Override
    public void editShipmentSpace(EditShipmentSpaceRequest editShipmentSpaceRequest) {
        positionModelShipmentMapper.editShipmentSpace(editShipmentSpaceRequest.getId(), Double.valueOf(editShipmentSpaceRequest.getSpace()));
    }
}

 在service中配置@Service(filter = "userInfoProviderFilter"),使用userInfoProviderFilter.threadLocal.get().getId()获取用户信息

consumer接收web请求,是服务的消费者 

 配置拦截器:获取用户信息

public class SaTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserResponse currentUser = (UserResponse) StpUtil.getSession().get(Constants.SESSION_KEY);
        RpcContext.getContext().setAttachment(Constants.SESSION_KEY, JsonUtils.toString(currentUser));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

 注册拦截器:

@Configuration
public class SaTokenConfigure extends WebMvcConfigurationSupport {
    @Bean
    public SaRouteInterceptor getAuthInterceptor() {
        return new SaRouteInterceptor();

    }

    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册Sa-Token的路由拦截器
        registry.addInterceptor(getAuthInterceptor())
                .addPathPatterns("/*/**")
                .excludePathPatterns("/authentication/login", "/publish/email", "/info/upload/callback");
        registry.addInterceptor(new SaTokenInterceptor())
                .addPathPatterns("/*/**")
                .excludePathPatterns("/authentication/login", "/publish/email", "/info/upload/callback");
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值