testng和mock用例


   package com.newland.paas.paasservicenj.cd.service.impl;

import com.newland.paas.advice.request.RequestContext;
import com.newland.paas.advice.request.SessionInfo;
import com.newland.paas.common.util.dataset.ftp.JschSftpClient;
import com.newland.paas.paasdatamodulenj.cd.dao.CdLogTaskAutotestMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdLogTaskMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdLogTaskSqlMapper;
import com.newland.paas.paasdatamodulenj.cd.model.CdLogTask;
import com.newland.paas.paasdatamodulenj.cd.model.CdLogTaskAutotest;
import com.newland.paas.paasdatamodulenj.cd.model.CdLogTaskSql;
import com.newland.paas.paasservice.controllerapi.sysmgr.vo.SysTenantRespVo;
import com.newland.paas.paasservicenj.cd.controller.vo.CdLogTaskVo;
import com.newland.paas.paasservicenj.cd.controller.vo.LogTaskSqlStatusVo;
import com.newland.paas.paasservicenj.cd.enums.CdTaskLogSqlStatusEnum;
import com.newland.paas.sbcommon.common.ApplicationException;
import com.newland.paas.sbcommon.properties.MicroservicesProperties;
import com.newland.paas.sbcommon.utils.RestTemplateUtils;
import com.newland.paas.sbcommon.vo.BasicResponseContentVo;
import com.newland.paas.taskflow.core.enums.TaskStatusEnum;
import mockit.Expectations;
import mockit.Injectable;
import mockit.Mock;
import mockit.MockUp;
import mockit.Tested;
import org.springframework.core.ParameterizedTypeReference;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;


public class TaskLoggerServiceImplTest {
// 装饰器来声明某个类可被注入实例化
    @Injectable
    private CdLogTaskSqlMapper cdLogTaskSqlMapper;
    // 装饰器来声明某个类可被注入实例化
    @Injectable
    private CdLogTaskAutotestMapper cdLogTaskAutotestMapper;
    // 装饰器来声明某个类可被注入实例化
    @Injectable
    private CdLogTaskMapper cdLogTaskMapper;
    // 装饰器来声明某个类可被注入实例化
    @Injectable
    private MicroservicesProperties microservicesProperties;
    // 装饰器来声明某个类可被注入实例化
    @Injectable
    private RestTemplateUtils restTemplateUtils;
//调度的测试类
    @Tested
    TaskLoggerServiceImpl taskLoggerService;

	//执行前实例化
    @BeforeClass
    public void set() {
    	//RequestContext给这个类赋值
        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setTenantId(100220L);
        sessionInfo.setUserId(100100L);
        RequestContext.set(sessionInfo);
        //JschSftpClient这个类mock值
        new MockUp() {
            @Mock
            public void reConnect() throws IOException {
            }

            @Mock
            public InputStream getInputStream(String file) throws IOException {
                InputStream inputStream = new InputStream() {
                    @Override
                    public int read() throws IOException {
                        return -2;
                    }

                    byte[] buffer = new byte[1024];
					//对应调用的方法赋值
                    @Override
                    public int read(byte[] buffer) throws IOException {
                        return -2;
                    }
                };
                return inputStream;
            }

            @Mock
            public void release() throws IOException {

            }
        };

    }

    @Test
    public void getLogTaskStatus() {
        CdLogTask cdLogTask = new CdLogTask();
        cdLogTask.setLogId(111L);
        cdLogTask.setStatus(TaskStatusEnum.EXECUTE_SUCCESS.getCode());
        cdLogTask.setCreateDate(new Date());
        List autotestList = new ArrayList<>();
        CdLogTaskAutotest autotest = new CdLogTaskAutotest();
        autotest.setLogId(1L);
        autotest.setReportPath("/3333");
        autotest.setTaskLogId(11l);
        autotest.setCreateDate(new Date());
        autotestList.add(autotest);


        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        cdLogTask.setChangeDate(new Date());
        new Expectations() {
            {
            	//相当于mock对象
            	//这种情况下,Mockito提供了一系列的 any 方法,来表示任何的参数都行
                cdLogTaskMapper.lastExecuteLogByLogId(anyLong, anyLong);
                //调用上面的方法mock返回设置的值
                result = cdLogTask;
                cdLogTaskAutotestMapper.selectBySelective(withAny(autotest));
                result = autotestList;

            }

        };
        Long logId = 1L;
        CdLogTaskVo cdLogTaskVo = taskLoggerService.getLogTaskStatus(logId, 2l);
        Assert.assertNotNull(cdLogTaskVo);
    }

    @Test
    public void getLogTaskSqlFileQuery() {
        List cdLogTaskSqls = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            CdLogTaskSql cdLogTaskSql = new CdLogTaskSql();
            cdLogTaskSql.setTaskLogId(111l);
            cdLogTaskSql.setLogId((long) i);
            cdLogTaskSql.setActionId(1l);
            cdLogTaskSql.setFileName("1111");
            cdLogTaskSql.setFilePath("/ssss");
            cdLogTaskSql.setCreateDate(new Date());
            cdLogTaskSql.setStatus(CdTaskLogSqlStatusEnum.EXEC_SUC.getCode());
            cdLogTaskSqls.add(cdLogTaskSql);
        }
        CdLogTask cdLogTask = new CdLogTask();
        cdLogTask.setLogId(111L);
        cdLogTask.setStatus(TaskStatusEnum.EXECUTE_SUCCESS.getCode());
        cdLogTask.setCreateDate(new Date());
        new Expectations() {
            {
                cdLogTaskMapper.lastExecuteLogByLogId(anyLong, anyLong);
                result = cdLogTask;
                cdLogTaskSqlMapper.selectBySelective((CdLogTaskSql) any);
                result = cdLogTaskSqls;
            }

        };
        Long id = 1L;

        LogTaskSqlStatusVo logTaskSqlStatusVo = taskLoggerService.getLogTaskSqlFileQuery(id, 2l);
        Assert.assertNotNull(logTaskSqlStatusVo);

    }

    @Test
    public void downloadReport() throws ApplicationException, IOException {
        ParameterizedTypeReference> responseType =
                new ParameterizedTypeReference>() {
                };
        BasicResponseContentVo response = new BasicResponseContentVo<>();
        SysTenantRespVo sysTenantRespVo = new SysTenantRespVo();
        sysTenantRespVo.setTenantId(111l);
        sysTenantRespVo.setAstAddress("11111");
        response.setContent(sysTenantRespVo);

        new Expectations() {
            {
//这种情况下,Mockito提供了一系列的 any 方法,来表示任何的参数都行
                restTemplateUtils.getForEntity(
                        microservicesProperties.getSysmgr(), anyString, new HashMap<>(), responseType);
                result = response;
                new JschSftpClient(anyString, anyInt, anyString, anyString);
                result = new JschSftpClient(anyString, anyInt, anyString, anyString);

            }


        };
        //new HttpServletResponse() 实例化对象
        taskLoggerService.downloadReport(new HttpServletResponse() {
            @Override
            public String getCharacterEncoding() {
                return null;
            }

            @Override
            public String getContentType() {
                return null;
            }

            @Override
            public ServletOutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public PrintWriter getWriter() throws IOException {
                return null;
            }

            @Override
            public void setCharacterEncoding(String s) {

            }

            @Override
            public void setContentLength(int i) {

            }

            @Override
            public void setContentLengthLong(long l) {

            }

            @Override
            public void setContentType(String s) {

            }

            @Override
            public void setBufferSize(int i) {

            }

            @Override
            public int getBufferSize() {
                return 0;
            }

            @Override
            public void flushBuffer() throws IOException {

            }

            @Override
            public void resetBuffer() {

            }

            @Override
            public boolean isCommitted() {
                return false;
            }

            @Override
            public void reset() {

            }

            @Override
            public void setLocale(Locale locale) {

            }

            @Override
            public Locale getLocale() {
                return null;
            }

            @Override
            public void addCookie(Cookie cookie) {

            }

            @Override
            public boolean containsHeader(String s) {
                return false;
            }

            @Override
            public String encodeURL(String s) {
                return null;
            }

            @Override
            public String encodeRedirectURL(String s) {
                return null;
            }

            @Override
            public String encodeUrl(String s) {
                return null;
            }

            @Override
            public String encodeRedirectUrl(String s) {
                return null;
            }

            @Override
            public void sendError(int i, String s) throws IOException {

            }

            @Override
            public void sendError(int i) throws IOException {

            }

            @Override
            public void sendRedirect(String s) throws IOException {

            }

            @Override
            public void setDateHeader(String s, long l) {

            }

            @Override
            public void addDateHeader(String s, long l) {

            }

            @Override
            public void setHeader(String s, String s1) {

            }

            @Override
            public void addHeader(String s, String s1) {

            }

            @Override
            public void setIntHeader(String s, int i) {

            }

            @Override
            public void addIntHeader(String s, int i) {

            }

            @Override
            public void setStatus(int i) {

            }

            @Override
            public void setStatus(int i, String s) {

            }

            @Override
            public int getStatus() {
                return 0;
            }

            @Override
            public String getHeader(String s) {
                return null;
            }

            @Override
            public Collection getHeaders(String s) {
                return null;
            }

            @Override
            public Collection getHeaderNames() {
                return null;
            }
        }, "1111");
    }

}

package com.newland.paas.paasservicenj.cd.service.impl;

import com.newland.paas.advice.request.RequestContext;
import com.newland.paas.common.util.dataset.ftp.JschSftpClient;
import com.newland.paas.log.Log;
import com.newland.paas.log.LogFactory;
import com.newland.paas.log.LogProperty;
import com.newland.paas.paasdatamodulenj.cd.dao.CdLogTaskAutotestMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdLogTaskMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdLogTaskSqlMapper;
import com.newland.paas.paasdatamodulenj.cd.model.CdLogTask;
import com.newland.paas.paasdatamodulenj.cd.model.CdLogTaskAutotest;
import com.newland.paas.paasdatamodulenj.cd.model.CdLogTaskSql;
import com.newland.paas.paasservice.controllerapi.sysmgr.vo.SysTenantRespVo;
import com.newland.paas.paasservicenj.cd.constant.CdConstant;
import com.newland.paas.paasservicenj.cd.controller.vo.CdLogTaskVo;
import com.newland.paas.paasservicenj.cd.controller.vo.LogTaskSqlStatusCountVo;
import com.newland.paas.paasservicenj.cd.controller.vo.LogTaskSqlStatusVo;
import com.newland.paas.paasservicenj.cd.controller.vo.LogTaskSqlVo;
import com.newland.paas.paasservicenj.cd.enums.CdTaskLogSqlStatusEnum;
import com.newland.paas.paasservicenj.cd.service.TaskLoggerService;
import com.newland.paas.sbcommon.common.ApplicationException;
import com.newland.paas.sbcommon.properties.MicroservicesProperties;
import com.newland.paas.sbcommon.utils.RestTemplateUtils;
import com.newland.paas.sbcommon.vo.BasicResponseContentVo;
import com.newland.paas.sbcommon.vo.PaasError;
import com.newland.paas.taskflow.core.enums.TaskStatusEnum;
import org.mortbay.util.ajax.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 任务日志管理
 *
 * @author
 * @since 2020/5/26
 */
@Service
public class TaskLoggerServiceImpl implements TaskLoggerService {
    private static final Log LOG = LogFactory.getLogger(TaskLoggerServiceImpl.class);

