com.xn.interfacetest.service.impl.TestCaseServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.xn.interfacetest.service.impl.TestCaseServiceImpl.java

Source

/*
 * Copyright (c) 2014-2015, Yunnex and/or its affiliates. All rights reserved. Use, Copy is subject to authorized license.
 */
package com.xn.interfacetest.service.impl;

import com.xn.common.base.CommonResult;
import com.xn.common.utils.*;
import com.xn.common.utils.FileUtil;
import com.xn.interfacetest.Enum.*;
import com.xn.interfacetest.api.*;
import com.xn.interfacetest.command.*;
import com.xn.interfacetest.dao.TestCaseMapper;
import com.xn.interfacetest.dto.*;
import com.xn.interfacetest.entity.RelationCaseDatabase;
import com.xn.interfacetest.entity.TestCase;
import com.xn.interfacetest.model.AssertKeyValueVo;
import com.xn.interfacetest.model.KeyValueStore;
import com.xn.interfacetest.response.Assert;
import com.xn.interfacetest.result.ReportResult;
import com.xn.interfacetest.singleton.InitThreadPool;
import com.xn.interfacetest.util.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.apache.poi.ss.usermodel.CellType.*;

/**
 * TestCase Service
 * 
 * @author Carol
 * @date 2017-02-14
 */
@Service
@Transactional
public class TestCaseServiceImpl implements TestCaseService {
    private static final Logger logger = LoggerFactory.getLogger(TestCaseServiceImpl.class);

    private static final String STRING_NAME = "java.lang.String";

    private static final String INTEGER_NAME = "java.lang.Integer";

    private static final String SHORT_NAME = "java.lang.Short";

    private static final String BYTE_NAME = "java.lang.Byte";

    private static final String LONG_NAME = "java.lang.Long";

    private static final String FLOAT_NAME = "java.lang.Float";

    private static final String DOUBLE_NAME = "java.lang.Double";

    private static final String CHARACTER_NAME = "java.lang.Character";

    private static final String BOOLEAN_NAME = "java.lang.Boolean";

    /**
     *  Dao
     */
    @Autowired
    private TestCaseMapper testCaseMapper;

    @Autowired
    private TestInterfaceService testInterfaceService;

    @Autowired
    private TestParamsService testParamsService;

    @Autowired
    private RelationCaseRedisService relationCaseRedisService;

    @Autowired
    private RelationCaseDatabaseService relationCaseDatabaseService;

    @Autowired
    private DataAssertService dataAssertService;

    @Autowired
    private ParamsAssertService paramsAssertService;

    @Autowired
    private TestReportService testReportService;

    @Autowired
    private TestEnvironmentService testEnvironmentService;

    @Autowired
    private RelationServiceEnvironmentService relationServiceEnvironmentService;

    @Autowired
    private TestDatabaseConfigService testDatabaseConfigService;

    @Autowired
    private RelationCaseParamsService relationCaseParamsService;

    @Autowired
    private TestJarMethodService testJarMethodService;

    @Autowired
    private TestRedisConfigService testRedisConfigService;

    @Override
    @Transactional(readOnly = true)
    public TestCaseDto get(Object condition) {
        TestCase testCase = testCaseMapper.get(condition);
        TestCaseDto testCaseDto = BeanUtils.toBean(testCase, TestCaseDto.class);
        return testCaseDto;
    }

    @Override
    @Transactional(readOnly = true)
    public long count(TestCaseDto condition) {
        return testCaseMapper.count(condition);
    }

    @Override
    @Transactional(readOnly = true)
    public List<TestCaseDto> list(TestCaseDto condition) {
        List<TestCase> list = testCaseMapper.list(condition);
        List<TestCaseDto> dtoList = CollectionUtils.transform(list, TestCaseDto.class);
        return dtoList;
    }

    @Override
    @Transactional(readOnly = true)
    public List<TestCaseDto> list(Map<String, Object> condition) {
        List<TestCase> list = testCaseMapper.list(condition);
        List<TestCaseDto> dtoList = CollectionUtils.transform(list, TestCaseDto.class);
        return dtoList;
    }

    @Override
    @Transactional(readOnly = true)
    public PageResult<TestCaseDto> page(Map<String, Object> condition) {
        return PageResult.wrap((PageInfo) condition.get("page"), list(condition));
    }

    @Override
    public TestCaseDto save(TestCaseDto testCaseDto) {
        TestCase testCase = BeanUtils.toBean(testCaseDto, TestCase.class);
        if (null == testCaseDto.getId()) {
            testCaseMapper.save(testCase);
        } else {
            testCaseMapper.update(testCase);
        }

        testCaseDto.setId(testCase.getId());
        return testCaseDto;
    }

    @Override
    public int save(List<TestCaseDto> testCaseDtos) {
        if (testCaseDtos == null || testCaseDtos.isEmpty()) {
            return 0;
        }
        List<TestCase> testCases = CollectionUtils.transform(testCaseDtos, TestCase.class);
        return testCaseMapper.saveBatch(testCases);
    }

    @Override
    public int update(TestCaseDto testCaseDto) {
        TestCase testCase = BeanUtils.toBean(testCaseDto, TestCase.class);
        return testCaseMapper.update(testCase);
    }

    @Override
    public int deleteByPK(Long id) {
        return testCaseMapper.deleteByPK(id);
    }

    @Override
    public int delete(TestCaseDto testCaseDto) {
        TestCase testCase = BeanUtils.toBean(testCaseDto, TestCase.class);
        return testCaseMapper.delete(testCase);
    }

    @Override
    public int deleteBatchByPK(List<Long> ids) {
        return testCaseMapper.deleteBatchByPK(ids);
    }

    @Override
    public int deleteBatch(List<TestCaseDto> testCases) {
        return 0;
    }

    @Override
    public int updatePart(TestCaseDto testCaseDto) {
        TestCase testCase = BeanUtils.toBean(testCaseDto, TestCase.class);
        return testCaseMapper.updatePart(testCase);
    }

