栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

dubbo服务传递用户信息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

dubbo服务传递用户信息

provider服务提供者

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

@Slf4j
@Activate(group = {"PROVIDER"})
public class UserInfoProviderFilter implements Filter {
    public static ThreadLocal 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;


@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 getModelCalculateData(Long modelId) {
        List positionAllYieldDTOList = getStrategyRate(modelId);
        Map stringObjectMap = new HashMap<>();
        List 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 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  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;
    }

    
    @Override
    public List getStrategyRate(Long modelId) {

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

        List newTargetIdList = positionModelShipmentPOList.stream().map(x->x.getTargetId()).collect(Collectors.toList());
        List deletedTargetIdList = targetIdList.stream().filter(x->!newTargetIdList.contains(x)).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(deletedTargetIdList)){
            List 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> openIndexCodeToTargetIdMap = positionModelTargetPOS.stream().collect(Collectors.groupingBy(PositionModelTargetPO::getOpeningPrice,Collectors.mapping(PositionModelTargetPO::getId,Collectors.toSet())));
        Set openIndexDataList = getIndexDataByIndexCode(openIndexCodeToTargetIdMap);
        if (CollectionUtils.isEmpty(openIndexDataList)) {
            throw new CommonException("101", positionModelPO.getModelName() + "开盘价无指标数据");
        }
        Map 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> closeIndexCodeToTargetIdMap = positionModelTargetPOS.stream().collect(Collectors.groupingBy(PositionModelTargetPO::getClosingPrice,Collectors.mapping(PositionModelTargetPO::getId,Collectors.toSet())));
        Set closeIndexDataList = getIndexDataByIndexCode(closeIndexCodeToTargetIdMap);
        if (CollectionUtils.isEmpty(closeIndexDataList)) {
            throw new CommonException("102", positionModelPO.getModelName() + "收盘价无指标数据");
        }
        Map 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 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 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 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;
    }

    
     void processUnderlyingYield(List strategyRateDTOList,Map targetIdToName,List positionAllYieldDTOList){
         Map> longListMap = strategyRateDTOList.stream().collect(Collectors.groupingBy(StrategyRateDTO::getTargetId));
         longListMap.forEach((k, v) -> {
             List 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());
         });
     }

    
     void processStraregicYield(Map closeStrategyRateMap, Map openStrategyRateMap,List positionAllYieldDTOList){
         List positionTargetYieldDTOList = new ArrayList<>();
         TreeMap strategyRateTreeMap = new TreeMap(closeStrategyRateMap);
         Set timeSet = strategyRateTreeMap.keySet();
         List 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());
     }

    
    void processFallback(Map closeStrategyRateMap, Map openStrategyRateMap,List positionAllYieldDTOList){
        TreeMap strategyRateTreeMap = new TreeMap(closeStrategyRateMap);
        Set timeSet = strategyRateTreeMap.keySet();
        List timeList = new ArrayList<>(timeSet);
        List retreatYieldList = new ArrayList<>();
        //策略回撤
        Double max = 0.0, maxWithdrawalRate = Double.MAX_VALUE;
        Iterator 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));

    }

    
    void processStrategicAnnualizadYield( Map closeStrategyRateMap, Map openStrategyRateMap,List 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)));
    }

    
    void processStrategicAnnualizadVolatility(Map closeStrategyRateMap, Map openStrategyRateMap,List positionAllYieldDTOList){
        Long maxDate = closeStrategyRateMap.keySet().stream().max(Comparator.comparing(Long::longValue)).get();
        TreeMap strategyRateTreeMap = new TreeMap(closeStrategyRateMap);
        Set timeSet = strategyRateTreeMap.keySet();
        List 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 retreatYieldList, List 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 getIndexDataByIndexCode(Map> map) {
        try {
            List indexCodeList = new ArrayList<>(map.keySet());
            Set positionIndexDataDTOList = new HashSet<>();
            IndexDataQueryRequest indexDataQueryRequest = new IndexDataQueryRequest();
            indexDataQueryRequest.setIndexCodes(indexCodeList);
            indexDataQueryRequest.setCurrentUserId(UserInfoProviderFilter.threadLocal.get().getId());
            List indexDataPoList = dataCataLogService.getIndexData(indexDataQueryRequest);
            indexDataPoList.forEach(x -> {
                Set 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 uploadReqList, Long modelId) {
        if(CollectionUtils.isEmpty(uploadReqList)){
            throw new CommonException("131","上传信息为空");
        }
        PositionModelPO positionModelPO = positionModelMapper.getPositionModel(modelId);
        List  existList = positionModelShipmentMapper.queryByModelId(modelId);
        List existModelIdTargerTimeStr = existList.stream().map(x->x.getModelId()+"_"+x.getTargetId()+"_"+x.getShipmentTime().getTime()).collect(Collectors.toList());
        Map existModelIdTargerTimeMap = existList.stream().collect(Collectors.toMap(x->x.getModelId()+"_"+x.getTargetId()+"_"+x.getShipmentTime().getTime(),x->x.getId()));
        List 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 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  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 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 exportTemplateHeader(Long modelId) {
        List headerList = new ArrayList<>();
        headerList.add("时间");
        List 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 headerList = new ArrayList<>();
        List> dataList = new ArrayList<>();
        headerList.add("时间");
        List positionAllYieldDTOList = getStrategyRate(modelId);
        List 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 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 dateList = underlyingList.stream().map(x -> x.getDates()).collect(Collectors.toList());
        String[] dateArray = dateList.get(0);
        List 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 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 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  positionModelTargetPOS = positionModelTargetMapper.findAllByModelId(shipmentSpaceByPageRequest.getModelId());
        if (CollectionUtils.isEmpty(positionModelTargetPOS)) {
            throw new CommonException("103", positionModelPO.getModelName() + "没有关联标的品种");
        }
        List targetIdList = positionModelTargetPOS.stream().map(x->x.getId()).collect(Collectors.toList());
        Map  targetIdToName = positionModelTargetPOS.stream().collect(Collectors.toMap(x->x.getId(),x->x.getTargetVariety()));
        PageMethod.startPage(shipmentSpaceByPageRequest.getPageNum(), shipmentSpaceByPageRequest.getPageSize());
        List shipmentSpaceByPageRsps = positionModelShipmentMapper.findShipmentSpaceByPage(shipmentSpaceByPageRequest.getModelId(),targetIdList);
        PageInfo responses = new PageInfo(shipmentSpaceByPageRsps);

        PageInfo shipmentSpaceByPageRspPageInfo = new PageInfo<>();
        BeanUtils.copyProperties(responses, shipmentSpaceByPageRspPageInfo);
        List shipmentSpaceByPageRspList = new ArrayList<>();
        responses.getList().forEach(x -> {
            List 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");
    }
}

 

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号