    @Autowired
    private CdLogTaskSqlMapper cdLogTaskSqlMapper;
    @Autowired
    private CdLogTaskAutotestMapper cdLogTaskAutotestMapper;
    @Autowired
    private CdLogTaskMapper cdLogTaskMapper;
    @Autowired
    private MicroservicesProperties microservicesProperties;
    @Autowired
    private RestTemplateUtils restTemplateUtils;
    @Override
    public CdLogTaskVo getLogTaskStatus(Long logId, Long planTaskId) {
        CdLogTask cdLogTask = cdLogTaskMapper.lastExecuteLogByLogId(logId, planTaskId);
        if (cdLogTask == null) {
            return null;
        }
        CdLogTaskVo cdLogTaskVo = new CdLogTaskVo();
        BeanUtils.copyProperties(cdLogTask, cdLogTaskVo);
        if (TaskStatusEnum.EXECUTING.getCode().equals(cdLogTask.getStatus())) {
            long time = (long) Math.floor((System.currentTimeMillis() - cdLogTaskVo.getCreateDate().getTime()) / 1000f);
            cdLogTaskVo.setDurationTime(time);

        } else if (cdLogTaskVo.getChangeDate() != null) {
            long time = (long) Math.floor((cdLogTaskVo.getChangeDate().getTime() - cdLogTaskVo.getCreateDate().getTime()) / 1000f);
            cdLogTaskVo.setDurationTime(time);
        } else {
            cdLogTaskVo.setDurationTime(0L);
        }
        if (TaskStatusEnum.EXECUTE_SUCCESS.getCode().equals(cdLogTask.getStatus())) {
            CdLogTaskAutotest autotest = new CdLogTaskAutotest();
            autotest.setTaskLogId(logId);
            List autotestList = cdLogTaskAutotestMapper.selectBySelective(autotest);
            if (!CollectionUtils.isEmpty(autotestList)) {
                cdLogTaskVo.setReport(autotestList.get(0).getReportPath());
            }
        }
        return cdLogTaskVo;
    }

    @Override
    public LogTaskSqlStatusVo getLogTaskSqlFileQuery(Long tasklogIdParam, Long planTaskId) {
        CdLogTask cdLogTask = cdLogTaskMapper.lastExecuteLogByLogId(tasklogIdParam, planTaskId);
        if (cdLogTask == null) {
            LOG.info(LogProperty.LOGTYPE_DETAIL, "sql执行文件根据任务日志id:" + tasklogIdParam + "计划任务id" + planTaskId + "查询任务日志当前最早信息成功为空");
            return null;
        }
        CdLogTaskSql cdLogTaskSql = new CdLogTaskSql();
        Long tasklogId = cdLogTask.getLogId();
        cdLogTaskSql.setTaskLogId(tasklogId);
        List cdLogTaskSqlList = cdLogTaskSqlMapper.selectBySelective(cdLogTaskSql);
        if (CollectionUtils.isEmpty(cdLogTaskSqlList)) {
            LOG.info(LogProperty.LOGTYPE_DETAIL, "sql执行文件根据任务id:" + tasklogId + "查询信息为空");
            return null;
        }
        LOG.info(LogProperty.LOGTYPE_DETAIL, "sql执行文件根据任务id:" + tasklogId + "查询信息" + JSON.toString(cdLogTaskSqlList));
        LogTaskSqlStatusVo logTaskSqlStatusVo = new LogTaskSqlStatusVo();
        //遍历信息组装个个目录分组信息
        List taskSqlVos = new ArrayList<>();

        for (CdLogTaskSql logTaskSql : cdLogTaskSqlList) {
            LogTaskSqlVo logTaskSqlVo = new LogTaskSqlVo();
            BeanUtils.copyProperties(logTaskSql, logTaskSqlVo);
            taskSqlVos.add(logTaskSqlVo);
        }
        logTaskSqlStatusVo.setLogTaskSqlVoList(taskSqlVos);
        //按状态分组计算状态数量
        Map> groupByStatus = taskSqlVos.stream().collect(Collectors.groupingBy(LogTaskSqlVo::getStatus));
        List logTaskSqlStatus = new ArrayList<>();
        Long total = 0L;
        Long complete = 0L;


        for (Map.Entry> entryStatus : groupByStatus.entrySet()) {
            LogTaskSqlStatusCountVo logTaskSqlStatusCountVo = new LogTaskSqlStatusCountVo();
            logTaskSqlStatusCountVo.setStatus(entryStatus.getKey());
            logTaskSqlStatusCountVo.setCount((long) entryStatus.getValue().size());
            //计算总数和完成数量
            total += entryStatus.getValue().size();
            if (Objects.equals(CdTaskLogSqlStatusEnum.EXEC_FAIL.getCode(), entryStatus.getKey()) || Objects.equals(CdTaskLogSqlStatusEnum.EXEC_SUC.getCode(), entryStatus.getKey())) {
                complete += entryStatus.getValue().size();
            }
            logTaskSqlStatus.add(logTaskSqlStatusCountVo);
        }

        //排序状态顺序
        //获取总数
        sortStatus(logTaskSqlStatusVo, logTaskSqlStatus, total, complete);
        return logTaskSqlStatusVo;
    }

    /**
     * @param logTaskSqlStatusVo
     * @param logTaskSqlStatus
     * @param total
     * @param complete
     */
    public void sortStatus(LogTaskSqlStatusVo logTaskSqlStatusVo, List logTaskSqlStatus, Long total, Long complete) {
        Map mapStatus = new LinkedHashMap<>();
        mapStatus.put(CdTaskLogSqlStatusEnum.COUNT.getCode(), total == null ? Long.valueOf(0) : total);
        mapStatus.put(CdTaskLogSqlStatusEnum.COMPLETED.getCode(), complete == null ? Long.valueOf(0) : complete);
        Map success = mapStatus(logTaskSqlStatus, CdTaskLogSqlStatusEnum.EXEC_SUC.getCode());
        Long successCount = success.get(CdTaskLogSqlStatusEnum.EXEC_SUC.getCode());
        mapStatus.put(CdTaskLogSqlStatusEnum.EXEC_SUC.getCode(), successCount == null ? Long.valueOf(0) : successCount);
        Map fail = mapStatus(logTaskSqlStatus, CdTaskLogSqlStatusEnum.EXEC_FAIL.getCode());
        Long failCount = fail.get(CdTaskLogSqlStatusEnum.EXEC_FAIL.getCode());
        mapStatus.put(CdTaskLogSqlStatusEnum.EXEC_FAIL.getCode(), failCount == null ? Long.valueOf(0) : failCount);
        Map waitForExecute = mapStatus(logTaskSqlStatus, CdTaskLogSqlStatusEnum.WAIT_EXEC.getCode());
        Long waitForExecuteCount = waitForExecute.get(CdTaskLogSqlStatusEnum.WAIT_EXEC.getCode());
        if (waitForExecuteCount != null)
            mapStatus.put(CdTaskLogSqlStatusEnum.WAIT_EXEC.getCode(), waitForExecuteCount);

        Map execute = mapStatus(logTaskSqlStatus, CdTaskLogSqlStatusEnum.EXECING.getCode());
        Long executeExecuteCount = execute.get(CdTaskLogSqlStatusEnum.EXECING.getCode());
        if (executeExecuteCount != null)
            mapStatus.put(CdTaskLogSqlStatusEnum.EXECING.getCode(), executeExecuteCount);

        Map rollBackFail = mapStatus(logTaskSqlStatus, CdTaskLogSqlStatusEnum.ROLLBACK_FAIL.getCode());

        Long rollBackFailCount = rollBackFail.get(CdTaskLogSqlStatusEnum.ROLLBACK_FAIL.getCode());
        if (rollBackFailCount != null)
            mapStatus.put(CdTaskLogSqlStatusEnum.ROLLBACK_FAIL.getCode(), rollBackFailCount);

        Map rollBackSuc = mapStatus(logTaskSqlStatus, CdTaskLogSqlStatusEnum.ROLLBACK_SUC.getCode());

        Long rollBackSucCount = rollBackSuc.get(CdTaskLogSqlStatusEnum.ROLLBACK_SUC.getCode());
        if (rollBackSucCount != null)
            mapStatus.put(CdTaskLogSqlStatusEnum.ROLLBACK_SUC.getCode(), rollBackSucCount);
        Map rollBackBegin = mapStatus(logTaskSqlStatus, CdTaskLogSqlStatusEnum.ROLLBACK_BEGIN.getCode());

        Long rollBackBeginCount = rollBackBegin.get(CdTaskLogSqlStatusEnum.ROLLBACK_BEGIN.getCode());
        if (rollBackBeginCount != null)
            mapStatus.put(CdTaskLogSqlStatusEnum.ROLLBACK_BEGIN.getCode(), rollBackBeginCount);

        Map rollBackRuning = mapStatus(logTaskSqlStatus, CdTaskLogSqlStatusEnum.ROLLBACK_RUING.getCode());

        Long rollBackRuningCount = rollBackRuning.get(CdTaskLogSqlStatusEnum.ROLLBACK_RUING.getCode());
        if (rollBackRuningCount != null)
            mapStatus.put(CdTaskLogSqlStatusEnum.ROLLBACK_RUING.getCode(), rollBackRuningCount);

        logTaskSqlStatusVo.setLogTaskSqlStatus(mapStatus);
    }

    /**
     * 遍历集合获取状态
     *
     * @param logTaskSqlStatus
     * @param code
     * @return
     */
    public Map mapStatus(List logTaskSqlStatus, String code) {
        return logTaskSqlStatus.stream().filter(v -> v.getStatus().equals(code)).collect(Collectors.toMap(LogTaskSqlStatusCountVo::getStatus,
                LogTaskSqlStatusCountVo::getCount));
    }

    @Override
    public void downloadReport(HttpServletResponse response, String filePath) throws ApplicationException {
        InputStream inputStream = null;
        String[] names = filePath.split(CdConstant.DPM_STRING_DIAGONAL);
        try {
            inputStream = getInputStream(filePath);
        } catch (Exception e) {
            throw new ApplicationException(new PaasError("downloadReport", "下载测试报告失败-读取流失败"), e);
        }
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" + names[names.length - 1]);

        byte[] buffer = new byte[CdConstant.BYTE_LENGTH];
        //FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;

        OutputStream os = null; //输出流
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(inputStream);
            int i = bis.read(buffer);
            while (i != CdConstant.DISABLED_NUM) {
                os.write(buffer);
                i = bis.read(buffer);
            }

        } catch (Exception e) {
            LOG.error(LogProperty.LOGTYPE_DETAIL, e.getMessage(), e, e.getMessage());
            throw new ApplicationException(new PaasError("downloadReport", "下载测试报告失败"), e);
        }
        try {
            bis.close();
            inputStream.close();
        } catch (IOException e) {
            LOG.error(LogProperty.LOGTYPE_DETAIL, e.getMessage(), e, e.getMessage());
            throw new ApplicationException(new PaasError("downloadReport", "下载测试报告失败-关闭流失败"), e);
        }
    }

    private InputStream getInputStream(String filePath) throws Exception {
        JschSftpClient ftpClient = null;
        InputStream inputStream = null;
        try {
            Long tenantId =RequestContext.getTenantId();
            ParameterizedTypeReference> responseType =
                    new ParameterizedTypeReference>() {
                    };
            BasicResponseContentVo response = restTemplateUtils
                    .getForEntity(microservicesProperties.getSysmgr(), "/v1/tenantMgr/" + tenantId,
                            new HashMap<>(), responseType);
            SysTenantRespVo sysTenantRespVo = response.getContent();
            String[] astAddressSplit = sysTenantRespVo.getAstAddress().split(CdConstant.COLON );
            String astSftpIp = astAddressSplit[0];
            int astSftpPort = 22;
            String astSftpUser = sysTenantRespVo.getAstUsername();
            String astSftpPassword = sysTenantRespVo.getAstPassword();
            ftpClient = new JschSftpClient(astSftpIp, astSftpPort, astSftpUser, astSftpPassword);
            ftpClient.reConnect();
            inputStream = ftpClient.getInputStream(filePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            inputStream = new ByteArrayInputStream(baos.toByteArray());
            LOG.info(MessageFormat.format("download file [{0}]", filePath), new String[0]);
        } catch (Exception var13) {
            LOG.error(LogProperty.LOGTYPE_DETAIL, var13.getMessage(), var13, var13.getMessage());
            throw new ApplicationException(new PaasError("TaskLoggerServiceImpl.getInputStream", "stfp错误"), var13);
        } finally {
            try {
                if (null != ftpClient) {
                    ftpClient.release();
                }
            } catch (IOException var12) {
                LOG.error(LogProperty.LOGTYPE_DETAIL, var12.getMessage(), var12, var12.getMessage());
                throw new ApplicationException(new PaasError("TaskLoggerServiceImpl.getInputStream", "stfp关闭错误"), var12);
            }

        }
        return inputStream;
    }

}

package com.newland.paas.paasservicenj.cd.taskflow.task;