    @Override
    public PageResult<TestCaseDto> listByParams(Map<String, Object> params) {
        List<TestCase> list = testCaseMapper.listByParams(params);
        List<TestCaseDto> dtoList = CollectionUtils.transform(list, TestCaseDto.class);
        for (TestCaseDto testCaseDto : dtoList) {
            if (null != testCaseDto.getInterfaceId()) {
                TestInterfaceDto testInterfaceDto = testInterfaceService.get(testCaseDto.getInterfaceId());
                testCaseDto.setInterfaceDto(testInterfaceDto);
            }
        }
        return PageResult.wrap((PageInfo) params.get("page"), dtoList);
    }

    @Override
    public List<TestCaseDto> listBySuitId(Long suitId) {
        List<TestCase> list = testCaseMapper.listBySuitId(suitId);
        List<TestCaseDto> dtoList = CollectionUtils.transform(list, TestCaseDto.class);
        return dtoList;
    }

    @Override
    public List<TestCaseDto> listAllBySuitList(List<TestSuitDto> testSuitDtoList) {
        List<TestCase> list = testCaseMapper.listAllBySuitList(testSuitDtoList);
        List<TestCaseDto> dtoList = CollectionUtils.transform(list, TestCaseDto.class);
        return dtoList;
    }

    @Override
    public void copyCase(Map<String, Object> params) {
        Long caseId = Long.parseLong((String) params.get("caseId"));

        //??
        TestCase testCase = this.copyBaseInfo(caseId, (String) params.get("caseNum"));

        //???1
        testCase.setParamsAssert(0);
        logger.info("????" + params.get("dataAssert"));
        if ("1".equals(params.get("dataAssert")) && testCase.getParamsAssert() == 1) {
            //???
            this.copyParamsAssert(caseId, testCase.getId());
            testCase.setParamsAssert(1);
        }

        logger.info("???" + params.get("dataClear"));
        testCase.setDataClear(0);
        if ("1".equals(params.get("dataClear")) && testCase.getDataClear() == 1) {
            //??
            this.copyDataClear(caseId, testCase.getId());
            testCase.setDataClear(1);
        }

        logger.info("???" + params.get("dataPrepare"));
        testCase.setDataPrepare(0);
        if ("1".equals(params.get("dataPrepare")) && testCase.getDataPrepare() == 1) {
            //??
            this.copyDataPrepare(caseId, testCase.getId());
            testCase.setDataPrepare(1);
        }
        testCaseMapper.update(testCase);

        logger.info("???" + (params.get("dataParams")));
        if ("1".equals(params.get("dataParams"))) {
            //??
            this.copyDataParams(testCase, caseId, testCase.getId());
        }
    }

    @Override
    public List<TestCaseDto> getByCaseNum(String number) {
        List<TestCase> testCaseList = testCaseMapper.getByCaseNum(number);
        List<TestCaseDto> dtoList = CollectionUtils.transform(testCaseList, TestCaseDto.class);
        return dtoList;
    }

    @Override
    public List<TestCaseDto> listBySuitIdOrderByInterfaceId(Long suitId) {
        List<TestCase> testCaseList = testCaseMapper.listBySuitIdOrderByInterfaceId(suitId);
        List<TestCaseDto> dtoList = CollectionUtils.transform(testCaseList, TestCaseDto.class);
        if (null != dtoList && dtoList.size() > 0) {
            for (TestCaseDto caseDto : dtoList) {
                //??
                caseDto.setInterfaceDto(testInterfaceService.get(caseDto.getInterfaceId()));
            }
        }
        return dtoList;
    }

    @Override
    public List<TestCaseDto> listAllOrderByInterface() {
        List<TestCase> testCaseList = testCaseMapper.listAllOrderByInterface();
        List<TestCaseDto> dtoList = CollectionUtils.transform(testCaseList, TestCaseDto.class);
        if (null != dtoList && dtoList.size() > 0) {
            for (TestCaseDto caseDto : dtoList) {
                //??
                caseDto.setInterfaceDto(testInterfaceService.get(caseDto.getInterfaceId()));
            }
        }
        return dtoList;
    }

    @Override
    public StringBuffer dealWithExcelFile(String path) throws Exception {
        //?
        return readExcel(path);
    }

