kimi
2020-11-27 75c32d6d697a550400d0b4eec95b8570d83b726f
src/main/java/com/highdatas/srs/web/FileController.java
@@ -1,12 +1,11 @@
package com.highdatas.srs.web;
import com.alibaba.fastjson.JSONObject;
import com.highdatas.srs.entity.ProjectDeal;
import com.highdatas.srs.entity.Scheme;
import com.highdatas.srs.entity.SchemeDetail;
import com.highdatas.srs.entity.Topic;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.highdatas.srs.entity.*;
import com.highdatas.srs.pojo.CodeMsg;
import com.highdatas.srs.pojo.Result;
import com.highdatas.srs.service.IModuleService;
import com.highdatas.srs.service.ISchemeDetailService;
import com.highdatas.srs.service.ISchemeService;
import com.highdatas.srs.service.ITopicService;
@@ -14,6 +13,9 @@
import com.highdatas.srs.util.FileUtils;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
@@ -24,9 +26,11 @@
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @author kimi
@@ -44,6 +48,9 @@
    ISchemeService schemeService;
    @Autowired
    ITopicService topicService;
    @Autowired
    IModuleService moduleService;
    @Value("${base.file.path}")
    String basePath;
    @Value("${base.topic.path}")
@@ -55,15 +62,16 @@
        ArrayList<JSONObject> childrenFiles = FileUtils.getChildrenFiles(path);
        return Result.success(childrenFiles);
    }
    @RequestMapping(value = "downloadPath", method = RequestMethod.GET)
    public Result downloadPath(@RequestParam String path, HttpServletResponse response) throws UnsupportedEncodingException {
        path = URLDecoder.decode(path, "UTF-8");
        File file = new File(path);
        if(file.exists()){ //判断文件父目录是否存在
        if (file.exists()) { //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(file.getName(),"UTF-8"));
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
@@ -74,7 +82,7 @@
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
@@ -90,9 +98,199 @@
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }}
            return null;
            }
        }
        return null;
    }
    @RequestMapping("timeline/{schemeId}")
    public void timeline(@PathVariable String schemeId, HttpServletResponse response) {
        Scheme scheme = schemeService.selectById(schemeId);
        if (scheme == null) {
            return;
        }
        String status = scheme.getStatus();
        if (!status.equalsIgnoreCase("working")) {
            return;
        }
        try {
            // 1.读取Excel模板
            String filePath = "D:/project/template.xlsx";
            File file = new File(filePath);
            InputStream in = new FileInputStream(file);
            XSSFWorkbook wb = new XSSFWorkbook(in);
            // 2.读取模板里面的所有Sheet
            XSSFSheet sheet = wb.getSheetAt(0);
//        Font dateFont = wb.createFont();
//        dateFont.setFontName("等线");
//        dateFont.setFontHeightInPoints((short) 9);
//        XSSFCellStyle dateCellStyle = wb.createCellStyle();
//        dateCellStyle.setRotation((short) (Math.abs(45)));
//        dateCellStyle.setWrapText(true);
//        dateCellStyle.setFont(dateFont);
            XSSFCellStyle inTimeCellStyle = wb.createCellStyle();
            inTimeCellStyle.setFillBackgroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
            inTimeCellStyle.setFillPattern(FillPatternType.THICK_HORZ_BANDS);
            XSSFCellStyle finishTimeCellStyle = wb.createCellStyle();
            finishTimeCellStyle.setFillBackgroundColor(IndexedColors.ORANGE.getIndex());
            finishTimeCellStyle.setFillPattern(FillPatternType.THICK_FORWARD_DIAG);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            XSSFRow dateRow = sheet.getRow(1);
            XSSFRow firstRow = sheet.getRow(0);
            XSSFCell planCell = firstRow.getCell(12);
            XSSFCellStyle planStyle = planCell.getCellStyle();
            XSSFCell planEndCell = firstRow.getCell(17);
            XSSFCell exportCell = firstRow.getCell(23);
            XSSFCellStyle exportStyle = exportCell.getCellStyle();
            XSSFCellStyle cellEndStyle = planEndCell.getCellStyle();
            XSSFRow titleRow = sheet.getRow(3);
            XSSFRow datesRow = sheet.getRow(2);
            datesRow.setHeightInPoints(60);
            XSSFCell dateCell = datesRow.getCell(12);
            XSSFCellStyle dateCellCellStyle = dateCell.getCellStyle();
            XSSFRow subTitleRow = sheet.getRow(4);
            XSSFCell subTitleCell = subTitleRow.getCell(2);
            XSSFCellStyle subTitleCellStyle = subTitleCell.getCellStyle();
            XSSFCell subStartCell = subTitleRow.getCell(6);
            XSSFCellStyle subStartCellStyle = subStartCell.getCellStyle();
            XSSFCell subtimesCell = subTitleRow.getCell(7);
            XSSFCellStyle subtimesCellStyle = subtimesCell.getCellStyle();
            XSSFCell subendTimeCell = subTitleRow.getCell(9);
            XSSFCellStyle subendTimeCellCellStyle = subendTimeCell.getCellStyle();
            XSSFCell subendRemarkCell = subTitleRow.getCell(10);
            XSSFCellStyle remarkCellCellStyle = subendRemarkCell.getCellStyle();
            XSSFCell titleCell = titleRow.getCell(1);
            XSSFCellStyle titleStyle = titleCell.getCellStyle();
            XSSFCell nameCell = dateRow.getCell(1);
            nameCell.setCellValue(scheme.getName() + "(" + dateFormat.format(scheme.getStartTime()) + ")");
            List<Module> parent_id = moduleService.selectList(new EntityWrapper<Module>().isNull("parent_id").orderBy("order_no"));
            List<SchemeDetail> schemeDetailList = schemeDetailService.selectList(new EntityWrapper<SchemeDetail>().eq("parent_id", scheme.getId()));
            Date startTime = scheme.getStartTime();
            Date endTime = scheme.getEndTime();
            Calendar start = Calendar.getInstance();
            start.setTime(startTime);
            int index = 12;
            XSSFRow dateRows = sheet.getRow(2);
            while (startTime.before(endTime)) {
                startTime = start.getTime();
                XSSFCell inTimeCell = dateRows.createCell(index);
                inTimeCell.setCellValue(dateFormat.format(startTime));
                inTimeCell.setCellStyle(dateCellCellStyle);
                index++;
                start.add(Calendar.DAY_OF_YEAR, 1);
            }
            startTime = scheme.getStartTime();
            start.setTime(startTime);
            int startRow = 3;
            for (int i = 0; i < parent_id.size(); i++) {
                Module module = parent_id.get(i);
                XSSFRow row = sheet.createRow(startRow);
                XSSFCell cell = row.createCell(1);
                cell.setCellValue(MessageFormat.format("Step {0} {1}", i + 1, module.getTitle()));
                cell.setCellStyle(titleStyle);
                List<Module> subModuleList = moduleService.selectList(new EntityWrapper<Module>().eq("parent_id", module.getId()).orderBy("order_no"));
                for (Module subModule : subModuleList) {
                    List<SchemeDetail> collect = schemeDetailList.stream().filter(schemeDetail -> schemeDetail.getType().toString().equals(subModule.getId())).collect(Collectors.toList());
                    if (collect.isEmpty()) {
                        continue;
                    }
                    startRow++;
                    SchemeDetail detail = collect.get(0);
                    XSSFRow nextRow = sheet.createRow(startRow);
                    XSSFCell subtitleCell = nextRow.createCell(2);
                    subtitleCell.setCellValue(subModule.getTitle());
                    subtitleCell.setCellStyle(subTitleCellStyle);
                    XSSFCell startCell = nextRow.createCell(6);
                    startCell.setCellValue(dateFormat.format(detail.getStartTime()));
                    startCell.setCellStyle(subStartCellStyle);
                    XSSFCell timesCell = nextRow.createCell(7);
                    int dayDiffer = DbUtils.getDayDiffer(detail.getStartTime(), detail.getEndTime());
                    timesCell.setCellValue(dayDiffer);
                    timesCell.setCellStyle(titleRow.getRowStyle());
                    XSSFCell endCell = nextRow.createCell(9);
                    endCell.setCellValue(dateFormat.format(detail.getEndTime()));
                    endCell.setCellStyle(subtimesCellStyle);
                    XSSFCell remarkCell = nextRow.createCell(10);
                    remarkCell.setCellValue((detail.getRemark()));
                    remarkCell.setCellStyle(titleRow.getRowStyle());
                    if (detail.getFinish()) {
                        XSSFCell finishCell = nextRow.createCell(8);
                        finishCell.setCellValue(dateFormat.format(detail.getFinishTime()));
                        finishCell.setCellStyle(subendTimeCellCellStyle);
                        XSSFCell endScheduleCell = nextRow.createCell(11);
                        endScheduleCell.setCellValue(DbUtils.getDayDiffer(detail.getStartTime(), detail.getFinishTime()));
                        endScheduleCell.setCellStyle(titleRow.getRowStyle());
                    }
                    index = 12;
                    Boolean finish = detail.getFinish();
                    startTime = scheme.getStartTime();
                    start.setTime(scheme.getStartTime());
                    endTime = scheme.getEndTime();
                    while (startTime.before(endTime)) {
                        startTime = start.getTime();
                        Date subStart = detail.getStartTime();
                        Date subEnd = detail.getEndTime();
                        Date lastTime;
                        if (finish && (DbUtils.getDayDiffer(detail.getFinishTime(), detail.getEndTime()) > 0)){
                            lastTime = detail.getFinishTime();
                        }
                        else{
                            lastTime = detail.getEndTime();
                        }
                        if (DbUtils.getDayDiffer(startTime, subStart) <= 0 && DbUtils.getDayDiffer(startTime, subEnd) >= 0) {
                            XSSFCell inTimeCell = nextRow.createCell(index);
                            inTimeCell.setCellStyle(planStyle);
                        }else if(DbUtils.getDayDiffer(startTime, subEnd) <= 0 && DbUtils.getDayDiffer(startTime, lastTime) >= 0){
                            XSSFCell inTimeCell = nextRow.createCell(index);
                            inTimeCell.setCellStyle(exportStyle);
                        }
                        if (detail.getFinish() && DbUtils.getDayDiffer(startTime, detail.getFinishTime()) == 0) {
                            XSSFCell inTimeCell = nextRow.createCell(index);
                            inTimeCell.setCellStyle(cellEndStyle);
                        }
                        index++;
                        start.add(Calendar.DAY_OF_YEAR, 1);
                    }
                }
                startRow++;
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            //默认Excel名称
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("mapping数据.xlsx", "UTF-8"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("{detailId}/download/{fileName}")
    public Result downLoad(@PathVariable String detailId, @PathVariable String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        SchemeDetail detail = schemeDetailService.selectById(detailId);
@@ -108,11 +306,11 @@
        String path = FileUtils.createFile(basePath, scheme.getName(), detail.getType().covert());
        File file = new File(path);
        if(file.exists()){ //判断文件父目录是否存在
        if (file.exists()) { //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(fileName,"UTF-8"));
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
@@ -123,7 +321,7 @@
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
@@ -143,16 +341,17 @@
        }
        return null;
    }
    @RequestMapping("/download/{topicId}")
    public Result downLoadTopic(@PathVariable String topicId, HttpServletResponse response) throws UnsupportedEncodingException {
        Topic topic = topicService.selectById(topicId);
        String path = topic.getAttachment();
        File file = new File(path);
        if(file.exists()){ //判断文件父目录是否存在
        if (file.exists()) { //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(file.getName(),"UTF-8"));
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
@@ -163,7 +362,7 @@
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
@@ -188,11 +387,11 @@
    public Result downLoadPath(@PathVariable String path, HttpServletResponse response) throws UnsupportedEncodingException {
        path = URLDecoder.decode(path, "UTF-8");
        File file = new File(path);
        if(file.exists()){ //判断文件父目录是否存在
        if (file.exists()) { //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(file.getName(),"UTF-8"));
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
@@ -203,7 +402,7 @@
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
@@ -226,10 +425,10 @@
    /**
     * 实现文件上传
     * */
     */
    @RequestMapping("fileUpload/{detailId}")
    @ResponseBody
    public Result fileUpload(@PathVariable String detailId,  @RequestParam("file") MultipartFile file, HttpServletRequest request){
    public Result fileUpload(@PathVariable String detailId, @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String desp = request.getParameter("desp");
        SchemeDetail detail = schemeDetailService.selectById(detailId);
        if (detail == null) {
@@ -239,7 +438,7 @@
            ProjectDeal projectDeal = new ProjectDeal();
            projectDeal.setCreateTime(new Date()).setSchemeId(detail.getParentId())
                    .setSchemeDetailId(detailId).setDesp(desp)
            .setId(DbUtils.getUUID()).insert();
                    .setId(DbUtils.getUUID()).insert();
            detail.setFinish(true);
            detail.setUpdateTime(new Date());
@@ -247,7 +446,7 @@
            detail.updateById();
            return Result.success(CodeMsg.SUCCESS);
        }
        if(file.isEmpty()){
        if (file.isEmpty()) {
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
@@ -263,7 +462,7 @@
        String path = FileUtils.createFile(basePath, scheme.getName(), detail.getType().covert());
        File dest = new File(path + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdirs();
        }
        dest.deleteOnExit();
@@ -299,26 +498,84 @@
        }
    }
    @RequestMapping("topicUpload")
    /**
     * 实现文件上传
     */
    @RequestMapping("/schemeUpload/{id}")
    @ResponseBody
    public Result topicUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String desp = request.getParameter("desp");
        String userId = request.getParameter("userId");
        Topic topic;
        if (StringUtils.isEmpty(id)) {
            topic = new Topic().setId(DbUtils.getUUID()).setTitle(title).setDesp(desp).setUserId(userId).setCreateTime(new Date());
        } else {
            topic = topicService.selectById(id).setTitle(title).setDesp(desp);
    public Result schemeFileUpload(@PathVariable String id, @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Scheme scheme = schemeService.selectById(id);
        if (scheme == null) {
            return Result.error(CodeMsg.SELECT_ERROR);
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        log.info(fileName + "-->" + size);
        String path = topicPath + "/"+ topic.getId() + fileName;
        String path = FileUtils.createFile(basePath, scheme.getName(), null);
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdirs();
        }
        dest.deleteOnExit();
        try {
            dest.createNewFile();
            file.transferTo(dest); //保存文件
            scheme.setAttachment(path + "/" + fileName);
            scheme.updateById();
            return Result.success(CodeMsg.SUCCESS);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Result.error(CodeMsg.OPERATR_ERROR);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Result.error(CodeMsg.OPERATR_ERROR);
        }
    }
    @RequestMapping("topicUpload")
    @ResponseBody
    public Result topicUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
//        new TitleService().setPopulation(population);
        Map<String, String[]> parameterMap = request.getParameterMap();
        String population = request.getParameter("population");
        String exposure = request.getParameter("exposure");
        String comparator = request.getParameter("comparator");
        String outcomes = request.getParameter("outcomes");
        String outcomesOther = request.getParameter("outcomesOther");
        String titleType = request.getParameter("titleType");
        TitleService titleService =new TitleService().setPopulation(population)
                .setExposure(exposure).setComparator(comparator).setOutcomes(outcomes).setOutcomesOther(outcomesOther)
                .setTitleType(titleType);
        String id = titleService.getId();
        String title = titleService.createTitle();
        String userId = request.getParameter("userId");
        Topic topic;
        if (StringUtils.isEmpty(id)) {
            String uuid = DbUtils.getUUID();
            titleService.setId(uuid);
            titleService.setTitle(titleService.createTitle());
            titleService.insert();
            topic = new Topic().setTitleId(uuid).setId(uuid).setUserId(userId).setCreateTime(new Date());
        } else {
            titleService.setTitle(titleService.createTitle());
            titleService.updateById();
            topic = topicService.selectById(id);
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        log.info(fileName + "-->" + size);
        String path = topicPath + "/" + topic.getId() + fileName;
        File dest = new File(path);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdirs();
        }
        dest.deleteOnExit();
@@ -340,35 +597,37 @@
        }
    }
    /**
     * 实现多文件上传
     * */
    @RequestMapping(value="multifileUpload",method= RequestMethod.POST)
    public @ResponseBody String multifileUpload(HttpServletRequest request){
     */
    @RequestMapping(value = "multifileUpload", method = RequestMethod.POST)
    public @ResponseBody
    String multifileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");
        if(files.isEmpty()){
        if (files.isEmpty()) {
            return "false";
        }
        String path = "F:/test" ;
        String path = "F:/test";
        for(MultipartFile file:files){
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            log.info(fileName + "-->" + size);
            if(file.isEmpty()){
            if (file.isEmpty()) {
                return "false";
            }else{
            } else {
                File dest = new File(path + "/" + fileName);
                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                }catch (Exception e) {
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return "false";