import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanPipelineMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanReleaseFileMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanReleaseMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanTaskMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanTaskPropertiesMapper;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlan;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanPipeline;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanRelease;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanReleaseFile;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanTask;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanTaskProperties;
import com.newland.paas.paasservice.controllerapi.cd.vo.TransportResponseVo;
import com.newland.paas.paasservice.controllerapi.sysmgr.vo.SysTenantOutputVo;
import com.newland.paas.paasservicenj.cd.taskflow.model.BossFlowSwitchResponseContentVo;
import com.newland.paas.paasservicenj.cd.taskflow.model.CdContextKey;
import com.newland.paas.paasservicenj.cd.taskflow.model.FlowSwitchDTO;
import com.newland.paas.sbcommon.common.SystemException;
import com.newland.paas.sbcommon.properties.MicroservicesItemProperties;
import com.newland.paas.sbcommon.properties.MicroservicesProperties;
import com.newland.paas.sbcommon.utils.ExtRestTemplateUtils;
import com.newland.paas.sbcommon.utils.RestTemplateUtils;
import com.newland.paas.sbcommon.utils.SpringContextUtil;
import com.newland.paas.sbcommon.vo.BasicResponseContentVo;
import com.newland.paas.sbcommon.vo.PaasError;
import com.newland.paas.taskflow.core.exception.TaskInterruptedException;
import com.newland.paas.taskflow.core.logger.ITaskLogger;
import com.newland.paas.taskflow.core.model.TaskContextWrapper;
import com.newland.paas.taskflow.core.model.TaskFlowContextWrapper;
import mockit.Deencapsulation;
import mockit.Expectations;
import mockit.Injectable;
import mockit.Mock;
import mockit.MockUp;
import org.springframework.core.ParameterizedTypeReference;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CdShakeHandsTaskTest {


    @Injectable
    private CdPlanTaskPropertiesMapper cdPlanTaskPropertiesMapper;
    @Injectable
    private ITaskLogger taskLogger;
    @Injectable
    private ExtRestTemplateUtils extRestTemplateUtils;
    @Injectable
    private CdPlanMapper cdPlanMapper;
    @Injectable
    private CdPlanReleaseMapper cdPlanReleaseMapper;
    @Injectable
    private CdPlanPipelineMapper cdPlanPipelineMapper;
    @Injectable
    private MicroservicesProperties microservicesProperties;
    @Injectable
    private RestTemplateUtils restTemplateUtils;
    @Injectable
    private CdPlanReleaseFileMapper cdPlanReleaseFileMapper;

    @Injectable
    private TaskFlowContextWrapper taskFlowContextWrapper;

    @Injectable
    private TaskContextWrapper taskContextWrapper;

    @Injectable
    private String CD_PLAN_RELEASE_FILE_ISSAVE;
    @Injectable
    private CdPlanTaskPropertiesAnalyze taskPropertiesAnalyze;
    @Injectable
    SpringContextUtil springContextUtil;
    @Injectable
    CdPlanTaskMapper cdPlanTaskMapper;

    @Test
    public void stop() {
        List properties = new ArrayList<>();
        properties.add(new CdPlanTaskProperties());
        new MockUp() {
            @Mock
            public  T getBean(Class requiredType) throws IllegalAccessException, InstantiationException {
                if (requiredType.isInstance(cdPlanTaskPropertiesMapper))
                    return (T) cdPlanTaskPropertiesMapper;
                if (requiredType.isInstance(taskLogger))
                    return (T) taskLogger;
                if (requiredType.isInstance(extRestTemplateUtils))
                    return (T) extRestTemplateUtils;
                if (requiredType.isInstance(restTemplateUtils))
                    return (T) restTemplateUtils;
                if (requiredType.isInstance(cdPlanMapper))
                    return (T) cdPlanMapper;
                if (requiredType.isInstance(cdPlanReleaseMapper))
                    return (T) cdPlanReleaseMapper;
                if (requiredType.isInstance(cdPlanPipelineMapper))
                    return (T) cdPlanPipelineMapper;
                if (requiredType.isInstance(microservicesProperties))
                    return (T) microservicesProperties;
                if (requiredType.isInstance(cdPlanReleaseFileMapper))
                    return (T) cdPlanReleaseFileMapper;
                if (requiredType.isInstance(cdPlanTaskMapper))
                    return (T) cdPlanTaskMapper;

                return null;
            }

            ;

            @Mock
            String getVaue(String key) {
                return "true";
            }

            ;
        };
        CdShakeHandsTask flowSwitchTask = new CdShakeHandsTask();
        Map context = new HashMap<>();
        flowSwitchTask.stop(context);

    }


    private void setUp() {
        new MockUp() {
            @Mock
            public  T getBean(Class requiredType) throws IllegalAccessException, InstantiationException {
                if (requiredType.isInstance(cdPlanTaskPropertiesMapper))
                    return (T) cdPlanTaskPropertiesMapper;
                if (requiredType.isInstance(taskLogger))
                    return (T) taskLogger;
                if (requiredType.isInstance(extRestTemplateUtils))
                    return (T) extRestTemplateUtils;
                if (requiredType.isInstance(cdPlanMapper))
                    return (T) cdPlanMapper;
                if (requiredType.isInstance(cdPlanReleaseMapper))
                    return (T) cdPlanReleaseMapper;
                if (requiredType.isInstance(cdPlanPipelineMapper))
                    return (T) cdPlanPipelineMapper;
                if (requiredType.isInstance(microservicesProperties))
                    return (T) microservicesProperties;
                if (requiredType.isInstance(cdPlanReleaseFileMapper))
                    return (T) cdPlanReleaseFileMapper;
                if (requiredType.isInstance(restTemplateUtils))
                    return (T) restTemplateUtils;
                if (requiredType.isInstance(taskPropertiesAnalyze))
                    return (T) taskPropertiesAnalyze;
                if (requiredType.isInstance(CD_PLAN_RELEASE_FILE_ISSAVE))
                    return (T) CD_PLAN_RELEASE_FILE_ISSAVE;
                if (requiredType.isInstance(cdPlanTaskMapper))
                    return (T) cdPlanTaskMapper;
                return null;
            }

            ;

            @Mock
            String getVaue(String key) {
                return "true";
            }

            ;
        };
        new MockUp() {
            @Mock
            Map getTaskContext(String taskId) {
                Map value = new HashMap<>();
                value.put("logId", 1000L);
                value.put("", 1);
                return value;
            }

            @Mock
            Object get(String param) {
                if (CdContextKey.AST_SFTP_RELEASE_PATH.equals(param))
                    return "/home/2222/";
                return null;
            }
        };
        new MockUp() {
            @Mock
            public Long getId() {
                return 1000L;
            }
        };

        new MockUp() {
            @Mock
            public  T getValue(String key, Class clazz) {
                if (clazz.isInstance(Long.valueOf(1000L)))
                    return (T) Long.valueOf(1000L);
                if (clazz.isInstance(new String()))
                    return (T) new String("taskId");
                return null;
            }
        };
    }


    @Test
    public void testPropertiesIsNull() {
        setUp();
        cdPlanTaskPropertiesMapper = new MockUp() {
            @Mock
            List selectBySelectiveWithBLOBs(CdPlanTaskProperties record) {
                return null;
            }
        }.getMockInstance();
        cdPlanReleaseFileMapper = new MockUp() {
            @Mock
            public CdPlanReleaseFile selectByPlanReleaseId(Long planReleaseId) {
                CdPlanReleaseFile cdPlanReleaseFile = new CdPlanReleaseFile();
                cdPlanReleaseFile.setFileSize(111L);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setTenantId(111L);
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setCreateorId(111L);
                return cdPlanReleaseFile;
            }

            @Mock
            public void insert(CdPlanReleaseFile cdPlanReleaseFile) {

            }
        }.getMockInstance();

        cdPlanPipelineMapper = new MockUp() {
            @Mock
            public CdPlanPipeline selectByPrimaryKey(Long taskFlowId) {
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setCreateDate(new Date());
                cdPlanPipeline.setPlanReleaseId(111L);
                cdPlanPipeline.setTenantId(111L);
                cdPlanPipeline.setChangeDate(new Date());
                cdPlanPipeline.setPlanPipelineId(111l);
                return cdPlanPipeline;
            }
        }.getMockInstance();

        cdPlanReleaseMapper = new MockUp() {
            @Mock
            public CdPlanRelease selectByPrimaryKey(Long taskFlowId) {
                CdPlanRelease cdPlanReleaseFile = new CdPlanRelease();
                cdPlanReleaseFile.setPlanReleaseId(111l);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setReleaseCode("111");
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setReleaseStatus("11");
                return cdPlanReleaseFile;
            }
        }.getMockInstance();
        cdPlanMapper = new MockUp() {
            @Mock
            public CdPlan selectByPrimaryKey(Long taskFlowId) {
                CdPlan cdPlan = new CdPlan();
                cdPlan.setPlanId(111l);
                cdPlan.setCreateDate(new Date());
                cdPlan.setTenanatId(111l);
                cdPlan.setPlanName("111");
                cdPlan.setChangeDate(new Date());
                cdPlan.setPlanVersion("1111");
                return cdPlan;
            }
        }.getMockInstance();
        microservicesProperties = new MockUp() {
            @Mock
            public MicroservicesItemProperties getSysmgr() {
                MicroservicesItemProperties sysmgr = new MicroservicesItemProperties();
                sysmgr.setContentPath("xx.xxx.xx.x");
                sysmgr.setServiceId("serviceName");
                return sysmgr;
            }
        }.getMockInstance();

        restTemplateUtils = new MockUp() {
            @Mock
            public Object postForEntity(MicroservicesItemProperties microservicesItemProperties, String interfaceUrl,
                                        Object params, ParameterizedTypeReference responseType) {
                BasicResponseContentVo> basicResponseContentVo = new BasicResponseContentVo<>();
                List list = new ArrayList<>();
                SysTenantOutputVo sysTenantOutputVo = new SysTenantOutputVo();
                sysTenantOutputVo.setTenantCode("1111");
                sysTenantOutputVo.setId(1l);
                list.add(sysTenantOutputVo);
                basicResponseContentVo.setContent(list);
                return basicResponseContentVo;
            }
        }.getMockInstance();

        CdShakeHandsTask flowSwitchTask = new CdShakeHandsTask();
        Map context = new HashMap<>();
        try {
            flowSwitchTask.execute(context);
        } catch (TaskInterruptedException e) {
            Assert.assertEquals(e.getLocalizedMessage(), "Cd握手任务[1000],缺失配置");

        }

    }


    @Test
    public void testURlConfigError() {
        setUp();
        cdPlanTaskPropertiesMapper = new MockUp() {
            @Mock
            public List selectBySelectiveWithBLOBs(CdPlanTaskProperties record) {
                List planTaskProperties = new ArrayList<>();
                CdPlanTaskProperties properties = new CdPlanTaskProperties();
                properties.setPropKey("CDShakeHandsTaskTargetStatus");
                properties.setPropValue("3,5");
                planTaskProperties.add(properties);
                return planTaskProperties;
            }

            ;

        }.getMockInstance();
        cdPlanReleaseFileMapper = new MockUp() {
            @Mock
            public CdPlanReleaseFile selectByPlanReleaseId(Long planReleaseId) {
                CdPlanReleaseFile cdPlanReleaseFile = new CdPlanReleaseFile();
                cdPlanReleaseFile.setFileSize(111L);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setTenantId(111L);
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setCreateorId(111L);
                return cdPlanReleaseFile;
            }

            @Mock
            public void insert(CdPlanReleaseFile cdPlanReleaseFile) {

            }
        }.getMockInstance();

        cdPlanPipelineMapper = new MockUp() {
            @Mock
            public CdPlanPipeline selectByPrimaryKey(Long taskFlowId) {
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setCreateDate(new Date());
                cdPlanPipeline.setPlanReleaseId(111L);
                cdPlanPipeline.setTenantId(111L);
                cdPlanPipeline.setChangeDate(new Date());
                cdPlanPipeline.setPlanPipelineId(111l);
                return cdPlanPipeline;
            }
        }.getMockInstance();

        cdPlanReleaseMapper = new MockUp() {
            @Mock
            public CdPlanRelease selectByPrimaryKey(Long taskFlowId) {
                CdPlanRelease cdPlanReleaseFile = new CdPlanRelease();
                cdPlanReleaseFile.setPlanReleaseId(111l);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setReleaseCode("111");
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setReleaseStatus("11");
                return cdPlanReleaseFile;
            }
        }.getMockInstance();
        cdPlanMapper = new MockUp() {
            @Mock
            public CdPlan selectByPrimaryKey(Long taskFlowId) {
                CdPlan cdPlan = new CdPlan();
                cdPlan.setPlanId(111l);
                cdPlan.setCreateDate(new Date());
                cdPlan.setTenanatId(111l);
                cdPlan.setPlanName("111");
                cdPlan.setChangeDate(new Date());
                cdPlan.setPlanVersion("1111");
                return cdPlan;
            }
        }.getMockInstance();
        restTemplateUtils = new MockUp() {
            @Mock
            public Object postForEntity(MicroservicesItemProperties microservicesItemProperties, String interfaceUrl,
                                        Object params, ParameterizedTypeReference responseType) {
                BasicResponseContentVo> basicResponseContentVo = new BasicResponseContentVo<>();
                List list = new ArrayList<>();
                SysTenantOutputVo sysTenantOutputVo = new SysTenantOutputVo();
                sysTenantOutputVo.setTenantCode("1111");
                sysTenantOutputVo.setId(1l);
                list.add(sysTenantOutputVo);
                basicResponseContentVo.setContent(list);
                return basicResponseContentVo;
            }
        }.getMockInstance();
        CdShakeHandsTask cdShakeHandsTask = new CdShakeHandsTask();
        Map context = new HashMap<>();
        try {
            cdShakeHandsTask.execute(context);
        } catch (TaskInterruptedException e) {
            Assert.assertEquals(e.getMessage(), "任务[null]异常:配置key=[cdPorterProddownloadPreProdFileUrl] 未进行配置");

        }
    }


    @Test
    public void testRetryNumConfigError() {
        setUp();
        cdPlanTaskPropertiesMapper = new MockUp() {
            @Mock
            public List selectBySelectiveWithBLOBs(CdPlanTaskProperties record) {
                List planTaskProperties = new ArrayList<>();
                CdPlanTaskProperties properties = new CdPlanTaskProperties();
                properties.setPropKey("cdPo" +
                        "rterIsUploadUrl");
                properties.setPropValue("http://10.1.8.20:32080/v1/prod/isUpload/");

                CdPlanTaskProperties urlProp = new CdPlanTaskProperties();
                urlProp.setPropKey("cdPorterProddownloadPreProdFileUrl");
                urlProp.setPropValue("http://10.1.8.20:32080/v1/prod/downloadPreProdFile");

                CdPlanTaskProperties retryNumberProp = new CdPlanTaskProperties();
                retryNumberProp.setPropKey("cdShakeHandsTaskRetryNumber");
                retryNumberProp.setPropValue("2");


                CdPlanTaskProperties retryIntervalProp = new CdPlanTaskProperties();
                retryIntervalProp.setPropKey("cdShakeHandsTaskRetryInterval");
                retryIntervalProp.setPropValue("2");


                planTaskProperties.add(properties);
                planTaskProperties.add(urlProp);
                planTaskProperties.add(retryIntervalProp);
                planTaskProperties.add(retryNumberProp);
                return planTaskProperties;
            }
        }.getMockInstance();
        cdPlanReleaseFileMapper = new MockUp() {
            @Mock
            public CdPlanReleaseFile selectByPlanReleaseId(Long planReleaseId) {
                CdPlanReleaseFile cdPlanReleaseFile = new CdPlanReleaseFile();
                cdPlanReleaseFile.setFileSize(111L);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setTenantId(111L);
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setCreateorId(111L);
                return cdPlanReleaseFile;
            }

            @Mock
            public void insert(CdPlanReleaseFile cdPlanReleaseFile) {

            }
        }.getMockInstance();

        cdPlanPipelineMapper = new MockUp() {
            @Mock
            public CdPlanPipeline selectByPrimaryKey(Long taskFlowId) {
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setCreateDate(new Date());
                cdPlanPipeline.setPlanReleaseId(111L);
                cdPlanPipeline.setTenantId(111L);
                cdPlanPipeline.setChangeDate(new Date());
                cdPlanPipeline.setPlanPipelineId(111l);
                return cdPlanPipeline;
            }
        }.getMockInstance();

        cdPlanReleaseMapper = new MockUp() {
            @Mock
            public CdPlanRelease selectByPrimaryKey(Long taskFlowId) {
                CdPlanRelease cdPlanReleaseFile = new CdPlanRelease();
                cdPlanReleaseFile.setPlanReleaseId(111l);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setReleaseCode("111");
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setReleaseStatus("11");
                return cdPlanReleaseFile;
            }
        }.getMockInstance();
        cdPlanMapper = new MockUp() {
            @Mock
            public CdPlan selectByPrimaryKey(Long taskFlowId) {
                CdPlan cdPlan = new CdPlan();
                cdPlan.setPlanId(111l);
                cdPlan.setCreateDate(new Date());
                cdPlan.setTenanatId(111l);
                cdPlan.setPlanName("111");
                cdPlan.setChangeDate(new Date());
                cdPlan.setPlanVersion("1111");
                return cdPlan;
            }
        }.getMockInstance();
        cdPlanTaskMapper = new MockUp() {
            @Mock
            public List selectBySelective(CdPlanTask taskQuery) {
                List ptList = new ArrayList<>();
                CdPlanTask cdPlanTask = new CdPlanTask();
                cdPlanTask.setPlanPipelineId(111l);
                cdPlanTask.setPlanTaskId(111l);
                cdPlanTask.setPlanTaskGroupId(111l);
                cdPlanTask.setPipelineId(111l);
                cdPlanTask.setTaskGroupId(111l);
                cdPlanTask.setTaskCode("111");
                cdPlanTask.setChangeDate(new Date());
                cdPlanTask.setChangeDate(new Date());
                ptList.add(cdPlanTask);
                return ptList;
            }
        }.getMockInstance();


        extRestTemplateUtils = new MockUp() {
            @Mock
            public Object postForExtEntity(String uri, String token,
                                           Object params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/downloadPreProdFile")) {
                    BasicResponseContentVo basicResponseContentVo = new BasicResponseContentVo<>();
                    TransportResponseVo transportResponseVo = new TransportResponseVo();
                    transportResponseVo.setCode("success");
                    transportResponseVo.setUploadCode("uploadCode");
                    basicResponseContentVo.setContent(transportResponseVo);
                    return basicResponseContentVo;
                }
                return null;
            }

            @Mock
            public Object getForExtEntity(String uri, String token,
                                          Map params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/isUpload")) {
                    PaasError REQUEST_ERROR = new PaasError("12201001", "请求错误!");

                    throw new SystemException(REQUEST_ERROR);
                }
                return null;

            }
        }.getMockInstance();
        microservicesProperties = new MockUp() {
            @Mock
            public MicroservicesItemProperties getSysmgr() {
                MicroservicesItemProperties sysmgr = new MicroservicesItemProperties();
                sysmgr.setContentPath("xx.xxx.xx.x");
                sysmgr.setServiceId("serviceName");
                return sysmgr;
            }
        }.getMockInstance();

        restTemplateUtils = new MockUp() {
            @Mock
            public Object postForEntity(MicroservicesItemProperties microservicesItemProperties, String interfaceUrl,
                                        Object params, ParameterizedTypeReference responseType) {
                BasicResponseContentVo> basicResponseContentVo = new BasicResponseContentVo<>();
                List list = new ArrayList<>();
                SysTenantOutputVo sysTenantOutputVo = new SysTenantOutputVo();
                sysTenantOutputVo.setTenantCode("1111");
                sysTenantOutputVo.setId(1l);
                list.add(sysTenantOutputVo);
                basicResponseContentVo.setContent(list);
                return basicResponseContentVo;
            }
        }.getMockInstance();


        CdShakeHandsTask cdShakeHandsTask = new CdShakeHandsTask();
        Map context = new HashMap<>();
        try {
            cdShakeHandsTask.execute(context);
        } catch (TaskInterruptedException e) {
            Assert.assertEquals(e.getMessage(), "Cd握手任务[1000]已经完成[2]重试,任务执行失败");
        }
    }

    @Test
    public void testRetryIntervalConfigError() {
        setUp();
        cdPlanTaskPropertiesMapper = new MockUp() {
            @Mock
            public List selectBySelectiveWithBLOBs(CdPlanTaskProperties record) {
                List planTaskProperties = new ArrayList<>();
                CdPlanTaskProperties properties = new CdPlanTaskProperties();
                properties.setPropKey("cdPorterIsUploadUrl");
                properties.setPropValue("http://10.1.8.20:32080/v1/prod/isUpload/");
                properties.setPlanTaskId(111L);
                CdPlanTaskProperties urlProp = new CdPlanTaskProperties();
                urlProp.setPropKey("cdPorterProddownloadPreProdFileUrl");
                urlProp.setPropValue("http://10.1.8.20:32080/v1/prod/downloadPreProdFile");
                urlProp.setPlanTaskId(111L);
                CdPlanTaskProperties retryNumberProp = new CdPlanTaskProperties();
                retryNumberProp.setPropKey("cdShakeHandsTaskRetryNumber");
                retryNumberProp.setPropValue("2");
                retryNumberProp.setPlanTaskId(111L);

                CdPlanTaskProperties retryIntervalProp = new CdPlanTaskProperties();
                retryIntervalProp.setPropKey("cdShakeHandsTaskRetryInterval");
                retryIntervalProp.setPropValue("2eee");
                retryIntervalProp.setPlanTaskId(111L);


                planTaskProperties.add(properties);
                planTaskProperties.add(urlProp);
                planTaskProperties.add(retryIntervalProp);
                planTaskProperties.add(retryNumberProp);
                return planTaskProperties;
            }

            @Mock
            public List getPlanTaskProperties(Long planTaskId) {
                List list = new ArrayList<>();
                CdPlanTaskProperties cdPlanTaskProperties = new CdPlanTaskProperties();
                cdPlanTaskProperties.setPlanTaskId(111l);
                cdPlanTaskProperties.setTaskId(111l);
                cdPlanTaskProperties.setPlanTaskPropertiesId(111L);
                cdPlanTaskProperties.setChangeDate(new Date());
                cdPlanTaskProperties.setCreateDate(new Date());
                cdPlanTaskProperties.setTenantId(111l);
                cdPlanTaskProperties.setPropValue("111");

                list.add(cdPlanTaskProperties);
                return list;
            }
        }.getMockInstance();
        cdPlanReleaseFileMapper = new MockUp() {
            @Mock
            public CdPlanReleaseFile selectByPlanReleaseId(Long planReleaseId) {
                CdPlanReleaseFile cdPlanReleaseFile = new CdPlanReleaseFile();
                cdPlanReleaseFile.setFileSize(111L);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setTenantId(111L);
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setCreateorId(111L);
                return cdPlanReleaseFile;
            }

            @Mock
            public void insert(CdPlanReleaseFile cdPlanReleaseFile) {

            }
        }.getMockInstance();

        cdPlanPipelineMapper = new MockUp() {
            @Mock
            public CdPlanPipeline selectByPrimaryKey(Long taskFlowId) {
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setCreateDate(new Date());
                cdPlanPipeline.setPlanReleaseId(111L);
                cdPlanPipeline.setTenantId(111L);
                cdPlanPipeline.setChangeDate(new Date());
                cdPlanPipeline.setPlanPipelineId(111l);
                return cdPlanPipeline;
            }
        }.getMockInstance();

        cdPlanReleaseMapper = new MockUp() {
            @Mock
            public CdPlanRelease selectByPrimaryKey(Long taskFlowId) {
                CdPlanRelease cdPlanReleaseFile = new CdPlanRelease();
                cdPlanReleaseFile.setPlanReleaseId(111l);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setReleaseCode("111");
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setReleaseStatus("11");
                return cdPlanReleaseFile;
            }
        }.getMockInstance();
        cdPlanMapper = new MockUp() {
            @Mock
            public CdPlan selectByPrimaryKey(Long taskFlowId) {
                CdPlan cdPlan = new CdPlan();
                cdPlan.setPlanId(111l);
                cdPlan.setCreateDate(new Date());
                cdPlan.setTenanatId(111l);
                cdPlan.setPlanName("111");
                cdPlan.setChangeDate(new Date());
                cdPlan.setPlanVersion("1111");
                return cdPlan;
            }
        }.getMockInstance();
        extRestTemplateUtils = new MockUp() {
            @Mock
            public Object postForExtEntity(String uri, String token,
                                           Object params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/downloadPreProdFile")) {
                    BasicResponseContentVo basicResponseContentVo = new BasicResponseContentVo<>();
                    TransportResponseVo transportResponseVo = new TransportResponseVo();
                    transportResponseVo.setCode("success");
                    transportResponseVo.setUploadCode("uploadCode");
                    basicResponseContentVo.setContent(transportResponseVo);
                    return basicResponseContentVo;
                }
                return null;
            }

        }.getMockInstance();
        microservicesProperties = new MockUp() {
            @Mock
            public MicroservicesItemProperties getSysmgr() {
                MicroservicesItemProperties sysmgr = new MicroservicesItemProperties();
                sysmgr.setContentPath("xx.xxx.xx.x");
                sysmgr.setServiceId("serviceName");
                return sysmgr;
            }
        }.getMockInstance();

        restTemplateUtils = new MockUp() {
            @Mock
            public Object postForEntity(MicroservicesItemProperties microservicesItemProperties, String interfaceUrl,
                                        Object params, ParameterizedTypeReference responseType) {
                BasicResponseContentVo> basicResponseContentVo = new BasicResponseContentVo<>();
                List list = new ArrayList<>();
                SysTenantOutputVo sysTenantOutputVo = new SysTenantOutputVo();
                sysTenantOutputVo.setTenantCode("1111");
                sysTenantOutputVo.setId(1l);
                list.add(sysTenantOutputVo);
                basicResponseContentVo.setContent(list);
                return basicResponseContentVo;
            }
        }.getMockInstance();


        CdShakeHandsTask cdShakeHandsTask = new CdShakeHandsTask();
        Map context = new HashMap<>();
        try {
            cdShakeHandsTask.execute(context);
        } catch (TaskInterruptedException e) {
            Assert.assertEquals(e.getMessage(), "任务[111]异常:配置key=[cdShakeHandsTaskRetryInterval] value=[2eee], value必须为数字");

        }
    }

    @Test
    public void testSuccess() {
        setUp();
        cdPlanTaskPropertiesMapper = new MockUp() {
            @Mock
            public List selectBySelectiveWithBLOBs(CdPlanTaskProperties record) {
                List planTaskProperties = new ArrayList<>();
                CdPlanTaskProperties properties = new CdPlanTaskProperties();
                properties.setPropKey("cdPorterIsUploadUrl");
                properties.setPropValue("http://10.1.8.20:32080/v1/prod/isUpload/");

                CdPlanTaskProperties urlProp = new CdPlanTaskProperties();
                urlProp.setPropKey("cdPorterProddownloadPreProdFileUrl");
                urlProp.setPropValue("http://10.1.8.20:32080/v1/prod/downloadPreProdFile");

                CdPlanTaskProperties retryNumberProp = new CdPlanTaskProperties();
                retryNumberProp.setPropKey("cdShakeHandsTaskRetryNumber");
                retryNumberProp.setPropValue("2");


                CdPlanTaskProperties retryIntervalProp = new CdPlanTaskProperties();
                retryIntervalProp.setPropKey("cdShakeHandsTaskRetryInterval");
                retryIntervalProp.setPropValue("2");


                planTaskProperties.add(properties);
                planTaskProperties.add(urlProp);
                planTaskProperties.add(retryIntervalProp);
                planTaskProperties.add(retryNumberProp);
                return planTaskProperties;
            }

            @Mock
            int updateByPrimaryKeyWithBLOBs(CdPlanTaskProperties record) {
                return 1;
            }

            @Mock
            public List getPlanTaskProperties(Long planTaskId) {
                List list = new ArrayList<>();
                CdPlanTaskProperties cdPlanTaskProperties = new CdPlanTaskProperties();
                cdPlanTaskProperties.setPlanTaskId(111l);
                cdPlanTaskProperties.setTaskId(111l);
                cdPlanTaskProperties.setPlanTaskPropertiesId(111L);
                cdPlanTaskProperties.setChangeDate(new Date());
                cdPlanTaskProperties.setCreateDate(new Date());
                cdPlanTaskProperties.setTenantId(111l);
                //cdPlanTaskProperties.setPropValue("111");
                cdPlanTaskProperties.setDefaultValue("111");
                list.add(cdPlanTaskProperties);
                return list;
            }
        }.getMockInstance();
        cdPlanReleaseFileMapper = new MockUp() {
            @Mock
            public CdPlanReleaseFile selectByPlanReleaseId(Long planReleaseId) {
                CdPlanReleaseFile cdPlanReleaseFile = new CdPlanReleaseFile();
                cdPlanReleaseFile.setFileSize(111L);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setTenantId(111L);
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setCreateorId(111L);
                return cdPlanReleaseFile;
            }

            @Mock
            public void insert(CdPlanReleaseFile cdPlanReleaseFile) {

            }
        }.getMockInstance();

        cdPlanPipelineMapper = new MockUp() {
            @Mock
            public CdPlanPipeline selectByPrimaryKey(Long taskFlowId) {
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setCreateDate(new Date());
                cdPlanPipeline.setPlanReleaseId(111L);
                cdPlanPipeline.setTenantId(111L);
                cdPlanPipeline.setChangeDate(new Date());
                cdPlanPipeline.setPlanPipelineId(111l);
                return cdPlanPipeline;
            }

            @Mock
            public List selectBySelective(CdPlanPipeline record) {
                List list = new ArrayList<>();
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPlanPipelineId(111l);
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setPlanReleaseId(111l);
                cdPlanPipeline.setCreatorId(111l);
                cdPlanPipeline.setTenantId(111l);
                list.add(cdPlanPipeline);
                return list;
            }
        }.getMockInstance();

        cdPlanReleaseMapper = new MockUp() {
            @Mock
            public CdPlanRelease selectByPrimaryKey(Long taskFlowId) {
                CdPlanRelease cdPlanReleaseFile = new CdPlanRelease();
                cdPlanReleaseFile.setPlanReleaseId(111l);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setReleaseCode("111");
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setReleaseStatus("11");
                return cdPlanReleaseFile;
            }
        }.getMockInstance();
        cdPlanMapper = new MockUp() {
            @Mock
            public CdPlan selectByPrimaryKey(Long taskFlowId) {
                CdPlan cdPlan = new CdPlan();
                cdPlan.setPlanId(111l);
                cdPlan.setCreateDate(new Date());
                cdPlan.setTenanatId(111l);
                cdPlan.setPlanName("111");
                cdPlan.setChangeDate(new Date());
                cdPlan.setPlanVersion("1111");
                return cdPlan;
            }
        }.getMockInstance();
        cdPlanTaskMapper = new MockUp() {
            @Mock
            public List selectBySelective(CdPlanTask taskQuery) {
                List ptList = new ArrayList<>();
                CdPlanTask cdPlanTask = new CdPlanTask();
                cdPlanTask.setPlanPipelineId(111l);
                cdPlanTask.setPlanTaskId(111l);
                cdPlanTask.setPlanTaskGroupId(111l);
                cdPlanTask.setPipelineId(111l);
                cdPlanTask.setTaskGroupId(111l);
                cdPlanTask.setTaskCode("111");
                cdPlanTask.setChangeDate(new Date());
                cdPlanTask.setChangeDate(new Date());
                ptList.add(cdPlanTask);
                return ptList;
            }
        }.getMockInstance();

        extRestTemplateUtils = new MockUp() {
            @Mock
            public Object postForExtEntity(String uri, String token,
                                           Object params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/downloadPreProdFile")) {
                    BasicResponseContentVo basicResponseContentVo = new BasicResponseContentVo<>();
                    TransportResponseVo transportResponseVo = new TransportResponseVo();
                    transportResponseVo.setCode("success");
                    transportResponseVo.setUploadCode("uploadCode");
                    basicResponseContentVo.setContent(transportResponseVo);
                    return basicResponseContentVo;
                }
                return null;
            }

            @Mock
            public Object getForExtEntity(String uri, String token,
                                          Map params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/isUpload")) {
                    BasicResponseContentVo basicResponseContentVo = new BasicResponseContentVo<>();
                    TransportResponseVo transportResponseVo = new TransportResponseVo();
                    transportResponseVo.setCode("uploaded");
                    transportResponseVo.setUploadCode("uploadCode");
                    transportResponseVo.setFileSize(11f);
                    basicResponseContentVo.setContent(transportResponseVo);
                    return basicResponseContentVo;
                }
                return null;
            }
        }.getMockInstance();
        microservicesProperties = new MockUp() {
            @Mock
            public MicroservicesItemProperties getSysmgr() {
                MicroservicesItemProperties sysmgr = new MicroservicesItemProperties();
                sysmgr.setContentPath("xx.xxx.xx.x");
                sysmgr.setServiceId("serviceName");
                return sysmgr;
            }
        }.getMockInstance();

        restTemplateUtils = new MockUp() {
            @Mock
            public Object postForEntity(MicroservicesItemProperties microservicesItemProperties, String interfaceUrl,
                                        Object params, ParameterizedTypeReference responseType) {
                BasicResponseContentVo> basicResponseContentVo = new BasicResponseContentVo<>();
                List list = new ArrayList<>();
                SysTenantOutputVo sysTenantOutputVo = new SysTenantOutputVo();
                sysTenantOutputVo.setTenantCode("1111");
                sysTenantOutputVo.setId(1l);
                list.add(sysTenantOutputVo);
                basicResponseContentVo.setContent(list);
                return basicResponseContentVo;
            }
        }.getMockInstance();


        CdShakeHandsTask cdShakeHandsTask = new CdShakeHandsTask();
        Map context = new HashMap<>();
        cdShakeHandsTask.execute(context);
    }

    @Test
    public void testHttp505() {
        setUp();
        cdPlanTaskPropertiesMapper = new MockUp() {
            @Mock
            public List selectBySelectiveWithBLOBs(CdPlanTaskProperties record) {
                List planTaskProperties = new ArrayList<>();
                CdPlanTaskProperties properties = new CdPlanTaskProperties();
                properties.setPropKey("cdPorterIsUploadUrl");
                properties.setPropValue("http://10.1.8.20:32080/v1/prod/isUpload/");

                CdPlanTaskProperties urlProp = new CdPlanTaskProperties();
                urlProp.setPropKey("cdPorterProddownloadPreProdFileUrl");
                urlProp.setPropValue("http://10.1.8.20:32080/v1/prod/downloadPreProdFile");

                CdPlanTaskProperties retryNumberProp = new CdPlanTaskProperties();
                retryNumberProp.setPropKey("cdShakeHandsTaskRetryNumber");
                retryNumberProp.setPropValue("2");


                CdPlanTaskProperties retryIntervalProp = new CdPlanTaskProperties();
                retryIntervalProp.setPropKey("cdShakeHandsTaskRetryInterval");
                retryIntervalProp.setPropValue("2");


                planTaskProperties.add(properties);
                planTaskProperties.add(urlProp);
                planTaskProperties.add(retryIntervalProp);
                planTaskProperties.add(retryNumberProp);
                return planTaskProperties;
            }
        }.getMockInstance();
        cdPlanReleaseFileMapper = new MockUp() {
            @Mock
            public CdPlanReleaseFile selectByPlanReleaseId(Long planReleaseId) {
                CdPlanReleaseFile cdPlanReleaseFile = new CdPlanReleaseFile();
                cdPlanReleaseFile.setFileSize(111L);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setTenantId(111L);
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setCreateorId(111L);
                return cdPlanReleaseFile;
            }

            @Mock
            public void insert(CdPlanReleaseFile cdPlanReleaseFile) {

            }
        }.getMockInstance();

        cdPlanPipelineMapper = new MockUp() {
            @Mock
            public CdPlanPipeline selectByPrimaryKey(Long taskFlowId) {
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setCreateDate(new Date());
                cdPlanPipeline.setPlanReleaseId(111L);
                cdPlanPipeline.setTenantId(111L);
                cdPlanPipeline.setChangeDate(new Date());
                cdPlanPipeline.setPlanPipelineId(111l);
                return cdPlanPipeline;
            }

            @Mock
            public List selectBySelective(CdPlanPipeline record) {
                List list = new ArrayList<>();
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPlanPipelineId(111l);
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setPlanReleaseId(111l);
                cdPlanPipeline.setCreatorId(111l);
                cdPlanPipeline.setTenantId(111l);
                list.add(cdPlanPipeline);
                return list;
            }
        }.getMockInstance();

        cdPlanReleaseMapper = new MockUp() {
            @Mock
            public CdPlanRelease selectByPrimaryKey(Long taskFlowId) {
                CdPlanRelease cdPlanReleaseFile = new CdPlanRelease();
                cdPlanReleaseFile.setPlanReleaseId(111l);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setReleaseCode("111");
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setReleaseStatus("11");
                return cdPlanReleaseFile;
            }
        }.getMockInstance();
        cdPlanMapper = new MockUp() {
            @Mock
            public CdPlan selectByPrimaryKey(Long taskFlowId) {
                CdPlan cdPlan = new CdPlan();
                cdPlan.setPlanId(111l);
                cdPlan.setCreateDate(new Date());
                cdPlan.setTenanatId(111l);
                cdPlan.setPlanName("111");
                cdPlan.setChangeDate(new Date());
                cdPlan.setPlanVersion("1111");
                return cdPlan;
            }
        }.getMockInstance();

        new MockUp() {
            @Mock
            private FlowSwitchDTO createHttpParams(Long taskLogId, List configProperties, String propKey) {
                FlowSwitchDTO dto = new FlowSwitchDTO();
                List statusArry = new ArrayList<>();
                statusArry.add(3);
                statusArry.add(5);
                dto.setAction_id(1000L);
                dto.setTarget_status(statusArry);
                return dto;
            }
        };

        extRestTemplateUtils = new MockUp() {
            @Mock
            public Object postForExtEntity(String uri, String token,
                                           Object params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/downloadPreProdFile")) {
                    BasicResponseContentVo basicResponseContentVo = new BasicResponseContentVo<>();
                    TransportResponseVo transportResponseVo = new TransportResponseVo();
                    transportResponseVo.setCode("success");
                    transportResponseVo.setUploadCode("uploadCode");
                    basicResponseContentVo.setContent(transportResponseVo);
                    return basicResponseContentVo;
                }
                return null;
            }

            @Mock
            public Object getForExtEntity(String uri, String token,
                                          Map params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/isUpload")) {
                    PaasError REQUEST_ERROR = new PaasError("12201002", "请求错误!");

                    throw new SystemException(REQUEST_ERROR);
                }
                return null;
            }
        }.getMockInstance();
        microservicesProperties = new MockUp() {
            @Mock
            public MicroservicesItemProperties getSysmgr() {
                MicroservicesItemProperties sysmgr = new MicroservicesItemProperties();
                sysmgr.setContentPath("xx.xxx.xx.x");
                sysmgr.setServiceId("serviceName");
                return sysmgr;
            }
        }.getMockInstance();

        restTemplateUtils = new MockUp() {
            @Mock
            public Object postForEntity(MicroservicesItemProperties microservicesItemProperties, String interfaceUrl,
                                        Object params, ParameterizedTypeReference responseType) {
                BasicResponseContentVo> basicResponseContentVo = new BasicResponseContentVo<>();
                List list = new ArrayList<>();
                SysTenantOutputVo sysTenantOutputVo = new SysTenantOutputVo();
                sysTenantOutputVo.setTenantCode("1111");
                sysTenantOutputVo.setId(1l);
                list.add(sysTenantOutputVo);
                basicResponseContentVo.setContent(list);
                return basicResponseContentVo;
            }
        }.getMockInstance();

        CdShakeHandsTask cdShakeHandsTask = new CdShakeHandsTask();
        Map context = new HashMap<>();
        try {
            cdShakeHandsTask.execute(context);
        } catch (TaskInterruptedException e) {
            Assert.assertEquals(e.getMessage(), "com.newland.paas.sbcommon.common.SystemException: 请求错误!");

        }
    }

    @Test
    public void testHttp404DefaultRetryNumber() {
        setUp();
        cdPlanTaskPropertiesMapper = new MockUp() {
            @Mock
            public List selectBySelectiveWithBLOBs(CdPlanTaskProperties record) {
                List planTaskProperties = new ArrayList<>();
                CdPlanTaskProperties properties = new CdPlanTaskProperties();
                properties.setPropKey("cdPo" +
                        "rterIsUploadUrl");
                properties.setPropValue("http://10.1.8.20:32080/v1/prod/isUpload/");

                CdPlanTaskProperties urlProp = new CdPlanTaskProperties();
                urlProp.setPropKey("cdPorterProddownloadPreProdFileUrl");
                urlProp.setPropValue("http://10.1.8.20:32080/v1/prod/downloadPreProdFile");

                CdPlanTaskProperties retryNumberProp = new CdPlanTaskProperties();
                retryNumberProp.setPropKey("cdShakeHandsTaskRetryNumber");
                retryNumberProp.setPropValue("2");


                CdPlanTaskProperties retryIntervalProp = new CdPlanTaskProperties();
                retryIntervalProp.setPropKey("cdShakeHandsTaskRetryInterval");
                retryIntervalProp.setPropValue("2");


                planTaskProperties.add(properties);
                planTaskProperties.add(urlProp);
          /*      planTaskProperties.add(retryIntervalProp);
                planTaskProperties.add(retryNumberProp);*/
                return planTaskProperties;
            }
        }.getMockInstance();
        cdPlanReleaseFileMapper = new MockUp() {
            @Mock
            public CdPlanReleaseFile selectByPlanReleaseId(Long planReleaseId) {
                CdPlanReleaseFile cdPlanReleaseFile = new CdPlanReleaseFile();
                cdPlanReleaseFile.setFileSize(111L);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setTenantId(111L);
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setCreateorId(111L);
                return cdPlanReleaseFile;
            }

            @Mock
            public void insert(CdPlanReleaseFile cdPlanReleaseFile) {

            }
        }.getMockInstance();

        cdPlanPipelineMapper = new MockUp() {
            @Mock
            public CdPlanPipeline selectByPrimaryKey(Long taskFlowId) {
                CdPlanPipeline cdPlanPipeline = new CdPlanPipeline();
                cdPlanPipeline.setPipelineCode("111");
                cdPlanPipeline.setCreateDate(new Date());
                cdPlanPipeline.setPlanReleaseId(111L);
                cdPlanPipeline.setTenantId(111L);
                cdPlanPipeline.setChangeDate(new Date());
                cdPlanPipeline.setPlanPipelineId(111l);
                return cdPlanPipeline;
            }
        }.getMockInstance();

        cdPlanReleaseMapper = new MockUp() {
            @Mock
            public CdPlanRelease selectByPrimaryKey(Long taskFlowId) {
                CdPlanRelease cdPlanReleaseFile = new CdPlanRelease();
                cdPlanReleaseFile.setPlanReleaseId(111l);
                cdPlanReleaseFile.setCreateDate(new Date());
                cdPlanReleaseFile.setPlanReleaseId(111L);
                cdPlanReleaseFile.setReleaseCode("111");
                cdPlanReleaseFile.setChangeDate(new Date());
                cdPlanReleaseFile.setReleaseStatus("11");
                return cdPlanReleaseFile;
            }
        }.getMockInstance();
        cdPlanMapper = new MockUp() {
            @Mock
            public CdPlan selectByPrimaryKey(Long taskFlowId) {
                CdPlan cdPlan = new CdPlan();
                cdPlan.setPlanId(111l);
                cdPlan.setCreateDate(new Date());
                cdPlan.setTenanatId(111l);
                cdPlan.setPlanName("111");
                cdPlan.setChangeDate(new Date());
                cdPlan.setPlanVersion("1111");
                return cdPlan;
            }
        }.getMockInstance();
        cdPlanTaskMapper = new MockUp() {
            @Mock
            public List selectBySelective(CdPlanTask taskQuery) {
                List ptList = new ArrayList<>();
                CdPlanTask cdPlanTask = new CdPlanTask();
                cdPlanTask.setPlanPipelineId(111l);
                cdPlanTask.setPlanTaskId(111l);
                cdPlanTask.setPlanTaskGroupId(111l);
                cdPlanTask.setPipelineId(111l);
                cdPlanTask.setTaskGroupId(111l);
                cdPlanTask.setTaskCode("111");
                cdPlanTask.setChangeDate(new Date());
                cdPlanTask.setChangeDate(new Date());
                ptList.add(cdPlanTask);
                return ptList;
            }
        }.getMockInstance();


        extRestTemplateUtils = new MockUp() {
            @Mock
            public Object postForExtEntity(String uri, String token,
                                           Object params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/downloadPreProdFile")) {
                    BasicResponseContentVo basicResponseContentVo = new BasicResponseContentVo<>();
                    TransportResponseVo transportResponseVo = new TransportResponseVo();
                    transportResponseVo.setCode("success");
                    transportResponseVo.setUploadCode("uploadCode");
                    basicResponseContentVo.setContent(transportResponseVo);
                    return basicResponseContentVo;
                }
                return null;
            }

            @Mock
            public Object getForExtEntity(String uri, String token,
                                          Map params, ParameterizedTypeReference responseType) {
                if (uri.contains("/v1/prod/isUpload")) {
                    PaasError REQUEST_ERROR = new PaasError("12201001", "请求错误!");

                    throw new SystemException(REQUEST_ERROR);
                }
                return null;

            }
        }.getMockInstance();
        microservicesProperties = new MockUp() {
            @Mock
            public MicroservicesItemProperties getSysmgr() {
                MicroservicesItemProperties sysmgr = new MicroservicesItemProperties();
                sysmgr.setContentPath("xx.xxx.xx.x");
                sysmgr.setServiceId("serviceName");
                return sysmgr;
            }
        }.getMockInstance();

        restTemplateUtils = new MockUp() {
            @Mock
            public Object postForEntity(MicroservicesItemProperties microservicesItemProperties, String interfaceUrl,
                                        Object params, ParameterizedTypeReference responseType) {
                BasicResponseContentVo> basicResponseContentVo = new BasicResponseContentVo<>();
                List list = new ArrayList<>();
                SysTenantOutputVo sysTenantOutputVo = new SysTenantOutputVo();
                sysTenantOutputVo.setTenantCode("1111");
                sysTenantOutputVo.setId(1l);
                list.add(sysTenantOutputVo);
                basicResponseContentVo.setContent(list);
                return basicResponseContentVo;
            }
        }.getMockInstance();


        CdShakeHandsTask cdShakeHandsTask = new CdShakeHandsTask();
        Map context = new HashMap<>();
        try {
            cdShakeHandsTask.execute(context);
        } catch (TaskInterruptedException e) {
            Assert.assertEquals(e.getMessage(), "Cd握手任务[1000]已经完成[0]重试,任务执行失败");
        }
    }
}