    private StringBuffer readExcel(String path) throws Exception {
        // ?Excel
        InputStream excelFile = new FileInputStream(path);

        //?????
        StringBuffer failCaseNumbers = new StringBuffer("");
        try {
            Workbook wb = WorkbookFactory.create(new File(path));
            Sheet sheet = wb.getSheetAt(0);
            // 
            int rowNum = sheet.getLastRowNum() + 1;
            logger.info("rowNum" + rowNum);

            //?1
            Row row = sheet.getRow(0);
            int colNum = row.getPhysicalNumberOfCells(); //?
            logger.info("colNum" + colNum);

            // 2,
            for (int i = 1; i < rowNum; i++) {
                TestCaseDto caseDto = new TestCaseDto();
                logger.info("??" + i);
                row = sheet.getRow(i);
                //???
                //?---?
                String number = getCellFormatValue(row.getCell(0)) + "";
                //?
                if (!checkCaseNumberUnique(number)) {
                    failCaseNumbers.append("?").append(number)
                            .append("??");
                    continue;
                }
                caseDto.setNumber(number);

                //?---??
                caseDto.setName(getCellFormatValue(row.getCell(1)) + "");

                //?---??
                caseDto.setDescription(getCellFormatValue(row.getCell(2)) + "");

                //?---?id,?id?id?
                if (StringUtils.isBlank(getCellFormatValue(row.getCell(3)) + "")
                        || !checkInterfaceIdExist(Long.parseLong(getCellFormatValue(row.getCell(3)) + ""))) {
                    failCaseNumbers.append("?").append(number)
                            .append("???id")
                            .append(row.getCell(3)).append("");
                    continue;
                }
                caseDto.setInterfaceId(Long.parseLong(getCellFormatValue(row.getCell(3)) + ""));

                //5?---?
                caseDto.setCustomParams(getCellFormatValue(row.getCell(4)) + "");
                caseDto.setCustomParamsType(ParamsGroupTypeEnum.CUSTOM.getId());

                //6?---?
                caseDto.setCustomParamsType(AppendParamEnum.getIdByName(getCellFormatValue(row.getCell(5)) + ""));

                //10-
                if ("SINGLE".equals(getCellFormatValue(row.getCell(9)))
                        || "MUTIPLE".equals(getCellFormatValue(row.getCell(9)))) {
                    caseDto.setType(getCellFormatValue(row.getCell(9)) + "");
                } else {
                    failCaseNumbers.append("?").append(number)
                            .append("???\"MUTIPLE\"\"SINGLE\"");
                    continue;
                }

                caseDto = this.save(caseDto);
                logger.info("?" + caseDto.toString());
                //7?---?
                String assertJson = getCellFormatValue(row.getCell(6)) + "";
                if (StringUtils.isNotBlank(assertJson)) {
                    try {
                        //??
                        saveParamsAsserts(assertJson, caseDto);
                    } catch (Exception e) {
                        logger.error("?", e);
                        failCaseNumbers.append("?").append(number).append(
                                "???,??");
                    }
                }
                //8-?
                String prepareStr = getCellFormatValue(row.getCell(7)) + "";
                if (StringUtils.isNotBlank(prepareStr)) {
                    try {
                        saveDataOperate(prepareStr, caseDto.getId(), OperationTypeEnum.PREPARE.getId(),
                                failCaseNumbers);
                        caseDto.setDataPrepare(1);
                        //
                        update(caseDto);
                    } catch (Exception e) {
                        logger.error("?sql", e);
                        failCaseNumbers.append("?").append(number).append(
                                "????,??"
                                        + e.getMessage() + "");
                    }
                }

                //9-?
                String clearStr = getCellFormatValue(row.getCell(8)) + "";
                if (StringUtils.isNotBlank(clearStr)) {
                    try {
                        saveDataOperate(clearStr, caseDto.getId(), OperationTypeEnum.CLEAR.getId(),
                                failCaseNumbers);
                        caseDto.setDataClear(1);
                        //
                        update(caseDto);

                    } catch (Exception e) {
                        logger.error("?sql", e);
                        failCaseNumbers.append("?").append(number).append(
                                "????,??"
                                        + e.getMessage() + "");
                    }
                } else {
                    continue;
                }

            }
        } catch (FileNotFoundException e) {
            logger.error("excel", e);
            throw e;
        } catch (IOException e) {
            logger.error("?excel", e);
            throw e;
        } finally {
            return failCaseNumbers;
        }
    }

    //????
    private void saveDataOperate(String operationStr, Long caseId, int operateType, StringBuffer failCaseNumbers) {
        logger.info("??" + OperationTypeEnum.getName(operateType)
                + ",?" + operationStr);
        //operationStr = "??:select * from test_case;??:select * from test_case;"
        String[] strArray = operationStr.split(";|");
        for (String str : strArray) {
            str = str.trim();
            //??redis?
            if (str.startsWith("db_") || str.startsWith("DB_")) {
                saveDataBaseOperate(str, operateType, caseId, failCaseNumbers);
            } else if (str.startsWith("redis_") || str.startsWith("REDIS_")) {
                saveRedisOperate(str, operateType, caseId, failCaseNumbers);
            } else {
                failCaseNumbers.append("?????")
                        .append(str.trim() + "??");
            }
        }

    }

    private void saveRedisOperate(String redisStr, int operateType, Long caseId, StringBuffer failCaseNumbers) {
        //redis???----redis?????? key value timeredis_redisname:set key-name-huhu 123455;

        String[] redisArray = redisStr.split(":|");
        if (null == redisArray || redisArray.length <= 1) {
            failCaseNumbers.append("??redis??")
                    .append(redisStr.trim() + "??");
        }
        String[] redis = redisArray[1].split(" ");
        if (null == redis || StringUtils.isBlank(redis[0])) {
            return;
        }
        RelationCaseRedisDto relationCaseRedisDto = new RelationCaseRedisDto();
        relationCaseRedisDto.setCaseId(caseId);
        relationCaseRedisDto.setOperateType(operateType);
        relationCaseRedisDto.setType(2);//??type2
        relationCaseRedisDto.setRedisName(redisArray[0].replaceFirst("redis_|REDIS_", "").trim());
        relationCaseRedisDto.setRedisOperateType(RedisOperationTypeEnum.getIdByName(redis[0]));
        relationCaseRedisDto.setKey(redis[1]);
        if (redis.length > 2) {
            relationCaseRedisDto.setValue(redis[2]);
        }
        if (redis.length > 3) {
            relationCaseRedisDto.setTime(Integer.parseInt(redis[3]));
        }
        relationCaseRedisService.save(relationCaseRedisDto);

    }

    private void saveDataBaseOperate(String sqlStr, int operateType, Long caseId, StringBuffer failCaseNumbers) {
        String[] sqlArray = sqlStr.split(":|");
        if (null == sqlArray || sqlArray.length <= 1) {
            failCaseNumbers.append(sqlStr.trim() + "??");
        }
        RelationCaseDatabaseDto relationCaseDataBase = new RelationCaseDatabaseDto();
        relationCaseDataBase.setCaseId(caseId);
        relationCaseDataBase.setOperateType(operateType);
        relationCaseDataBase.setDatabaseName(sqlArray[0].replaceFirst("db_|DB_", ""));//?db_DB_
        relationCaseDataBase.setSqlStr(sqlArray[1]);
        relationCaseDataBase.setType(2);//??
        relationCaseDatabaseService.save(relationCaseDataBase);
    }

    private boolean checkInterfaceIdExist(Long interfaceId) {
        TestInterfaceDto testInterfaceDto = testInterfaceService.get(interfaceId);
        if (null != testInterfaceDto) {
            return true;
        }
        return false;
    }