package com.newland.paas.paasservicenj.cd.taskflow.task;

import com.alibaba.fastjson.JSON;
import com.newland.paas.log.Log;
import com.newland.paas.log.LogFactory;
import com.newland.paas.log.LogProperty;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanPipelineMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanReleaseFileMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanReleaseMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanTaskMapper;
import com.newland.paas.paasdatamodulenj.cd.dao.CdPlanTaskPropertiesMapper;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlan;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanPipeline;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanRelease;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanReleaseFile;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanTask;
import com.newland.paas.paasdatamodulenj.cd.model.CdPlanTaskProperties;
import com.newland.paas.paasservice.controllerapi.cd.vo.TransportRequestVo;
import com.newland.paas.paasservice.controllerapi.cd.vo.TransportResponseVo;
import com.newland.paas.paasservice.controllerapi.sysmgr.vo.SysTenantOutputVo;
import com.newland.paas.paasservice.controllerapi.sysmgr.vo.SysTenantReqVo;
import com.newland.paas.paasservicenj.cd.errorcode.CdErrorCode;
import com.newland.paas.paasservicenj.cd.taskflow.model.CdContextKey;
import com.newland.paas.paasservicenj.cd.taskflow.util.BossSqlUtils;
import com.newland.paas.paasservicenj.cd.utils.ReleaseConfigUtil;
import com.newland.paas.sbcommon.common.ApplicationException;
import com.newland.paas.sbcommon.common.SystemException;
import com.newland.paas.sbcommon.properties.MicroservicesProperties;
import com.newland.paas.sbcommon.utils.ExtRestTemplateUtils;
import com.newland.paas.sbcommon.utils.RestTemplateUtils;
import com.newland.paas.sbcommon.utils.SpringContextUtil;
import com.newland.paas.sbcommon.vo.BasicRequestContentVo;
import com.newland.paas.sbcommon.vo.BasicResponseContentVo;
import com.newland.paas.taskflow.core.exception.TaskExecuteException;
import com.newland.paas.taskflow.core.exception.TaskInterruptedException;
import com.newland.paas.taskflow.core.exception.TaskRollbackException;
import com.newland.paas.taskflow.core.exception.TaskStopException;
import com.newland.paas.taskflow.core.logger.ITaskLogger;
import com.newland.paas.taskflow.core.model.ContextKey;
import com.newland.paas.taskflow.core.model.Task;
import com.newland.paas.taskflow.core.model.TaskContextWrapper;
import com.newland.paas.taskflow.core.model.TaskFlowContextWrapper;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;


public class CdShakeHandsTask extends Task {
    private static final Log LOG = LogFactory.getLogger(CdShakeHandsTask.class);


    //对应paas 通知接口url
    private static final  String DOWNLOAD_PREPROD_FILE_URL = "cdPorterProddownloadPreProdFileUrl";

    private static final  String FLOW_CD_PORTER_IS_UPLOAD_URL = "cdPorterIsUploadUrl";
    //接口调用异常重试次数
    private static final  String FLOW_SHAKE_HANDS_RETRY_NUMBER = "cdShakeHandsTaskRetryNumber";
    //接口异常重试时间间隔
    private static final  String FLOW_SHAKE_HANDS_RETRY_INTERVAL = "cdShakeHandsTaskRetryInterval";

    private static final  String CD_PLAN_RELEASE_FILE_ISSAVE = "cd.plan.release.file.isSave";
    //判断查询握手状态成功(验证生产包传输完成)
    private static final  String SUCCESS = "uploaded";

    private CdPlanMapper cdPlanMapper;

    private CdPlanReleaseMapper cdPlanReleaseMapper;

    private CdPlanPipelineMapper cdPlanPipelineMapper;


    private CdPlanTaskPropertiesMapper cdPlanTaskPropertiesMapper;

    private MicroservicesProperties microservicesProperties;