    private void saveParamsAsserts(String assertJson, TestCaseDto caseDto) throws Exception {
        logger.info("?json" + assertJson);
        //?
        if (StringUtils.isNotBlank(assertJson)) {
            JSONObject jsonObject = JSONObject.fromObject(assertJson);
            Set set = jsonObject.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                ParamsAssertDto paramsAssertDto = new ParamsAssertDto();
                paramsAssertDto.setCaseId(caseDto.getId());
                paramsAssertDto.setAssertParam(iterator.next().toString().split("=")[0]);
                paramsAssertDto.setRightValue(iterator.next().toString().split("=")[1]);
                paramsAssertService.save(paramsAssertDto);
            }
        }
    }

    private boolean checkCaseNumberUnique(String number) {
        List<TestCaseDto> testCaseList = this.getByCaseNum(number);
        if (null != testCaseList && testCaseList.size() > 0) {
            return false;
        }
        return true;
    }

    /**
     * ?Cell?
     * @param cell
     * @return
     */
    private Object getCellFormatValue(Cell cell) {
        if (null == cell) {
            return "";
        }
        DataFormatter formatter = new DataFormatter();
        switch (cell.getCellTypeEnum()) {
        case STRING:
            return cell.getRichStringCellValue().getString();
        case NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                return cell.getDateCellValue();
            } else {
                return Math.round(cell.getNumericCellValue());
            }
        case BOOLEAN:
            return cell.getBooleanCellValue();
        case FORMULA:
            return cell.getCellFormula();
        case BLANK:
            return "";
        default:
            return "";
        }

    }

    private void copyDataParams(TestCase testCase, Long caseId, Long newCaseId) {
        //???
        if (testCase.getParamsType() == ParamsGroupTypeEnum.KEY.getId()) {
            //?????
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("caseId", caseId);
            params.put("idDelete", 0);
            List<RelationCaseParamsDto> relationCaseParamsDtoList = relationCaseParamsService.list(params);
            if (null != relationCaseParamsDtoList && relationCaseParamsDtoList.size() > 0) {
                logger.info("??" + relationCaseParamsDtoList.size());
                for (RelationCaseParamsDto relationCaseParams : relationCaseParamsDtoList) {
                    relationCaseParams.setId(null);
                    relationCaseParams.setIsDelete(0);
                    relationCaseParams.setCaseId(newCaseId);
                    relationCaseParamsService.save(relationCaseParams);
                }
            }
        }

    }

    //?
    private void copyDataPrepare(Long caseId, Long newCaseId) {
        copyDataOperate(caseId, newCaseId, OperationTypeEnum.PREPARE.getId());
    }

    //?
    private void copyDataClear(Long caseId, Long newCaseId) {
        copyDataOperate(caseId, newCaseId, OperationTypeEnum.CLEAR.getId());
    }

    //???
    private void copyParamsAssert(Long caseId, Long newCaseId) {
        List<ParamsAssertDto> paramsAssertDtoList = paramsAssertService.getByCaseId(caseId);
        if (null != paramsAssertDtoList && paramsAssertDtoList.size() > 0) {
            logger.info("??" + paramsAssertDtoList.size());
            for (ParamsAssertDto paramsAssertDto : paramsAssertDtoList) {
                paramsAssertDto.setId(null);
                paramsAssertDto.setCaseId(newCaseId);
                paramsAssertDto.setIsDelete(0);
                paramsAssertService.save(paramsAssertDto);
            }
        }
    }

    //??
    private TestCase copyBaseInfo(Long caseId, String caseNum) {
        TestCase testCase = testCaseMapper.get(caseId);
        //id??
        testCase.setId(null);
        testCase.setIsDelete(0);
        testCase.setStatus(0);
        testCase.setNumber(caseNum);
        testCaseMapper.save(testCase);//?idtestCase
        logger.info("???" + testCase.toString());
        return testCase;
    }

    //???
    private void copyDataOperate(Long caseId, Long newCaseId, Integer operateType) {
        //?
        List<RelationCaseDatabaseDto> relationCaseDatabaseList = relationCaseDatabaseService
                .getByCaseIdAndOperateType(caseId, operateType);
        if (null != relationCaseDatabaseList && relationCaseDatabaseList.size() > 0) {
            logger.info("???" + relationCaseDatabaseList.size());
            for (RelationCaseDatabaseDto relationCaseDatabaseDto : relationCaseDatabaseList) {
                relationCaseDatabaseDto.setId(null);
                relationCaseDatabaseDto.setIsDelete(0);
                relationCaseDatabaseDto.setCaseId(newCaseId);
                relationCaseDatabaseService.save(relationCaseDatabaseDto);
            }
        }

        //redis
        List<RelationCaseRedisDto> relationCaseRedisList = relationCaseRedisService
                .getByCaseIdAndOperateType(caseId, operateType);
        if (null != relationCaseRedisList && relationCaseRedisList.size() > 0) {
            logger.info("redis??" + relationCaseRedisList.size());
            for (RelationCaseRedisDto relationCaseRedisDto : relationCaseRedisList) {
                relationCaseRedisDto.setId(null);
                relationCaseRedisDto.setIsDelete(0);
                relationCaseRedisDto.setCaseId(newCaseId);
                relationCaseRedisService.save(relationCaseRedisDto);
            }
        }
    }

    @Override
    public void excuteCaseList(List<TestCaseDto> testCaseDtoList, TestEnvironmentDto testEnvironmentDto,
            Long planId, TestReportDto testReportDto, TestSuitDto suitDto) throws Exception {
        ReportResult.getReportResult().setTotal(ReportResult.getReportResult().getTotal() + testCaseDtoList.size());
        excute(testCaseDtoList, testEnvironmentDto, planId, testReportDto, suitDto);

    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    private void excute(final List<TestCaseDto> testCaseDtoList, final TestEnvironmentDto testEnvironmentDto,
            final Long planId, final TestReportDto testReportDto, final TestSuitDto suitDto) {
        logger.info("==================");
        //
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        ;
        //??
        for (int i = 0; i < testCaseDtoList.size(); i++) {
            final int finalI = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        logger.info("========" + finalI);
                        excuteCase(testCaseDtoList.get(finalI), testEnvironmentDto, planId, testReportDto, suitDto);
                    } catch (Exception e) {
                        logger.error("", e);
                    }

                }
            });
        }

        try {
            logger.info("sleep-----" + 1000);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.info("InterruptedException-----" + e.getMessage());
        }

        threadPool.shutdown();
        while (true) {
            if (threadPool.isTerminated()) {
                break;
            }
        }
    }

    @Override
    public void testRun(Long caseId, Long environmentId) throws Exception {
        //dubbo?http?
        logger.info("==========?========");
        TestInterfaceDto testInterfaceDto = testInterfaceService.getByCaseId(caseId);
        if (null != testInterfaceDto) {
            if (InterfaceTypeEnum.HTTP.getId() == testInterfaceDto.getType()) {
                testRunHttp(testInterfaceDto, caseId, environmentId);
            } else if (InterfaceTypeEnum.DUBBO.getId() == testInterfaceDto.getType()) {
                testRunDubbo(testInterfaceDto, caseId, environmentId);
            }
        }
    }

    @Override
    public List<TestCaseDto> getByCaseIds(String caseIds) {
        String[] ids = caseIds.split(",|");
        List<TestCase> testCaseList = testCaseMapper.getByCaseIds(ids);
        List<TestCaseDto> dtoList = CollectionUtils.transform(testCaseList, TestCaseDto.class);
        return dtoList;
    }

    @Override
    public void changeStatusList(int status, List<TestCaseDto> testCaseDtoList) {
        testCaseMapper.changeStatusList(status, testCaseDtoList);
    }

    /**
     * dubbo??
     * @param testInterfaceDto
     * @param caseId
     * @param environmentId
     */
    private void testRunDubbo(TestInterfaceDto testInterfaceDto, Long caseId, Long environmentId) {
        logger.info("==========?DUBBO========");
        TestCaseDto testCaseDto = this.get(caseId);
        TestEnvironmentDto testEnvironmentDto = testEnvironmentService.get(environmentId);
        this.excuteDubbo(testCaseDto, testInterfaceDto, testEnvironmentDto, null, null);
    }

    /**
     * http??
     * @param testInterfaceDto
     * @param caseId
     * @param environmentId
     */
    private void testRunHttp(TestInterfaceDto testInterfaceDto, Long caseId, Long environmentId) throws Exception {
        logger.info("==========?HTTP========");
        TestCaseDto testCaseDto = this.get(caseId);
        TestEnvironmentDto testEnvironmentDto = testEnvironmentService.get(environmentId);
        this.excuteHttp(testCaseDto, testInterfaceDto, testEnvironmentDto, null, null, null);
    }

    /**
     * 
     * @param caseDto 
     * @param testEnvironmentDto 
     * @param testReportDto
     */
    //    @Transactional(propagation = TransactionDefinition.ISOLATION_READ_UNCOMMITTED)
    private void excuteCase(TestCaseDto caseDto, TestEnvironmentDto testEnvironmentDto, Long planId,
            TestReportDto testReportDto, TestSuitDto suitDto) throws Exception {
        logger.info("" + caseDto.getId() + "-" + caseDto.getName());
        logger.info("reportResult"
                + ReportResult.getReportResult().toString());

        //??
        logger.info("==========id=" + caseDto.getId() + "??========");
        TestInterfaceDto interfaceDto = testInterfaceService.getByCaseId(caseDto.getId());
        if (null != interfaceDto) {
            if (InterfaceTypeEnum.DUBBO.getId() == interfaceDto.getType()) {
                //dubbo?
                this.excuteDubbo(caseDto, interfaceDto, testEnvironmentDto, planId, testReportDto);
            } else if (InterfaceTypeEnum.HTTP.getId() == interfaceDto.getType()) {
                //http?
                this.excuteHttp(caseDto, interfaceDto, testEnvironmentDto, planId, testReportDto, suitDto);
            }
        }

    }

    /**
     * http?
     * @param caseDto
     * @param interfaceDto
     * @param testEnvironmentDto
     */
    private void excuteHttp(TestCaseDto caseDto, TestInterfaceDto interfaceDto,
            TestEnvironmentDto testEnvironmentDto, Long planId, TestReportDto testReportDto, TestSuitDto suitDto)
            throws Exception {
        Long caseId = caseDto.getId(); //id
        Long interfaceId = interfaceDto.getId();//?id
        Long environmentId = testEnvironmentDto.getId();//id
        Long reportId = null != testReportDto ? testReportDto.getId() : null;
        logger.info("==========http?:id??id?id?========" + caseId
                + "," + interfaceId + "," + environmentId);
        //???
        boolean flag = DBUtil.getDBInit(environmentId, caseId);

        if (!flag) {
            logger.info("???");
            return;
        }

        TestCaseCommand testCaseCommand = new TestCaseCommand();
        //??
        testCaseCommand.setBeforeCommand(getBeforeCommand(testEnvironmentDto, caseDto));
        //?
        testCaseCommand.setAfterCommand(getAfterCommand(testEnvironmentDto, caseDto));
        //?
        testCaseCommand.setAssertCommand(getAssertCommand(caseDto, interfaceDto, reportId));

        //========================??http?===============================
        //?---200000
        String timeout = "200000";
        //?get/post
        String requestType = RequestTypeEnum.getName(interfaceDto.getRequestType());
        //??
        String propType = HttpTypeEnum.getName(interfaceDto.getProtocolType());
        //?http?url
        String url = interfaceDto.getUrl();
        //contentType
        String contentType = interfaceDto.getContentType();
        logger.info("contentType:" + contentType);
        //http??
        RelationServiceEnvironmentDto relationServiceEnvironmentDto = relationServiceEnvironmentService
                .getByCaseAndEnvironment(interfaceDto.getServiceId(), environmentId);
        if (null != relationServiceEnvironmentDto) {
            url = propType + "://" + relationServiceEnvironmentDto.getIpAddress() + ":"
                    + relationServiceEnvironmentDto.getHttpPort() + "/" + url;
        }
        logger.info("url:" + url);
        //??9
        String paramsStr = formatParams(caseDto, contentType, interfaceDto);
        logger.info("paramsStr:" + paramsStr);

        testCaseCommand.setCaseCommand(getCaseCommand(requestType, url, paramsStr, contentType, timeout, propType,
                caseDto, interfaceDto, planId, reportId, suitDto));

        //
        testCaseCommand.execute();

        if (flag) {
            DBUtil.DBClose();
        }
    }

    //?
    private CaseCommand getCaseCommand(String requestType, String url, String paramsStr, String contentType,
            String timeout, String propType, TestCaseDto caseDto, TestInterfaceDto interfaceDto, Long planId,
            Long reportId, TestSuitDto suitDto) {
        return new HttpCaseCommand(requestType, url, paramsStr, contentType, timeout, propType, caseDto,
                interfaceDto, planId, reportId, suitDto);
    }

    //?
    private AssertCommand getAssertCommand(TestCaseDto caseDto, TestInterfaceDto interfaceDto, Long reportId) {
        Assert assertItem = new Assert(interfaceDto, caseDto);
        List<AssertKeyValueVo> paralist = new ArrayList();
        // List<KeyValueStore> redislist = new ArrayList();

        List<Command> dbAssertCommandList = new ArrayList();
        ParaAssertCommand paraAssertCommand = null;
        DBAssertCommand dbAssertCommand = null;

        //??
        //1.?
        List<DataAssertDto> dataAssertDtoList = dataAssertService.getByCaseId(caseDto.getId());
        if (null != dataAssertDtoList && dataAssertDtoList.size() > 0) {
            for (DataAssertDto dataAssert : dataAssertDtoList) {
                dbAssertCommand = new DBAssertCommand();
                //???????
                TestDatabaseConfigDto testDatabaseConfigDto = testDatabaseConfigService
                        .getByName(dataAssert.getDatabaseName());
                if (null != testDatabaseConfigDto) {
                    logger.info("??????"
                            + testDatabaseConfigDto.toString());
                    dbAssertCommand.setName(testDatabaseConfigDto.getDatabaseName());
                }
                dbAssertCommand.setSql(dataAssert.getSqlStr());
                dbAssertCommand.setAssertItem(assertItem);
                dbAssertCommand.setId(dataAssert.getId());
                dbAssertCommandList.add(dbAssertCommand);
                logger.info("?" + dbAssertCommand.toString());
            }
        }

        //        //2.redis-----??
        //        List<Command> redisAssertCommandList = new ArrayList();
        //        List<RedisAssertDto> redisAssertDtoList = redisAssertService.getByCaseId(caseDto.getId());

        //3.?
        List<ParamsAssertDto> paramsAssertDtoList = paramsAssertService.getByCaseId(caseDto.getId());
        if (null != paramsAssertDtoList && paramsAssertDtoList.size() > 0) {
            for (ParamsAssertDto paramsDto : paramsAssertDtoList) {
                AssertKeyValueVo keyValueStore = new AssertKeyValueVo(paramsDto.getAssertParam(),
                        paramsDto.getRightValue(), paramsDto.getId());
                paralist.add(keyValueStore);
                logger.info("?" + keyValueStore.toString());
            }
            paraAssertCommand = new ParaAssertCommand(paralist);
            paraAssertCommand.setAssertItem(assertItem);
        }
        AssertCommand assertCommand = new AssertCommand(paraAssertCommand, null, dbAssertCommandList, assertItem,
                reportId);
        return assertCommand;

    }

    //????
    private List<Command> getAfterCommand(TestEnvironmentDto testEnvironmentDto, TestCaseDto testcaseDto) {
        List<Command> list = new ArrayList();
        Long caseId = testcaseDto.getId(); //id
        Long environmentId = testEnvironmentDto.getId();//id

        //?
        if (null != testcaseDto.getDataClear() && testcaseDto.getDataClear() > 0) {
            //?---?
            List<RelationCaseDatabaseDto> relationCaseDatabaseDtoList = relationCaseDatabaseService
                    .getByCaseIdAndOperateType(caseId, OperationTypeEnum.CLEAR.getId());
            if (null != relationCaseDatabaseDtoList && relationCaseDatabaseDtoList.size() > 0) {
                for (RelationCaseDatabaseDto relationCaseDatbase : relationCaseDatabaseDtoList) {
                    //?sql
                    logger.info("==========?sql" + relationCaseDatbase.getSqlStr());
                    //???????
                    TestDatabaseConfigDto testDatabaseConfigDto = testDatabaseConfigService
                            .getByName(relationCaseDatbase.getDatabaseName());
                    if (null != testDatabaseConfigDto) {
                        logger.info("??????"
                                + testDatabaseConfigDto.toString());
                        list.add(new DBCommand(testDatabaseConfigDto.getDatabaseName(),
                                relationCaseDatbase.getSqlStr()));
                    }
                }
            }
            //?---redis
            List<RelationCaseRedisDto> relationCaseRedisDtoList = relationCaseRedisService
                    .getByCaseIdAndOperateType(caseId, OperationTypeEnum.CLEAR.getId());
            if (null != relationCaseRedisDtoList && relationCaseRedisDtoList.size() > 0) {
                for (RelationCaseRedisDto relationCaseRedisDto : relationCaseRedisDtoList) {
                    RedisCommand redisCommand = new RedisCommand();
                    redisCommand.setCaseId(caseId);
                    redisCommand.setEnvironmentId(environmentId);
                    redisCommand.setKey(relationCaseRedisDto.getKey());
                    redisCommand.setMethodName(
                            RedisOperationTypeEnum.getName(relationCaseRedisDto.getRedisOperateType()));
                    if (null != relationCaseRedisDto.getTime()) {
                        redisCommand.setTime(relationCaseRedisDto.getTime());
                    }
                    if (null != relationCaseRedisDto.getValue()) {
                        redisCommand.setValue(relationCaseRedisDto.getValue());
                    }
                    //?redis
                    RedisUtil redisUtil = new RedisUtil();
                    setRedisConnect(relationCaseRedisDto.getRedisName(), environmentId, redisUtil);
                    redisCommand.setRedisUtil(redisUtil);
                    list.add(redisCommand);
                }
            }
        }
        return list;
    }

    //????
    private List<Command> getBeforeCommand(TestEnvironmentDto testEnvironmentDto, TestCaseDto testcaseDto) {
        List<Command> list = new ArrayList();

        Long caseId = testcaseDto.getId(); //id
        Long environmentId = testEnvironmentDto.getId();//id

        //?
        if (null != testcaseDto.getDataPrepare() && testcaseDto.getDataPrepare() > 0) {
            //?---?
            List<RelationCaseDatabaseDto> relationCaseDatabaseDtoList = relationCaseDatabaseService
                    .getByCaseIdAndOperateType(caseId, OperationTypeEnum.PREPARE.getId());
            if (null != relationCaseDatabaseDtoList && relationCaseDatabaseDtoList.size() > 0) {
                for (RelationCaseDatabaseDto relationCaseDatbase : relationCaseDatabaseDtoList) {
                    //?sql
                    logger.info("==========?sql" + relationCaseDatbase.getSqlStr());
                    //???????
                    TestDatabaseConfigDto testDatabaseConfigDto = testDatabaseConfigService
                            .getByName(relationCaseDatbase.getDatabaseName());
                    if (null != testDatabaseConfigDto) {
                        list.add(new DBCommand(testDatabaseConfigDto.getDatabaseName(),
                                relationCaseDatbase.getSqlStr()));
                    }
                }
            }
            //?---redis
            List<RelationCaseRedisDto> relationCaseRedisDtoList = relationCaseRedisService
                    .getByCaseIdAndOperateType(caseId, OperationTypeEnum.PREPARE.getId());
            if (null != relationCaseRedisDtoList && relationCaseRedisDtoList.size() > 0) {
                for (RelationCaseRedisDto relationCaseRedisDto : relationCaseRedisDtoList) {
                    RedisCommand redisCommand = new RedisCommand();
                    redisCommand.setCaseId(caseId);
                    redisCommand.setEnvironmentId(environmentId);
                    redisCommand.setKey(relationCaseRedisDto.getKey());
                    redisCommand.setMethodName(
                            RedisOperationTypeEnum.getName(relationCaseRedisDto.getRedisOperateType()));
                    if (null != relationCaseRedisDto.getTime()) {
                        redisCommand.setTime(relationCaseRedisDto.getTime());
                    }
                    if (null != relationCaseRedisDto.getValue()) {
                        redisCommand.setValue(relationCaseRedisDto.getValue());
                    }

                    //?redis
                    RedisUtil redisUtil = new RedisUtil();
                    setRedisConnect(relationCaseRedisDto.getRedisName(), environmentId, redisUtil);
                    redisCommand.setRedisUtil(redisUtil);
                    list.add(redisCommand);
                }
            }
        }
        return list;
    }

    private void setRedisConnect(String redisName, Long environmentId, RedisUtil redisUtil) {
        HashSet<HostAndPort> nodes = new HashSet();
        TestRedisConfigDto redisConfigDto = testRedisConfigService.getByRedisNameAndEnvironmentId(redisName,
                environmentId);
        if (null != redisConfigDto) {
            String ips = redisConfigDto.getIpAddress();
            if (StringUtils.isNotBlank(ips)) {
                String[] ipAndPorts = ips.split(";|");
                for (String ipAndPort : ipAndPorts) {
                    String ip = ipAndPort.split(":|")[0].trim();
                    int port = Integer.parseInt(ipAndPort.split(":|")[1].trim());
                    HostAndPort hostAndPort = new HostAndPort(ip, port);
                    nodes.add(hostAndPort);
                }
            }
        }
        redisUtil.setJedisCluster(new JedisCluster(nodes, 3000, 30));
    }

    //??
    private String formatParams(TestCaseDto caseDto, String contentType, TestInterfaceDto interfaceDto) {
        //?,???,???
        StringBuffer paramsStr = new StringBuffer("");
        if (null != caseDto.getParamsType() && ParamsGroupTypeEnum.KEY.getId() == caseDto.getParamsType()) {
            //??
            List<ParamDto> testParamsDtoList = testParamsService.listByCaseIdFromRelation(caseDto.getId());
            if (contentType.equals("application/json")) {
                logger.info("??json" + testParamsDtoList.size() + "?");
                //?json
                if (null != testParamsDtoList && testParamsDtoList.size() > 0) {
                    JSONObject jsonObject = new JSONObject();
                    Iterator iterator = testParamsDtoList.iterator();
                    //---???
                    Date date = new Date();

                    while (iterator.hasNext()) {
                        ParamDto param = (ParamDto) iterator.next();
                        logger.info("?" + param.toString());
                        String value = param.getValue();
                        //??
                        if (param.getFormatType() == ParamFormatTypeEnum.ENCRYPT.getId()) {
                            //?,???
                            value = encrypt(interfaceDto.getJarPath(), interfaceDto, caseDto.getId(),
                                    param.getMethodName(), date);
                            logger.info("????" + param.getName()
                                    + "," + value);
                        } else if (value.equals("timestamp")) {
                            //
                            value = (date.getTime()) + "";
                        }
                        jsonObject.put(param.getName(), value);
                    }
                    paramsStr = paramsStr.append(jsonObject.toString());
                    logger.info("??" + paramsStr);
                }

            } else {
                logger.info("??&?" + testParamsDtoList.size() + "?");
                //?
                if (null != testParamsDtoList && testParamsDtoList.size() > 0) {
                    Iterator iterator = testParamsDtoList.iterator();
                    //---???
                    Date date = new Date();
                    while (iterator.hasNext()) {
                        ParamDto param = (ParamDto) iterator.next();
                        String value = param.getValue();
                        //??
                        if (param.getFormatType() == ParamFormatTypeEnum.ENCRYPT.getId()) {
                            //?,???
                            value = encrypt(interfaceDto.getJarPath(), interfaceDto, caseDto.getId(),
                                    param.getMethodName(), date);
                            logger.info("????" + param.getName()
                                    + "," + value);
                        } else if (value.equals("timestamp")) {
                            //
                            value = (date.getTime()) + "";
                        }
                        paramsStr.append(param.getName() + "=" + param.getValue());
                        paramsStr.append("&");
                    }
                    paramsStr = new StringBuffer(paramsStr.substring(0, paramsStr.lastIndexOf("&")));
                }
            }
        } else if (null != caseDto.getParamsType()
                && ParamsGroupTypeEnum.CUSTOM.getId() == caseDto.getParamsType()) {
            //??
            logger.info("?" + caseDto.getCustomParams());
            paramsStr = new StringBuffer(caseDto.getCustomParams());
        }

        return paramsStr.toString();
    }

    public String encrypt(String path, TestInterfaceDto interfaceDto, Long caseId, String methodName, Date date) {
        //??
        TestJarMethodDto testJarMethodDto = testJarMethodService.getByMethodNameAndInterfaceId(methodName,
                interfaceDto.getId());
        if (null == testJarMethodDto) {
            return null;
        }

        StringBuffer value = new StringBuffer("");
        //???????
        try {
            String className = testJarMethodDto.getClassName();
            String paramsTypes = testJarMethodDto.getParamsTypes();//String,int,double
            String paramsValues = testJarMethodDto.getParamsValues();//?{appid},123,4556appid=?{appid}&req=123,ddddd

            logger.info("??------");
            //??
            String[] typesArray = paramsTypes.split(",|");
            Class<?>[] types = new Class[typesArray.length];
            for (int i = 0; i < types.length; i++) {
                //??????
                String type = getTypeFullName(typesArray[i]);
                logger.info("??------" + type);
                types[i] = Class.forName(type);
            }

            StringBuffer paramsValuesNew = new StringBuffer("");
            logger.info("??------??");
            String[] values = paramsValues.split(",|");
            for (String oValue : values) {
                //???,appId=?&nonce=56412&reqId=timestamp&timestamp=timestamp
                logger.info("?" + oValue);
                //???jar?---appid=?{appid}&req=123
                if (oValue.contains("&")) {
                    String[] valueItemArray = oValue.split("&");
                    for (int i = 0; i < valueItemArray.length; i++) {
                        String itemValue = valueItemArray[i];
                        logger.info("???" + itemValue);
                        //????
                        if (itemValue.contains("?")) {
                            String[] valueItem = itemValue.split("=");//valueItem[0] = "appid"valueItem[1] = "?{appid}"
                            //valueItem[1] = "?{appid}"????
                            String valueName = valueItem[1].substring(2, valueItem[1].length() - 1);
                            //?
                            RelationCaseParamsDto relationCaseParams = relationCaseParamsService
                                    .getByCaseIdAndParamName(valueName, caseId, 0);
                            if (null != relationCaseParams) {
                                //paramsValues = paramsValues.replace(itemValue,valueItem[0] + "=" + relationCaseParams.getValue());
                                paramsValuesNew.append(valueItem[0]).append("=")
                                        .append(relationCaseParams.getValue());
                            }
                        } else {
                            paramsValuesNew.append(itemValue);
                        }
                        //???&?
                        if (i < valueItemArray.length - 1) {
                            paramsValuesNew.append("&");
                        }
                    }
                } else if (oValue.contains("?")) {
                    //?????jar?----?{appid}
                    //???
                    String valueName = oValue.substring(2, oValue.length() - 1);
                    ;

                    //?
                    RelationCaseParamsDto relationCaseParams = relationCaseParamsService
                            .getByCaseIdAndParamName(valueName, caseId, 0);
                    if (null != relationCaseParams) {
                        //paramsValues = paramsValues.replace(oValue, relationCaseParams.getValue());
                        paramsValuesNew.append(relationCaseParams.getValue());
                    } else {
                        //?
                        //paramsValues = paramsValues.replace(oValue, "");
                        paramsValuesNew.append("");
                    }
                } else {
                    paramsValuesNew.append(oValue);
                }
                paramsValuesNew.append(",");
            }

            logger.info("?" + paramsValuesNew.toString());
            //??
            String timestamp = "=" + date.getTime();
            //???????
            Object[] valusObject = paramsValuesNew.toString().replaceAll("=timestamp", timestamp).split(",|");
            //jar
            value = JarUtil.signature(path, className, methodName, types, valusObject);
        } catch (Exception e) {
            logger.error("" + e);
        }
        return (null == value ? null : value.toString());
    }

    private static String getTypeFullName(String s) {
        if (s.equalsIgnoreCase("string")) {
            return STRING_NAME;
        } else if (s.equalsIgnoreCase("integer") || s.equalsIgnoreCase("int")) {
            return INTEGER_NAME;
        } else if (s.equalsIgnoreCase("short")) {
            return SHORT_NAME;
        } else if (s.equalsIgnoreCase("byte")) {
            return BYTE_NAME;
        } else if (s.equalsIgnoreCase("long")) {
            return LONG_NAME;
        } else if (s.equalsIgnoreCase("double")) {
            return DOUBLE_NAME;
        } else if (s.equalsIgnoreCase("float")) {
            return FLOAT_NAME;
        } else if (s.equalsIgnoreCase("boolean")) {
            return BOOLEAN_NAME;
        } else {
            return STRING_NAME;
        }
    }

    /**
     * dubbo?
     * @param caseDto
     * @param interfaceDto
     * @param testEnvironmentDto
     * @param testReportDto
     */
    private void excuteDubbo(TestCaseDto caseDto, TestInterfaceDto interfaceDto,
            TestEnvironmentDto testEnvironmentDto, Long planId, TestReportDto testReportDto) {
        logger.info("==========dubbo?:id??id?id?========"
                + caseDto.getId() + "," + interfaceDto.getId() + "," + testEnvironmentDto.getId());

    }

    public static void main(String[] s) {
        String redisStr = "redis_redisname:set key-name-huhu 123455";
        String[] redisArray = redisStr.split(":|");

        String[] redis = redisArray[1].split(" ");
        if (null == redis || StringUtils.isBlank(redis[0])) {
            return;
        }
        RelationCaseRedisDto relationCaseRedisDto = new RelationCaseRedisDto();

        relationCaseRedisDto.setRedisName(redisArray[0].replaceFirst("redis_|REDIS_", "").trim());
        relationCaseRedisDto.setRedisOperateType(RedisOperationTypeEnum.getIdByName(redis[0]));
        relationCaseRedisDto.setKey(redis[1]);
        if (redis.length > 2) {
            relationCaseRedisDto.setValue(redis[2]);
        }
        if (redis.length > 3) {
            relationCaseRedisDto.setTime(Integer.parseInt(redis[3]));
        }
        System.out.println(relationCaseRedisDto.toString());
    }
}