    private RestTemplateUtils restTemplateUtils;

    private CdPlanReleaseFileMapper cdPlanReleaseFileMapper;
    private CdPlanTaskMapper cdPlanTaskMapper;
    private ITaskLogger taskLogger;
    private ExtRestTemplateUtils extRestTemplateUtils;
    private String isSave = "false";
    private static String isProd = "true";
    private Boolean requiredToStop = false;
    private CdPlanTaskPropertiesAnalyze taskPropertiesAnalyze;

    private String taskLogFileId = "";

    public CdShakeHandsTask() {
        this.cdPlanMapper = SpringContextUtil.getBean(CdPlanMapper.class);
        this.cdPlanReleaseMapper = SpringContextUtil.getBean(CdPlanReleaseMapper.class);
        this.cdPlanPipelineMapper = SpringContextUtil.getBean(CdPlanPipelineMapper.class);
        this.microservicesProperties = SpringContextUtil.getBean(MicroservicesProperties.class);
        this.restTemplateUtils = SpringContextUtil.getBean(RestTemplateUtils.class);
        this.cdPlanReleaseFileMapper = SpringContextUtil.getBean(CdPlanReleaseFileMapper.class);
        this.cdPlanTaskMapper = SpringContextUtil.getBean(CdPlanTaskMapper.class);
        this.cdPlanTaskPropertiesMapper = SpringContextUtil.getBean(CdPlanTaskPropertiesMapper.class);
        this.extRestTemplateUtils = SpringContextUtil.getBean(ExtRestTemplateUtils.class);
        taskPropertiesAnalyze = new CdPlanTaskPropertiesAnalyze();
        this.isSave = SpringContextUtil.getVaue(CD_PLAN_RELEASE_FILE_ISSAVE);
        this.taskLogger = SpringContextUtil.getBean(ITaskLogger.class);

    }

    @Override
    public void execute(Map context) throws TaskExecuteException, TaskInterruptedException {
        try {
            process(context, DOWNLOAD_PREPROD_FILE_URL, FLOW_CD_PORTER_IS_UPLOAD_URL, FLOW_SHAKE_HANDS_RETRY_NUMBER, FLOW_SHAKE_HANDS_RETRY_INTERVAL);

        } catch (TaskInterruptedException e1) {
            taskLogger.log(taskLogFileId, String.format("[%s] Cd握手任务[%s],出错错误信息:%s", BossSqlUtils.getLogTime(), getId(), e1.getMessage()), false);
            throw e1;
        } catch (Exception e) {
            taskLogger.log(taskLogFileId, String.format("[%s] Cd握手任务[%s],出错错误信息:%s", BossSqlUtils.getLogTime(), getId(), e.getMessage()), false);
            throw new TaskInterruptedException(e);
        } finally {
            taskLogger.log(taskLogFileId, String.format("[%s] Cd握手任务[%s]----- END -----", BossSqlUtils.getLogTime(), getId()), true);
        }

    }

    @Override
    public void rollback(Map context) throws TaskRollbackException, TaskInterruptedException {
        try {
            TaskFlowContextWrapper taskFlowContextWrapper = new TaskFlowContextWrapper(context);
            Map taskContext = taskFlowContextWrapper.getTaskContext(this.getId().toString());
            TaskContextWrapper taskContextWrapper = new TaskContextWrapper(taskContext);
            String taskLogFileId = taskContextWrapper.getValue(ContextKey.TASK_LOG_FILE_ID, String.class);
            this.taskLogFileId = taskLogFileId;
            taskLogger.log(taskLogFileId, String.format("[%s]cd握手任务回滚[%s]----- BEGIN -----", BossSqlUtils.getLogTime(), this.getId()), false);
            //获取任务流id
            Long taskFlowId = (Long) taskFlowContextWrapper.get(ContextKey.TASK_FLOW_ID);
            // 获取流水线信息
            CdPlanPipeline cdPlanPipeline = cdPlanPipelineMapper.selectByPrimaryKey(taskFlowId);
            if (cdPlanPipeline == null) {
                throw new TaskInterruptedException(CdErrorCode.PLAN_PIPE_LINE_INFO_NOT_FOUND.getDescription());
            }
            cdPlanReleaseFileMapper.deleteByPrimaryKey(cdPlanPipeline.getPlanReleaseId());
        } catch (TaskInterruptedException e1) {
            taskLogger.log(taskLogFileId, String.format("[%s] Cd握手任务[%s],出错错误信息:%s", BossSqlUtils.getLogTime(), getId(), e1.getMessage()), false);
            throw e1;
        } catch (Exception e) {
            taskLogger.log(taskLogFileId, String.format("[%s] Cd握手任务[%s],出错错误信息:%s", BossSqlUtils.getLogTime(), getId(), e.getMessage()), false);
            throw new TaskInterruptedException(e);
        } finally {
            taskLogger.log(taskLogFileId, String.format("[%s] Cd握手任务[%s]----- END -----", BossSqlUtils.getLogTime(), getId()), true);
        }
    }


    /**
     * @param context
     * @param downloadPreProdFileUrlKey
     * @param isUploadUrlKey
     * @param retryNumberKey
     * @param retryIntervalKey
     * @throws ApplicationException
     */
    private void process(Map context, String downloadPreProdFileUrlKey, String isUploadUrlKey, String retryNumberKey, String retryIntervalKey) throws ApplicationException {
        TaskFlowContextWrapper taskFlowContextWrapper = new TaskFlowContextWrapper(context);
        Map taskContext = taskFlowContextWrapper.getTaskContext(this.getId().toString());
        TaskContextWrapper taskContextWrapper = new TaskContextWrapper(taskContext);
        String taskLogFileId = taskContextWrapper.getValue(ContextKey.TASK_LOG_FILE_ID, String.class);
        this.taskLogFileId = taskLogFileId;
        taskLogger.log(taskLogFileId, String.format("[%s]cd握手任务[%s]----- BEGIN -----", BossSqlUtils.getLogTime(), this.getId()), false);
        //获取任务流id
        Long taskFlowId = (Long) taskFlowContextWrapper.get(ContextKey.TASK_FLOW_ID);
        // 获取流水线信息
        CdPlanPipeline cdPlanPipeline = cdPlanPipelineMapper.selectByPrimaryKey(taskFlowId);
        if (cdPlanPipeline == null) {
            throw new TaskInterruptedException(CdErrorCode.PLAN_PIPE_LINE_INFO_NOT_FOUND.getDescription());
        }
        // 获取发布信息
        CdPlanRelease cdPlanRelease = cdPlanReleaseMapper.selectByPrimaryKey(cdPlanPipeline.getPlanReleaseId());
        if (cdPlanRelease == null) {
            throw new TaskInterruptedException(CdErrorCode.PLAN_RELEASE_INFO_NOT_FOUND.getDescription());
        }
        // 获取上线计划信息
        CdPlan cdPlan = cdPlanMapper.selectByPrimaryKey(cdPlanRelease.getPlanId());
        if (cdPlan == null) {
            throw new TaskInterruptedException(CdErrorCode.PLAN_INFO_NOT_FOUND.getDescription());
        }
        //本地发布包目录(绝对路径)
        String localRleasePath = (String) taskFlowContextWrapper.get(CdContextKey.LOCAL_RELEASE_PATH);
        // 获取租户信息
        Long tenantId = cdPlan.getTenanatId();
        SysTenantOutputVo sysTenantRespVo = getTenantInfo(tenantId);
        //计划版本
        String planVersion = cdPlan.getPlanVersion();
        //发布标识
        String releaseCode = cdPlanRelease.getReleaseCode();
        //计划发布ID
        Long planReleaseId = cdPlanRelease.getPlanReleaseId();
        //租户标识
        String tenantCode = sysTenantRespVo.getTenantCode();
        //资产仓库发布包目录(绝对路径)
        String dirPath = (String) taskFlowContextWrapper.get(CdContextKey.AST_SFTP_RELEASE_PATH);

        Long taskId = this.getId();
        CdPlanTaskProperties taskProperties = new CdPlanTaskProperties();
        taskProperties.setPlanTaskId(taskId);
        List configProperties = cdPlanTaskPropertiesMapper.selectBySelectiveWithBLOBs(taskProperties);
        //判断是否进行任务配置
        if (configProperties == null || configProperties.size() == 0) {
            throw new TaskInterruptedException(String.format("Cd握手任务[%s],缺失配置", taskId));
        }
        //根据配置创建请求参数
        String url = taskPropertiesAnalyze.getConfigByPropKey(configProperties, downloadPreProdFileUrlKey, true);
        //调用测试机接口通知下载
        String uploadCode = this.uploadCode(taskLogFileId, dirPath, planVersion, releaseCode, tenantCode, url, taskId);
        //根据配置创建请求参数
        String isUploadUrlKeyUrl = taskPropertiesAnalyze.getConfigByPropKey(configProperties, isUploadUrlKey, true);
        Integer retryNum = taskPropertiesAnalyze.getIntegerPropValue(configProperties, retryNumberKey);
        Long interval = taskPropertiesAnalyze.getLongPropValue(configProperties, retryIntervalKey);
        isUploadUrlKeyUrl = isUploadUrlKeyUrl + uploadCode;
        callBack(interval, retryNum, isUploadUrlKeyUrl, planReleaseId, tenantId, uploadCode, localRleasePath, cdPlanRelease);

    }

    /**
     * 轮询回调
     *
     * @param interval
     * @param retryNum
     * @param isUploadUrlKeyUrl
     * @param planReleaseId
     * @param tenantId
     * @param uploadCode
     * @param localRleasePath
     * @param cdPlanRelease
     */
    public void callBack(Long interval, Integer retryNum, String isUploadUrlKeyUrl, Long planReleaseId, Long tenantId, String uploadCode, String localRleasePath, CdPlanRelease cdPlanRelease) {
        int retryCount = 0;
        int loopCount = 0;
        while (true) {
            loopCount++;
            // 检查是否收到停止任务指令
            if (requiredToStop) {
                taskLogger.log(taskLogFileId, String.format("[%s]Cd握手任务被手动停止,[%s] ----- END -----", BossSqlUtils.getLogTime(), getId()), false);
                throw new TaskInterruptedException("任务被终止执行");
            }
            try {
                TransportResponseVo transportResponseVo1 = isUpload(taskLogFileId, loopCount, isUploadUrlKeyUrl, uploadCode);
                if (transportResponseVo1 == null) {
                    taskLogger.log(taskLogFileId, String.format("[%s]Cd握手任务第[%s]调用[%s]出错错误信息:返回为空", BossSqlUtils.getLogTime(), loopCount, isUploadUrlKeyUrl), false);
                    continue;
                }
                taskLogger(taskLogFileId, false, "[%s]Cd握手任务第[%s]次调用[%s]返回结果[%s]", BossSqlUtils.getLogTime(), loopCount, isUploadUrlKeyUrl, JSON.toJSON(transportResponseVo1));
                //如果boss成功返回信息结束重试
                if (SUCCESS.equals(transportResponseVo1.getCode())) {
                    if (isProd.equals(isSave)) {
                        //添加上线发布文件记录
                        CdPlanReleaseFile cdPlanReleaseFile1 = new CdPlanReleaseFile();
                        cdPlanReleaseFile1.setChangeDate(new Date());
                        cdPlanReleaseFile1.setFileName(transportResponseVo1.getFileName());
                        cdPlanReleaseFile1.setPlanReleaseId(planReleaseId);
                        cdPlanReleaseFile1.setTenantId(tenantId);
                        cdPlanReleaseFile1.setCreateDate(new Date());
                        float fileSize = transportResponseVo1.getFileSize();
                        cdPlanReleaseFile1.setFileSize((long) (fileSize * 1000));
                        cdPlanReleaseFileMapper.insertSelective(cdPlanReleaseFile1);
                    }
                    // 解析并渲染发布包配置
                    CdPlanPipeline pipelineQuery = new CdPlanPipeline();
                    pipelineQuery.setPlanReleaseId(cdPlanRelease.getPlanReleaseId());
                    List ppList = cdPlanPipelineMapper.selectBySelective(pipelineQuery);
                    for (CdPlanPipeline pp : ppList) {
                        parseAndRenderReleaseConfig(localRleasePath, pp);
                    }
                    break;
                }

            } catch (SystemException e) {
                retryCount++;
                httpException(taskLogFileId, isUploadUrlKeyUrl, retryCount, retryNum, e);
            }


            try {
                taskLogger.log(taskLogFileId, String.format("[%s]获取结果无效将进入[%s]秒休眠", BossSqlUtils.getLogTime(), interval), false);
                Thread.sleep(interval * 1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

        }
    }

    /**
     * 添加日志
     *
     * @param logEnd
     * @param msgContent
     * @param objects
     */
    private void taskLogger(String taskLogFileId, Boolean logEnd, String msgContent, Object... objects) {
        StringBuffer logMsg = new StringBuffer();
        if (objects != null) {
            logMsg.append(String.format(msgContent, objects));
            taskLogger.log(taskLogFileId, logMsg.toString(), logEnd);
            LOG.info(LogProperty.LOGTYPE_DETAIL, String.format(msgContent, objects));
        } else {
            logMsg.append(String.format(msgContent));
            taskLogger.log(taskLogFileId, logMsg.toString(), logEnd);
            LOG.info(LogProperty.LOGTYPE_DETAIL, String.format(msgContent));
        }


    }

    /**
     * @param url
     * @param retryCount
     * @param retryNum
     * @param e
     */
    private void httpException(String taskLogFileId, String url, int retryCount, int retryNum, SystemException e) {
        //判断是否500异常如是结束任务
        if ((e.getError().getCode().equals("12201002"))) {
            throw new TaskInterruptedException(e);
        }
        taskLogger(taskLogFileId, false, "第[%s]调用[%s]出错错误信息:%s", retryCount, url, e.getMessage());
        //如果重试重试超过配置重试次数结束重试
        if (retryCount >= retryNum) {
            throw new TaskInterruptedException(String.format("Cd握手任务[%s]已经完成[%s]重试,任务执行失败", getId(), retryNum));
        }

    }

    /**
     * 判断是否上传完成
     *
     * @param taskLogFileId
     * @param loopCount
     * @param isUploadUrlKeyUrl
     * @param uploadCode
     * @return
     */

    public TransportResponseVo isUpload(String taskLogFileId, int loopCount, String isUploadUrlKeyUrl, String uploadCode) {

        taskLogger.log(taskLogFileId, String.format("[%s]查询Cd握手状态第[%s]次向[%s]发送请求,参数[%s]", BossSqlUtils.getLogTime(), loopCount, isUploadUrlKeyUrl, uploadCode), false);
        LOG.info(LogProperty.LOGTYPE_DETAIL, ">>>>>>>>>>>> 发送查询Cd握手状态地址和参数:" + JSON.toJSONString(isUploadUrlKeyUrl));
        BasicResponseContentVo transportResponseContent = extRestTemplateUtils.getForExtEntity(isUploadUrlKeyUrl, null, null,
                new ParameterizedTypeReference>() {
                });
        return transportResponseContent.getContent();

    }

    /**
     * 获取上传标识码
     *
     * @param taskLogFileId
     * @param dirPath
     * @param planVersion
     * @param releaseCode
     * @param tenantCode
     * @param url
     * @param taskId
     * @return
     */
    public String uploadCode(String taskLogFileId, String dirPath, String planVersion, String releaseCode,
                             String tenantCode, String url, Long taskId) {

        //调用通知生产下载测试机下载包
        BasicRequestContentVo transportRequestVoBasicRequestContentVo = new BasicRequestContentVo<>();
        TransportRequestVo transportRequestVo = new TransportRequestVo();
        transportRequestVo.setDirPath(dirPath);
        transportRequestVo.setPlanVersion(planVersion);
        transportRequestVo.setReleaseCode(releaseCode);
        transportRequestVo.setTenantCode(tenantCode);
        transportRequestVoBasicRequestContentVo.setParams(transportRequestVo);
        LOG.info(LogProperty.LOGTYPE_DETAIL, ">>>>>>>>>>>> 发送cd通知握手接口参数:" + JSON.toJSONString(transportRequestVoBasicRequestContentVo));
        taskLogger.log(taskLogFileId, String.format("CI握手任务向[%s]发送请求,参数[%s]", url, JSON.toJSONString(transportRequestVoBasicRequestContentVo)), false);
        BasicResponseContentVo contentVo = extRestTemplateUtils.postForExtEntity(url, null, transportRequestVoBasicRequestContentVo,
                new ParameterizedTypeReference>() {
                });
        if (contentVo.getContent() == null) {
            LOG.error(LogProperty.LOGTYPE_DETAIL, null, null, ">>>>>>>>>>>> " + String.format("Cd握手任务通知握手接口[%s],缺失返回数据", taskId));
            throw new TaskInterruptedException(String.format("CI握手任务通知握手接口[%s],缺失返回数据", taskId));
        }
        taskLogger.log(taskLogFileId, String.format("CI握手任务调用[%s]返回结果[%s]", url, JSON.toJSONString(contentVo)), false);
        LOG.info(LogProperty.LOGTYPE_DETAIL, ">>>>>>>>>>>> 发送cd通知握手接口返回结果:" + JSON.toJSONString(transportRequestVoBasicRequestContentVo));

        TransportResponseVo transportResponseVo = contentVo.getContent();
        //获取上传标识码
        return transportResponseVo.getUploadCode();
    }

    /**
     * 解析配置文件渲染
     *
     * @param localRleasePath
     * @param cdPlanPipeline
     */
    private void parseAndRenderReleaseConfig(String localRleasePath, CdPlanPipeline cdPlanPipeline) {
        // 解析配置文件
        Map envConfig;
        Map> pipelineConfig;
        CdPlanTask taskQuery = new CdPlanTask();
        taskQuery.setPlanPipelineId(cdPlanPipeline.getPlanPipelineId());
        List ptList = cdPlanTaskMapper.selectBySelective(taskQuery);
        try {
            envConfig = ReleaseConfigUtil.parseEnvConfig(localRleasePath, cdPlanPipeline.getPipelineEnv());
            pipelineConfig = ReleaseConfigUtil.parsePipelineConfig(localRleasePath, cdPlanPipeline.getPipelineCode(), envConfig);
            // 渲染阶段.cfg文件
            ReleaseConfigUtil.renderPipelineConfig(localRleasePath, cdPlanPipeline.getPipelineCode(), envConfig);
            for (CdPlanTask cdPlanTask : ptList) {
                String taskDir = localRleasePath + "/" + cdPlanTask.getTaskCode();
                // 渲染app.yaml中的变量
                ReleaseConfigUtil.renderAppYaml(taskDir, envConfig);
            }
        } catch (Exception e) {
            throw new TaskInterruptedException(CdErrorCode.RELEASE_CONFIG_PARSE_ERROR.getDescription() + e.getMessage());
        }
        // 任务属性取值
        for (CdPlanTask cdPlanTask : ptList) {
            // 任务属性读取优先级: 属性已有值 > 上线包配置值 > 默认值
            // 如果以上均读取不到值,则报错
            List cdPlanTaskPropertiesList = cdPlanTaskPropertiesMapper.getPlanTaskProperties(cdPlanTask.getPlanTaskId());
            if (cdPlanTaskPropertiesList == null) {
                continue;
            }
            Map taskConfig = pipelineConfig.get(cdPlanTask.getTaskCode());
            for (CdPlanTaskProperties cdPlanTaskProperties : cdPlanTaskPropertiesList) {
                String value = null;
                if (!com.newland.paas.common.util.StringUtils.isBlank(cdPlanTaskProperties.getPropValue())) {
                    continue;
                } else if (taskConfig != null) {
                    value = taskConfig.get(cdPlanTaskProperties.getPropKey());
                } else if (!com.newland.paas.common.util.StringUtils.isBlank(cdPlanTaskProperties.getDefaultValue())) {
                    value = cdPlanTaskProperties.getDefaultValue();
                }
                if (com.newland.paas.common.util.StringUtils.isBlank(value)) {
                    CdErrorCode.RELEASE_CONFIG_MISSING.setMsgArguments("阶段[" + cdPlanPipeline.getPipelineCode() + "].环节[" + cdPlanTask.getTaskCode() + "]." + cdPlanTaskProperties.getPropKey());
                    throw new TaskInterruptedException(CdErrorCode.RELEASE_CONFIG_MISSING.getDescription() + CdErrorCode.RELEASE_CONFIG_MISSING.getSolution());
                }
                // 写入属性值
                cdPlanTaskProperties.setPropValue(value);
                cdPlanTaskPropertiesMapper.updateByPrimaryKeyWithBLOBs(cdPlanTaskProperties);
            }
        }
    }


    /**
     * 根据租户id获取租户信息
     *
     * @param tenantId
     * @return
     */
    public SysTenantOutputVo getTenantInfo(Long tenantId) {
        ParameterizedTypeReference>> responseType =
                new ParameterizedTypeReference>>() {
                };
        BasicRequestContentVo sysTenantReqVoBase = new BasicRequestContentVo<>();
        SysTenantReqVo sysTenantReqVo = new SysTenantReqVo();
        sysTenantReqVo.setTenantId(tenantId);
        sysTenantReqVoBase.setParams(sysTenantReqVo);
        BasicResponseContentVo> response = restTemplateUtils
                .postForEntity(microservicesProperties.getSysmgr(), "/v1/tenantMgr/getTenantInfo",
                        sysTenantReqVoBase, responseType);
        if (CollectionUtils.isEmpty(response.getContent())) {
            LOG.error(LogProperty.LOGTYPE_DETAIL, null, null, ">>>>>>>>>>>> " + String.format("调用租户id[%s]信息接口,返回数据数据为空", tenantId));
            throw new TaskInterruptedException(CdErrorCode.CD_TENANT_NULL.getDescription());
        }
        return response.getContent().get(0);
    }


    /**
     * @param context
     * @throws TaskStopException
     */
    @Override
    public void stop(Map context) throws TaskStopException {
        this.requiredToStop = true;
    }


}

你可能感兴趣的:(testng,java,spring)