Explorar el Código

试卷下载接口修改

wangliang hace 4 años
padre
commit
ba58396531
Se han modificado 17 ficheros con 593 adiciones y 534 borrados
  1. 24 3
      themis-business/src/main/java/com/qmth/themis/business/cache/bean/ExamPaperCacheBean.java
  2. 28 3
      themis-business/src/main/java/com/qmth/themis/business/entity/TEExamPaper.java
  3. 2 1
      themis-business/src/main/java/com/qmth/themis/business/excel/ExportUtils.java
  4. 2 1
      themis-business/src/main/java/com/qmth/themis/business/service/TEExamService.java
  5. 4 1
      themis-business/src/main/java/com/qmth/themis/business/service/impl/TEExamServiceImpl.java
  6. 4 10
      themis-business/src/main/java/com/qmth/themis/business/templete/TaskExportCommon.java
  7. 4 10
      themis-business/src/main/java/com/qmth/themis/business/templete/TaskImportCommon.java
  8. 4 3
      themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskExamPaperImportTemplete.java
  9. 3 3
      themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskExamStudentImportTemplete.java
  10. 2 2
      themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskMarkResultSimpleExportTemplete.java
  11. 2 2
      themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskMarkResultStandardExportTemplete.java
  12. 2 2
      themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskRoomCodeExportTemplete.java
  13. 3 3
      themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskRoomCodeImportTemplete.java
  14. 12 16
      themis-business/src/main/java/com/qmth/themis/business/templete/service/impl/TempleteLogicServiceImpl.java
  15. 1 3
      themis-common/src/main/java/com/qmth/themis/common/contanst/Constants.java
  16. 494 470
      themis-common/src/main/java/com/qmth/themis/common/util/FileUtil.java
  17. 2 1
      themis-exam/src/main/java/com/qmth/themis/exam/api/TEExamController.java

+ 24 - 3
themis-business/src/main/java/com/qmth/themis/business/cache/bean/ExamPaperCacheBean.java

@@ -2,9 +2,11 @@ package com.qmth.themis.business.cache.bean;
 
 import java.io.Serializable;
 
+import com.baomidou.mybatisplus.annotation.TableField;
 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
 import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
 import com.qmth.themis.business.enums.EncryptModeEnum;
+import io.swagger.annotations.ApiModelProperty;
 
 public class ExamPaperCacheBean implements Serializable {
 
@@ -68,6 +70,28 @@ public class ExamPaperCacheBean implements Serializable {
 	// 音频播放次数
 	private Integer audioPlayCount;
 
+	@ApiModelProperty(value = "题干md5")
+	private String paperMd5;
+
+	@ApiModelProperty(value = "结构文件md5")
+	private String structMd5;
+
+	public String getPaperMd5() {
+		return paperMd5;
+	}
+
+	public void setPaperMd5(String paperMd5) {
+		this.paperMd5 = paperMd5;
+	}
+
+	public String getStructMd5() {
+		return structMd5;
+	}
+
+	public void setStructMd5(String structMd5) {
+		this.structMd5 = structMd5;
+	}
+
 	public Long getId() {
 		return id;
 	}
@@ -223,7 +247,4 @@ public class ExamPaperCacheBean implements Serializable {
 	public void setTotalSubjectiveScore(Double totalSubjectiveScore) {
 		this.totalSubjectiveScore = totalSubjectiveScore;
 	}
-
-	
-
 }

+ 28 - 3
themis-business/src/main/java/com/qmth/themis/business/entity/TEExamPaper.java

@@ -42,6 +42,10 @@ public class TEExamPaper extends BaseEntity {
     @ApiModelProperty(value = "题干路径")
     @TableField(value = "paper_path")
     private String paperPath;
+
+    @ApiModelProperty(value = "题干md5")
+    @TableField(value = "paper_md5")
+    private String paperMd5;
     
     @ApiModelProperty(value = "阅卷用试卷json路径")
     @TableField(value = "paper_view_path")
@@ -92,6 +96,10 @@ public class TEExamPaper extends BaseEntity {
     @TableField(value = "struct_path")
     private String structPath;
 
+    @ApiModelProperty(value = "结构文件md5")
+    @TableField(value = "struct_md5")
+    private String structMd5;
+
     @ApiModelProperty(value = "解密向量")
     @TableField(value = "decrypt_vector")
     private String decryptVector;
@@ -239,7 +247,24 @@ public class TEExamPaper extends BaseEntity {
 	public void setTotalSubjectiveScore(Double totalSubjectiveScore) {
 		this.totalSubjectiveScore = totalSubjectiveScore;
 	}
-    
-	
-    
+
+    public static long getSerialVersionUID() {
+        return serialVersionUID;
+    }
+
+    public String getPaperMd5() {
+        return paperMd5;
+    }
+
+    public void setPaperMd5(String paperMd5) {
+        this.paperMd5 = paperMd5;
+    }
+
+    public String getStructMd5() {
+        return structMd5;
+    }
+
+    public void setStructMd5(String structMd5) {
+        this.structMd5 = structMd5;
+    }
 }

+ 2 - 1
themis-business/src/main/java/com/qmth/themis/business/excel/ExportUtils.java

@@ -7,6 +7,7 @@ import java.util.Collection;
 import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletResponse;
 
+import com.qmth.themis.common.contanst.Constants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -24,7 +25,7 @@ public class ExportUtils {
     public static void exportEXCEL(String fileName,Class<?> dataClass,
                              Collection<?> dataset,HttpServletResponse response) throws Exception {
     	log.debug("导出Excel开始...");
-        response.setHeader("Content-Disposition","inline;filename="+URLEncoder.encode(fileName, "UTF-8")+DEFALUT_EXT);
+        response.setHeader("Content-Disposition","inline;filename="+URLEncoder.encode(fileName, Constants.CHARSET_NAME)+DEFALUT_EXT);
         response.setContentType(DEFALUT_CONTENT_TYPE);
         ServletOutputStream outputStream = response.getOutputStream();
     	

+ 2 - 1
themis-business/src/main/java/com/qmth/themis/business/service/TEExamService.java

@@ -15,6 +15,7 @@ import com.qmth.themis.business.enums.ScoreStatusEnum;
 import com.qmth.themis.business.enums.SystemOperationEnum;
 import org.springframework.web.multipart.MultipartFile;
 
+import java.io.IOException;
 import java.util.List;
 import java.util.Map;
 
@@ -172,7 +173,7 @@ public interface TEExamService extends IService<TEExam> {
      * @param recordId
      * @return
      */
-    public ExamPaperDownloadBean paperDownload(Long recordId);
+    public ExamPaperDownloadBean paperDownload(Long recordId) throws IOException;
 
     /**
      * 监考端获取考试批次列表

+ 4 - 1
themis-business/src/main/java/com/qmth/themis/business/service/impl/TEExamServiceImpl.java

@@ -42,6 +42,7 @@ import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
 import java.text.SimpleDateFormat;
 import java.util.*;
 import java.util.regex.Matcher;
@@ -1222,7 +1223,7 @@ public class TEExamServiceImpl extends ServiceImpl<TEExamMapper, TEExam> impleme
      * @return
      */
     @Override
-    public ExamPaperDownloadBean paperDownload(Long recordId) {
+    public ExamPaperDownloadBean paperDownload(Long recordId) throws IOException {
         Long paperId = ExamRecordCacheUtil.getPaperId(recordId);
         ExamPaperCacheBean ep = teExamPaperService.getExamPaperCacheBean(paperId);
         if (Objects.isNull(ep)) {
@@ -1230,7 +1231,9 @@ public class TEExamServiceImpl extends ServiceImpl<TEExamMapper, TEExam> impleme
         }
         ExamPaperDownloadBean ret = new ExamPaperDownloadBean();
         ret.setPaperUrl(ossUtil.getPrivateUrl(ep.getPaperPath()));
+        ret.setPaperMd5(BinaryUtil.encodeMD5(ossUtil.download(false, ep.getPaperPath())));
         ret.setStructUrl(ossUtil.getPrivateUrl(ep.getStructPath()));
+        ret.setStructMd5(BinaryUtil.encodeMD5(ossUtil.download(false, ep.getStructPath())));
         return ret;
     }
 

+ 4 - 10
themis-business/src/main/java/com/qmth/themis/business/templete/TaskExportCommon.java

@@ -11,6 +11,7 @@ import com.qmth.themis.business.enums.UploadFileEnum;
 import com.qmth.themis.business.service.TBAttachmentService;
 import com.qmth.themis.business.service.TBTaskHistoryService;
 import com.qmth.themis.business.util.OssUtil;
+import com.qmth.themis.common.contanst.Constants;
 import org.apache.poi.ss.usermodel.Cell;
 import org.apache.poi.ss.usermodel.CellStyle;
 import org.apache.poi.ss.usermodel.Row;
@@ -18,6 +19,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.io.*;
+import java.nio.charset.StandardCharsets;
 import java.util.*;
 
 /**
@@ -45,8 +47,6 @@ public class TaskExportCommon {
 
     private TBTaskHistory tbTaskHistory = null;
 
-    private String timeFormat = null;
-
     private boolean exception = false;
 
     private TBAttachmentService tbAttachmentService = null;
@@ -80,9 +80,7 @@ public class TaskExportCommon {
         this.tbTaskHistory = gson.fromJson(gson.toJson(tbTaskHistoryMap), TBTaskHistory.class);
         this.tbTaskHistoryService = SpringContextHolder.getBean(TBTaskHistoryService.class);
         this.tbAttachmentService = SpringContextHolder.getBean(TBAttachmentService.class);
-        this.timeFormat = "yyyy-MM-dd HH:mm:ss";
         map.put("tbTaskHistory", tbTaskHistory);
-        map.put("timeFormat", timeFormat);
     }
 
     /**
@@ -149,7 +147,7 @@ public class TaskExportCommon {
         InputStream inputStream = null;
         try {
             out = new ByteArrayOutputStream();
-            out.write(txtStr.getBytes("UTF-8"));
+            out.write(txtStr.getBytes(StandardCharsets.UTF_8));
             byte[] bookByteAry = out.toByteArray();
             inputStream = new ByteArrayInputStream(bookByteAry);
             JSONObject json = new JSONObject();
@@ -196,7 +194,7 @@ public class TaskExportCommon {
     public List<String> exception(int min, int y, Exception e, List<String> txtList) {
         this.exception = true;
         String exceptionStr = "数据导出到第" + (y == 0 ? y + 1 : y) + "条时发生异常,请联系系统管理员处理!";
-        txtList.add(DateUtil.format(new Date(), this.timeFormat) + "->" + exceptionStr);
+        txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->" + exceptionStr);
         this.tbTaskHistory.setSummary(exceptionStr);
         this.tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
         return txtList;
@@ -210,10 +208,6 @@ public class TaskExportCommon {
         return exception;
     }
 
-    public String getTimeFormat() {
-        return timeFormat;
-    }
-
     public Map<String, Object> getMap() {
         return map;
     }

+ 4 - 10
themis-business/src/main/java/com/qmth/themis/business/templete/TaskImportCommon.java

@@ -9,10 +9,12 @@ import com.qmth.themis.business.entity.TBTaskHistory;
 import com.qmth.themis.business.enums.TaskStatusEnum;
 import com.qmth.themis.business.service.TBTaskHistoryService;
 import com.qmth.themis.business.util.OssUtil;
+import com.qmth.themis.common.contanst.Constants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.io.*;
+import java.nio.charset.StandardCharsets;
 import java.util.*;
 
 /**
@@ -50,8 +52,6 @@ public class TaskImportCommon {
 
     private TBTaskHistory tbTaskHistory = null;
 
-    private String timeFormat = null;
-
     private boolean exception = false;
 
     private List<String> txtList = null;
@@ -89,9 +89,7 @@ public class TaskImportCommon {
         Map tbTaskHistoryMap = (Map) this.map.get("tbTaskHistory");
         this.tbTaskHistory = gson.fromJson(gson.toJson(tbTaskHistoryMap), TBTaskHistory.class);
         this.tbTaskHistoryService = SpringContextHolder.getBean(TBTaskHistoryService.class);
-        this.timeFormat = "yyyy-MM-dd HH:mm:ss";
         map.put("tbTaskHistory", tbTaskHistory);
-        map.put("timeFormat", timeFormat);
     }
 
     /**
@@ -142,7 +140,7 @@ public class TaskImportCommon {
         InputStream inputStream = null;
         try {
             out = new ByteArrayOutputStream();
-            out.write(txtStr.getBytes("UTF-8"));
+            out.write(txtStr.getBytes(StandardCharsets.UTF_8));
             byte[] bookByteAry = out.toByteArray();
             inputStream = new ByteArrayInputStream(bookByteAry);
             StringJoiner stringJoiner = new StringJoiner("");
@@ -182,7 +180,7 @@ public class TaskImportCommon {
     public List<String> exception(int min, Exception e, List<String> txtList) {
         this.exception = true;
         String exceptionStr = "数据处理到第" + (min == 0 ? min + 1 : min) + "条时发生异常,请联系系统管理员处理!";
-        txtList.add(DateUtil.format(new Date(), this.timeFormat) + "->" + exceptionStr);
+        txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->" + exceptionStr);
         this.tbTaskHistory.setSummary(exceptionStr);
         this.tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
         return txtList;
@@ -205,10 +203,6 @@ public class TaskImportCommon {
         return exception;
     }
 
-    public String getTimeFormat() {
-        return timeFormat;
-    }
-
     public String getMode() {
         return mode;
     }

+ 4 - 3
themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskExamPaperImportTemplete.java

@@ -21,6 +21,7 @@ import com.qmth.themis.business.templete.TaskImportTemplete;
 import com.qmth.themis.business.util.OssUtil;
 import com.qmth.themis.business.util.RedisUtil;
 import com.qmth.themis.business.util.UidUtil;
+import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.enums.ExceptionResultEnum;
 import com.qmth.themis.common.exception.BusinessException;
 import com.qmth.themis.common.util.FileUtil;
@@ -83,8 +84,7 @@ public class TaskExamPaperImportTemplete implements TaskImportTemplete {
         TaskImportCommon taskImportCommon = new TaskImportCommon(map);
         taskImportCommon.init();
         StringBuilder result = new StringBuilder();
-        String timeFormat = taskImportCommon.getTimeFormat();
-        addResult(result, DateUtil.format(new Date(), timeFormat) + "处理开始");
+        addResult(result, DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "处理开始");
         File file = null;
         try {
             file = taskImportCommon.getUploadFile();
@@ -99,7 +99,7 @@ public class TaskExamPaperImportTemplete implements TaskImportTemplete {
             if (file != null) {
                 file.delete();
             }
-            addResult(result, DateUtil.format(new Date(), timeFormat) + "处理结束");
+            addResult(result, DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "处理结束");
             long end = System.currentTimeMillis();
             addResult(result, "耗时(秒):" + ((end - start) / 1000));
             taskImportCommon.getTbTaskHistory().setFinishTime(System.currentTimeMillis());
@@ -396,6 +396,7 @@ public class TaskExamPaperImportTemplete implements TaskImportTemplete {
         FileUtil.encryptFile(zip, encryptZip, paper.getDecryptSecret(), paper.getDecryptVector());
         String filePath = sdf.format(new Date()) + "/" + uuid() + ".zip";
         paper.setPaperPath(filePath);
+        paper.setPaperMd5(BinaryUtil.encodeMD5(FileUtil.fileConvertToByteArray(encryptZip)));
         ossUtil.upload(false, filePath, encryptZip);
     }
 

+ 3 - 3
themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskExamStudentImportTemplete.java

@@ -15,6 +15,7 @@ import com.qmth.themis.business.util.ExcelCallback;
 import com.qmth.themis.business.util.ExcelError;
 import com.qmth.themis.business.util.ExcelUtil;
 import com.qmth.themis.business.util.JacksonUtil;
+import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.exception.BusinessException;
 import com.qmth.themis.common.util.Result;
 import com.qmth.themis.common.util.ResultUtil;
@@ -57,8 +58,7 @@ public class TaskExamStudentImportTemplete implements TaskImportTemplete {
         taskImportCommon.init();
         InputStream inputStream = taskImportCommon.getUploadFileInputStream();
         taskImportCommon.setTxtList(new ArrayList());
-        String timeFormat = taskImportCommon.getTimeFormat();
-        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->开始准备处理导入的考生数据");
+        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->开始准备处理导入的考生数据");
         Map<String, Object> finalMap = map;
         Map<String, TEExamActivity> teExamActivityMap = (Map<String, TEExamActivity>) map.get("teExamActivityMap");
         try {
@@ -90,7 +90,7 @@ public class TaskExamStudentImportTemplete implements TaskImportTemplete {
                         }
                     }
                     if (excelErrorList.size() > 0) {
-                        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->数据校验异常:" + JSONObject.toJSONString(excelErrorList));
+                        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据校验异常:" + JSONObject.toJSONString(excelErrorList));
                         taskImportCommon.setException(true);
                         taskImportCommon.getTbTaskHistory().setFinishTime(System.currentTimeMillis());
                         taskImportCommon.getTbTaskHistory().setProgress(0d);

+ 2 - 2
themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskMarkResultSimpleExportTemplete.java

@@ -15,6 +15,7 @@ import com.qmth.themis.business.service.TOeExamRecordService;
 import com.qmth.themis.business.templete.TaskExportCommon;
 import com.qmth.themis.business.templete.TaskExportTemplete;
 import com.qmth.themis.business.templete.service.TempleteLogicService;
+import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.util.Result;
 import com.qmth.themis.common.util.ResultUtil;
 import org.apache.poi.ss.usermodel.*;
@@ -65,7 +66,6 @@ public class TaskMarkResultSimpleExportTemplete implements TaskExportTemplete {
         long start = System.currentTimeMillis();
         TaskExportCommon taskExportCommon = new TaskExportCommon(map);
         taskExportCommon.init();
-        String timeFormat = taskExportCommon.getTimeFormat();
         taskExportCommon.setTxtList(new ArrayList());
         SXSSFWorkbook wb = null;
         StringJoiner stringJoiner = null;
@@ -74,7 +74,7 @@ public class TaskMarkResultSimpleExportTemplete implements TaskExportTemplete {
         ByteArrayOutputStream out = null;
         int y = 0, min = 0;
         try {
-            taskExportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->开始准备处理导出的成绩简版数据");
+            taskExportCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->开始准备处理导出的成绩简版数据");
             Long examId = (Long) map.get("examId");
             Long activityId = (Long) map.get("activityId");
             String identity = (String) map.get("identity");

+ 2 - 2
themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskMarkResultStandardExportTemplete.java

@@ -21,6 +21,7 @@ import com.qmth.themis.business.service.*;
 import com.qmth.themis.business.templete.TaskExportCommon;
 import com.qmth.themis.business.templete.TaskExportTemplete;
 import com.qmth.themis.business.templete.service.TempleteLogicService;
+import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.util.Result;
 import com.qmth.themis.common.util.ResultUtil;
 import org.apache.poi.ss.usermodel.*;
@@ -77,7 +78,6 @@ public class TaskMarkResultStandardExportTemplete implements TaskExportTemplete
         long start = System.currentTimeMillis();
         TaskExportCommon taskExportCommon = new TaskExportCommon(map);
         taskExportCommon.init();
-        String timeFormat = taskExportCommon.getTimeFormat();
         taskExportCommon.setTxtList(new ArrayList());
         SXSSFWorkbook wb = null;
         StringJoiner stringJoiner = null;
@@ -86,7 +86,7 @@ public class TaskMarkResultStandardExportTemplete implements TaskExportTemplete
         ByteArrayOutputStream out = null;
         int y = 0, min = 0;
         try {
-            taskExportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->开始准备处理导出的成绩标准版数据");
+            taskExportCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->开始准备处理导出的成绩标准版数据");
             Long examId = (Long) map.get("examId");
             Long activityId = (Long) map.get("activityId");
             String identity = (String) map.get("identity");

+ 2 - 2
themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskRoomCodeExportTemplete.java

@@ -8,6 +8,7 @@ import com.qmth.themis.business.service.TBExamInvigilateUserService;
 import com.qmth.themis.business.templete.TaskExportCommon;
 import com.qmth.themis.business.templete.TaskExportTemplete;
 import com.qmth.themis.business.templete.service.TempleteLogicService;
+import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.util.Result;
 import com.qmth.themis.common.util.ResultUtil;
 import org.apache.poi.ss.usermodel.*;
@@ -51,7 +52,6 @@ public class TaskRoomCodeExportTemplete implements TaskExportTemplete {
         long start = System.currentTimeMillis();
         TaskExportCommon taskExportCommon = new TaskExportCommon(map);
         taskExportCommon.init();
-        String timeFormat = taskExportCommon.getTimeFormat();
         taskExportCommon.setTxtList(new ArrayList());
         SXSSFWorkbook wb = null;
         StringJoiner stringJoiner = null;
@@ -60,7 +60,7 @@ public class TaskRoomCodeExportTemplete implements TaskExportTemplete {
         ByteArrayOutputStream out = null;
         int y = 0, min = 0;
         try {
-            taskExportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->开始准备处理导出的考场数据");
+            taskExportCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->开始准备处理导出的考场数据");
             Long examId = (Long) map.get("examId");
             String roomCode = (String) map.get("roomCode");
             Long userId = (Long) map.get("userId");

+ 3 - 3
themis-business/src/main/java/com/qmth/themis/business/templete/impl/TaskRoomCodeImportTemplete.java

@@ -12,6 +12,7 @@ import com.qmth.themis.business.templete.service.TempleteLogicService;
 import com.qmth.themis.business.util.ExcelCallback;
 import com.qmth.themis.business.util.ExcelError;
 import com.qmth.themis.business.util.ExcelUtil;
+import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.exception.BusinessException;
 import com.qmth.themis.common.util.Result;
 import com.qmth.themis.common.util.ResultUtil;
@@ -53,8 +54,7 @@ public class TaskRoomCodeImportTemplete implements TaskImportTemplete {
         taskImportCommon.init();
         InputStream inputStream = taskImportCommon.getUploadFileInputStream();
         taskImportCommon.setTxtList(new ArrayList());
-        String timeFormat = taskImportCommon.getTimeFormat();
-        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->开始准备处理导入的考场数据");
+        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->开始准备处理导入的考场数据");
         try {
             List<LinkedMultiValueMap<Integer, Object>> finalList = ExcelUtil.excelReader(inputStream, Lists.newArrayList(RoomCodeImportDto.class), new ExcelCallback() {
                 @Override
@@ -72,7 +72,7 @@ public class TaskRoomCodeImportTemplete implements TaskImportTemplete {
                         }
                     }
                     if (excelErrorList.size() > 0) {
-                        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->数据校验异常:" + JSONObject.toJSONString(excelErrorList));
+                        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据校验异常:" + JSONObject.toJSONString(excelErrorList));
                         taskImportCommon.setException(true);
                         taskImportCommon.getTbTaskHistory().setFinishTime(System.currentTimeMillis());
                         taskImportCommon.getTbTaskHistory().setProgress(0d);

+ 12 - 16
themis-business/src/main/java/com/qmth/themis/business/templete/service/impl/TempleteLogicServiceImpl.java

@@ -13,6 +13,7 @@ import com.qmth.themis.business.enums.RoleEnum;
 import com.qmth.themis.business.enums.TaskStatusEnum;
 import com.qmth.themis.business.service.*;
 import com.qmth.themis.business.templete.service.TempleteLogicService;
+import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.exception.BusinessException;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
@@ -67,7 +68,6 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
         Long createId = Long.parseLong(String.valueOf(map.get("createId")));
         List<String> txtList = (List<String>) map.get("txtList");
         TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
-        String timeFormat = String.valueOf(map.get("timeFormat"));
         List<TEExamStudent> teExamStudentList = new ArrayList<>();
         List<TEStudent> teStudentList = new ArrayList<>();
         List<TBExamInvigilateUser> tbExamInvigilateUserList = new ArrayList<>();
@@ -168,7 +168,7 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
                     roomCodeAndNameSet.add(examId + ":" + teExamStudent.getRoomCode() + ":" + teExamStudent.getRoomName());
                     teExamStudentList.add(teExamStudent);
                 }
-                txtList = this.importProgress(max, min, size, txtList, tbTaskHistory, timeFormat);
+                txtList = this.importProgress(max, min, size, txtList, tbTaskHistory);
                 map.put("min", min);
                 if (max == size) {
                     break;
@@ -197,7 +197,7 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
             });
             tbExamInvigilateUserService.saveOrUpdateBatch(tbExamInvigilateUserList);
             if (count.get() > 0) {
-                txtList.add(DateUtil.format(new Date(), timeFormat) + "->创建了" + count + "条考场数据");
+                txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->创建了" + count + "条考场数据");
             }
         }
         return map;
@@ -224,7 +224,6 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
         List<TBUserRole> tbUserRoleList = new ArrayList<>();
         List<TBExamInvigilateUser> tbExamInvigilateUserList = new ArrayList<>();
         TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
-        String timeFormat = String.valueOf(map.get("timeFormat"));
         //保存用户
         for (int i = 0; i < finalList.size(); i++) {
             LinkedMultiValueMap<Integer, Object> finalMap = finalList.get(i);
@@ -242,7 +241,7 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
                     dataVerify(examId, roomCodeImportDto.getTeacher2(), roomCodeImportDto.getRoomCode(), roomCodeImportDto.getRoomName(), orgId, createId, tbUserList, tbUserRoleList, tbExamInvigilateUserList);
                     dataVerify(examId, roomCodeImportDto.getTeacher3(), roomCodeImportDto.getRoomCode(), roomCodeImportDto.getRoomName(), orgId, createId, tbUserList, tbUserRoleList, tbExamInvigilateUserList);
                 }
-                txtList = this.importProgress(max, min, size, txtList, tbTaskHistory, timeFormat);
+                txtList = this.importProgress(max, min, size, txtList, tbTaskHistory);
                 if (max == size) {
                     break;
                 }
@@ -359,21 +358,20 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
      * @param size
      * @param txtList
      * @param tbTaskHistory
-     * @param timeFormat
      * @return
      */
-    public List<String> importProgress(int max, int min, int size, List<String> txtList, TBTaskHistory tbTaskHistory, String timeFormat) {
+    public List<String> importProgress(int max, int min, int size, List<String> txtList, TBTaskHistory tbTaskHistory) {
         BigDecimal bigDecimal = new BigDecimal(100);
         BigDecimal progress = new BigDecimal(Double.valueOf(new BigDecimal(max).divide(new BigDecimal(size), 2, BigDecimal.ROUND_HALF_UP).multiply(bigDecimal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())).setScale(0, BigDecimal.ROUND_HALF_UP);
         if (progress.intValue() == 100) {
             tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
             tbTaskHistory.setSummary("共处理了" + size + "条数据");
             tbTaskHistory.setFinishTime(System.currentTimeMillis());
-            txtList.add(DateUtil.format(new Date(), timeFormat) + "->数据处理完毕," + tbTaskHistory.getSummary());
+            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据处理完毕," + tbTaskHistory.getSummary());
         } else {
             tbTaskHistory.setStatus(TaskStatusEnum.RUNNING);
             tbTaskHistory.setSummary("正在处理第" + min + "条至" + max + "条数据");
-            txtList.add(DateUtil.format(new Date(), timeFormat) + "->数据处理中," + tbTaskHistory.getSummary());
+            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据处理中," + tbTaskHistory.getSummary());
         }
         tbTaskHistory.setProgress(progress.doubleValue());
         return txtList;
@@ -387,10 +385,9 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
      * @param size
      * @param txtList
      * @param tbTaskHistory
-     * @param timeFormat
      * @return
      */
-    public List<String> exportProgress(int max, int min, int size, List<String> txtList, TBTaskHistory tbTaskHistory, String timeFormat) {
+    public List<String> exportProgress(int max, int min, int size, List<String> txtList, TBTaskHistory tbTaskHistory) {
         BigDecimal bigDecimal = new BigDecimal(100);
         BigDecimal progress = null;
         if (size > 0) {
@@ -402,16 +399,16 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
             tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
             tbTaskHistory.setSummary("共导出了" + size + "条数据");
             tbTaskHistory.setFinishTime(System.currentTimeMillis());
-            txtList.add(DateUtil.format(new Date(), timeFormat) + "->数据导出完毕," + tbTaskHistory.getSummary());
+            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据导出完毕," + tbTaskHistory.getSummary());
         } else if (progress.intValue() == -1) {
             tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
             tbTaskHistory.setSummary("没有导出数据");
             tbTaskHistory.setFinishTime(System.currentTimeMillis());
-            txtList.add(DateUtil.format(new Date(), timeFormat) + "->数据导出完毕," + tbTaskHistory.getSummary());
+            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据导出完毕," + tbTaskHistory.getSummary());
         } else {
             tbTaskHistory.setStatus(TaskStatusEnum.RUNNING);
             tbTaskHistory.setSummary("正在导出第" + min + "条至" + max + "条数据");
-            txtList.add(DateUtil.format(new Date(), timeFormat) + "->数据导出中," + tbTaskHistory.getSummary());
+            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据导出中," + tbTaskHistory.getSummary());
         }
         tbTaskHistory.setProgress(progress.doubleValue());
         return txtList;
@@ -429,8 +426,7 @@ public class TempleteLogicServiceImpl implements TempleteLogicService {
         Integer max = Integer.parseInt(String.valueOf(map.get("max")));
         Integer min = Integer.parseInt(String.valueOf(map.get("min")));
         Integer size = Integer.parseInt(String.valueOf(map.get("size")));
-        String timeFormat = String.valueOf(map.get("timeFormat"));
-        this.exportProgress(max, min, size, txtList, tbTaskHistory, timeFormat);
+        this.exportProgress(max, min, size, txtList, tbTaskHistory);
         return map;
     }
 }

+ 1 - 3
themis-common/src/main/java/com/qmth/themis/common/contanst/Constants.java

@@ -4,8 +4,6 @@ import java.nio.charset.Charset;
 
 public interface Constants {
 
-    public static final String CLOUD_HOST = "https://www.teach-cloud.com";
-
     public static final int SIGNATURE_EXPIRE_SECONDS = 15;
 
     public static final int SIGNATURE_AHEAD_SECONDS = 5;
@@ -14,7 +12,7 @@ public interface Constants {
 
     public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
 
-    public static final String CHARSET_NAME = "utf8";
+    public static final String CHARSET_NAME = "UTF-8";
 
     public static final Charset CHARSET = Charset.forName(CHARSET_NAME);
 

+ 494 - 470
themis-common/src/main/java/com/qmth/themis/common/util/FileUtil.java

@@ -1,483 +1,507 @@
 package com.qmth.themis.common.util;
 
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
+import com.qmth.themis.common.contanst.Constants;
+import com.qmth.themis.common.exception.BusinessException;
+import org.apache.commons.io.IOUtils;
+
+import javax.crypto.Cipher;
+import javax.crypto.CipherOutputStream;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.*;
 import java.net.HttpURLConnection;
 import java.net.URL;
-import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
 import java.util.Enumeration;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Objects;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
 import java.util.zip.ZipOutputStream;
 
-import javax.crypto.Cipher;
-import javax.crypto.CipherOutputStream;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-
-import org.apache.commons.io.IOUtils;
-
-import com.qmth.themis.common.exception.BusinessException;
-
 public class FileUtil {
-	/**
-	 * 将网络文件保存到本地
-	 *
-	 * @param fileUrl       网络文件URL
-	 * @param localFilePath 例如D:/123.txt
-	 * @throws IOException
-	 */
-	public static void saveUrlAsFile(String fileUrl, String localFilePath) {
-		HttpURLConnection connection = null;
-		DataOutputStream dataOutputStream = null;
-		DataInputStream dataInputStream = null;
-		try {
-			URL url = new URL(fileUrl);
-
-			connection = (HttpURLConnection) url.openConnection();
-
-			dataInputStream = new DataInputStream(connection.getInputStream());
-			FileOutputStream fileOutputStream = new FileOutputStream(localFilePath);
-			dataOutputStream = new DataOutputStream(fileOutputStream);
-
-			byte[] buffer = new byte[4096];
-			int count;
-			while ((count = dataInputStream.read(buffer)) > 0) {
-				dataOutputStream.write(buffer, 0, count);
-			}
-			fileOutputStream.flush();
-			dataOutputStream.flush();
-		} catch (IOException e) {
-			throw new BusinessException("下载文件出错" + e.getMessage());
-		} finally {
-			if (connection != null) {
-				connection.disconnect();
-			}
-			if (dataOutputStream != null) {
-				try {
-					dataOutputStream.close();
-				} catch (IOException e) {
-				}
-			}
-			if (dataInputStream != null) {
-				try {
-					dataInputStream.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-	}
-
-	/**
-	 * 将网络文件保存到本地
-	 * 
-	 * @param fileUrl   网络文件URL
-	 * @param localFile 本地文件对象
-	 * @throws IOException
-	 */
-	public static void saveUrlAsFile(String fileUrl, File localFile) {
-
-		saveUrlAsFile(fileUrl, localFile.getAbsolutePath());
-	}
-
-	/**
-	 * 读取文件内容
-	 *
-	 * @param file
-	 * @return
-	 * @throws IOException
-	 */
-	public static String readFileContent(File file) {
-		StringBuilder content = new StringBuilder();
-		InputStreamReader streamReader = null;
-		BufferedReader bufferedReader = null;
-		try {
-			String encoding = "UTF-8";
-			if (file.exists() && file.isFile()) {
-				streamReader = new InputStreamReader(new FileInputStream(file), encoding);
-				bufferedReader = new BufferedReader(streamReader);
-				String line;
-				while ((line = bufferedReader.readLine()) != null) {
-					content.append(line);
-				}
-			}
-		} catch (IOException e) {
-			throw new BusinessException("读取文件出错" + e.getMessage());
-		} finally {
-			if (streamReader != null) {
-				try {
-					streamReader.close();
-				} catch (IOException e) {
-				}
-			}
-			if (bufferedReader != null) {
-				try {
-					bufferedReader.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-		return content.toString();
-	}
-
-	/**
-	 * 创建文件目录
-	 */
-	public static boolean makeDirs(String path) {
-		if (path == null || "".equals(path)) {
-			return false;
-		}
-		File folder = new File(path);
-		if (!folder.exists()) {
-			return folder.mkdirs();
-		}
-		return true;
-	}
-
-	/**
-	 * 保存字符串到文件中 @throws IOException @throws
-	 */
-	public static void saveAsFile(String path, String content) {
-		saveAsFile(path, content, null);
-	}
-
-	public static void saveAsFile(String path, String content, String encoding) {
-		if (path == null || content == null) {
-			return;
-		}
-
-		if (encoding == null) {
-			encoding = "UTF-8";
-		}
-		BufferedWriter bw = null;
-		try {
-			File file = new File(path);
-			if (!file.exists()) {
-				if (FileUtil.makeDirs(file.getParent())) {
-					boolean ok = file.createNewFile();
-					if (!ok) {
-						throw new BusinessException("文件创建失败!");
-					}
-				}
-			}
-
-			FileOutputStream fos = new FileOutputStream(file);
-			OutputStreamWriter write = new OutputStreamWriter(fos, encoding);
-			bw = new BufferedWriter(write);
-			bw.write(content);
-			bw.flush();
-		} catch (IOException e) {
-			throw new BusinessException("保存文件出错" + e.getMessage());
-		} finally {
-			if (bw != null) {
-				try {
-					bw.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-	}
-
-	/**
-	 * 解压文件
-	 *
-	 * @param targetDir 解压目录
-	 * @param zipFile   待解压的ZIP文件
-	 * @throws IOException
-	 */
-	public static List<File> unZip(File targetDir, File zipFile) throws IOException {
-		if (targetDir == null) {
-			throw new BusinessException("解压目录不能为空!");
-		}
-
-		if (zipFile == null) {
-			throw new BusinessException("待解压的文件不能为空!");
-		}
-
-		if (!zipFile.exists()) {
-			throw new BusinessException("待解压的文件不存在!" + zipFile.getAbsolutePath());
-		}
-
-		String zipName = zipFile.getName().toLowerCase();
-		if (zipFile.isDirectory() || zipName.indexOf(".zip") < 0) {
-			throw new BusinessException("待解压的文件格式错误!");
-		}
-
-		if (!targetDir.exists()) {
-			targetDir.mkdir();
-		}
-
-		List<File> result = new LinkedList<>();
-
-		try (ZipFile zip = new ZipFile(zipFile, Charset.forName("UTF-8"));) {
-
-			Enumeration entries = zip.entries();
-			while (entries.hasMoreElements()) {
-				ZipEntry entry = (ZipEntry) entries.nextElement();
-
-				// Linux中需要替换掉路径的反斜杠
-				String entryName = (File.separator + entry.getName()).replaceAll("\\\\", "/");
-
-				String filePath = targetDir.getAbsolutePath() + entryName;
-				File target = new File(filePath);
-				if (entry.isDirectory()) {
-					target.mkdirs();
-				} else {
-					File dir = target.getParentFile();
-					if (!dir.exists()) {
-						dir.mkdirs();
-					}
-
-					try (OutputStream os = new FileOutputStream(target); InputStream is = zip.getInputStream(entry);) {
-						IOUtils.copy(is, os);
-						os.flush();
-					}
-					result.add(target);
-				}
-			}
-
-		}
-
-		return result;
-	}
-
-	/**
-	 * 文件压缩
-	 *
-	 * @param target 目录或文件 @param zipFile 压缩后的ZIP文件 @throws IOException @throws
-	 */
-	public static boolean doZip(File target, File zipFile) throws IOException {
-		if (target == null || !target.exists()) {
-			throw new BusinessException("目录或文件不能为空!");
-		}
-
-		if (zipFile == null) {
-			throw new BusinessException("待压缩的文件不能为空!");
-		}
-
-		try (OutputStream outStream = new FileOutputStream(zipFile);
-				ZipOutputStream zipOutStream = new ZipOutputStream(outStream, Charset.forName("UTF-8"));) {
-			if (!zipFile.exists()) {
-				boolean ok = zipFile.createNewFile();
-				if (!ok) {
-					throw new BusinessException("压缩的文件创建失败!");
-				}
-			}
-
-			if (target.isDirectory()) {
-				File[] files = target.listFiles();
-				if (files.length == 0) {
-					throw new BusinessException("文件夹内未找到任何文件!");
-				}
-
-				for (File file : files) {
-					doZip(zipOutStream, file, null);
-				}
-			} else {
-				doZip(zipOutStream, target, null);
-			}
-		}
-
-		return true;
-	}
-
-	/**
-	 * @param resultFile
-	 * @param sourseFiles
-	 * @return
-	 * @throws IOException
-	 */
-	public static boolean doZip(File resultFile, List<File> sourseFiles) {
-		if (sourseFiles == null || sourseFiles.size() == 0) {
-			throw new BusinessException("待压缩的文件不能为空!");
-		}
-
-		if (resultFile == null) {
-			throw new BusinessException("压缩后的文件不能为空!");
-		}
-		ZipOutputStream zipOutStream = null;
-		try {
-			OutputStream outStream = new FileOutputStream(resultFile);
-			zipOutStream = new ZipOutputStream(outStream, Charset.forName("UTF-8"));
-			if (!resultFile.exists()) {
-				boolean ok = resultFile.createNewFile();
-				if (!ok) {
-					throw new BusinessException("压缩的文件创建失败!");
-				}
-			}
-
-			for (File file : sourseFiles) {
-				doZip(zipOutStream, file, null);
-			}
-		} catch (IOException e) {
-			throw new BusinessException("压缩的文件创建失败!" + e.getMessage());
-		} finally {
-			if (zipOutStream != null) {
-				try {
-					zipOutStream.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-
-		return true;
-	}
-
-	private static void doZip(ZipOutputStream zipOutStream, File target, String parentDir) throws IOException {
-		if (parentDir == null) {
-			parentDir = "";
-		}
-
-		if (!"".equals(parentDir) && !parentDir.endsWith(File.separator)) {
-			parentDir += File.separator;
-		}
-
-		if (target.isDirectory()) {
-			File[] files = target.listFiles();
-			if (files.length > 0) {
-				for (File file : files) {
-					doZip(zipOutStream, file, parentDir + target.getName());
-				}
-			} else {
-				zipOutStream.putNextEntry(new ZipEntry(parentDir + target.getName()));
-				zipOutStream.closeEntry();
-			}
-		} else {
-			try (InputStream is = new FileInputStream(target);) {
-				zipOutStream.putNextEntry(new ZipEntry(parentDir + target.getName()));
-				int len;
-				byte[] bytes = new byte[1024];
-				while ((len = is.read(bytes)) > 0) {
-					zipOutStream.write(bytes, 0, len);
-				}
-			}
-			zipOutStream.closeEntry();
-		}
-	}
-
-	public static void deleteFolder(String path) {
-
-		File file = new File(path);
-		if (file.exists()) {
-			if (file.isFile()) {
-				deleteFile(path);
-			} else {
-				deleteDirectory(path);
-			}
-		}
-	}
-
-	public static void deleteFile(String path) {
-		File file = new File(path);
-		deleteFile(file);
-	}
-	public static void deleteFile(File file) {
-		if (file.isFile() && file.exists()) {
-			file.delete();
-		}
-	}
-	public static void deleteDirectory(File dirFile) {
-		if (!dirFile.exists() || !dirFile.isDirectory()) {
-			return;
-		}
-		File[] files = dirFile.listFiles();
-		if (files != null) {
-			for (int i = 0; i < files.length; i++) {
-				if (files[i].isFile()) {
-					deleteFile(files[i]);
-				} else {
-					deleteDirectory(files[i]);
-				}
-			}
-		}
-
-		dirFile.delete();
-	}
-	public static void deleteDirectory(String path) {
-		if (!path.endsWith(File.separator)) {
-			path = path + File.separator;
-		}
-		File dirFile = new File(path);
-		deleteDirectory(dirFile);
-	}
-
-	private static Cipher initAESCipher(String sKey, String vector, int cipherMode) throws Exception {
-		byte[] raw;
-		raw = sKey.getBytes();
-		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
-		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
-		IvParameterSpec iv = new IvParameterSpec(vector.getBytes());
-		cipher.init(cipherMode, skeySpec, iv);
-		return cipher;
-	}
-
-	/**
-	 * 解密文件
-	 * 
-	 * @param sourceFile  源文件
-	 * @param decryptFile 解密后的文件
-	 * @param sKey        密钥
-	 * @param vc          向量
-	 * @throws Exception
-	 */
-	public static void decryptFile(File sourceFile, File decryptFile, String sKey, String vc) {
-		decryptOrEncryptFile(Cipher.DECRYPT_MODE, sourceFile, decryptFile, sKey, vc);
-	}
-
-	/**
-	 * 加密文件
-	 * 
-	 * @param sourceFile  源文件
-	 * @param encryptFile 加密后的文件
-	 * @param sKey        密钥
-	 * @param vc          向量
-	 * @throws Exception
-	 */
-	public static void encryptFile(File sourceFile, File encryptFile, String sKey, String vc) {
-		decryptOrEncryptFile(Cipher.ENCRYPT_MODE, sourceFile, encryptFile, sKey, vc);
-	}
-
-	private static void decryptOrEncryptFile(int cipherMode, File sourceFile, File targetFile, String sKey, String vc) {
-		InputStream inputStream = null;
-		OutputStream outputStream = null;
-		try {
-			Cipher cipher = initAESCipher(sKey, vc, cipherMode);
-			inputStream = new FileInputStream(sourceFile);
-			outputStream = new FileOutputStream(targetFile);
-			CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
-			byte[] buffer = new byte[1024];
-			int r;
-			while ((r = inputStream.read(buffer)) >= 0) {
-				cipherOutputStream.write(buffer, 0, r);
-			}
-			cipherOutputStream.close();
-		} catch (Exception e) {
-			throw new BusinessException("加解密文件失败!" + e.getMessage());
-		} finally {
-			try {
-				if (inputStream != null) {
-					inputStream.close();
-				}
-			} catch (IOException e) {
-			}
-			try {
-				if (outputStream != null) {
-					outputStream.close();
-				}
-			} catch (IOException e) {
-			}
-		}
-	}
+    /**
+     * 将网络文件保存到本地
+     *
+     * @param fileUrl       网络文件URL
+     * @param localFilePath 例如D:/123.txt
+     * @throws IOException
+     */
+    public static void saveUrlAsFile(String fileUrl, String localFilePath) {
+        HttpURLConnection connection = null;
+        DataOutputStream dataOutputStream = null;
+        DataInputStream dataInputStream = null;
+        try {
+            URL url = new URL(fileUrl);
+
+            connection = (HttpURLConnection) url.openConnection();
+
+            dataInputStream = new DataInputStream(connection.getInputStream());
+            FileOutputStream fileOutputStream = new FileOutputStream(localFilePath);
+            dataOutputStream = new DataOutputStream(fileOutputStream);
+
+            byte[] buffer = new byte[4096];
+            int count;
+            while ((count = dataInputStream.read(buffer)) > 0) {
+                dataOutputStream.write(buffer, 0, count);
+            }
+            fileOutputStream.flush();
+            dataOutputStream.flush();
+        } catch (IOException e) {
+            throw new BusinessException("下载文件出错" + e.getMessage());
+        } finally {
+            if (connection != null) {
+                connection.disconnect();
+            }
+            if (dataOutputStream != null) {
+                try {
+                    dataOutputStream.close();
+                } catch (IOException e) {
+                }
+            }
+            if (dataInputStream != null) {
+                try {
+                    dataInputStream.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+    }
+
+    /**
+     * 将网络文件保存到本地
+     *
+     * @param fileUrl   网络文件URL
+     * @param localFile 本地文件对象
+     * @throws IOException
+     */
+    public static void saveUrlAsFile(String fileUrl, File localFile) {
+        saveUrlAsFile(fileUrl, localFile.getAbsolutePath());
+    }
+
+    /**
+     * 读取文件内容
+     *
+     * @param file
+     * @return
+     * @throws IOException
+     */
+    public static String readFileContent(File file) {
+        StringBuilder content = new StringBuilder();
+        InputStreamReader streamReader = null;
+        BufferedReader bufferedReader = null;
+        try {
+            String encoding = Constants.CHARSET_NAME;
+            if (file.exists() && file.isFile()) {
+                streamReader = new InputStreamReader(new FileInputStream(file), encoding);
+                bufferedReader = new BufferedReader(streamReader);
+                String line;
+                while ((line = bufferedReader.readLine()) != null) {
+                    content.append(line);
+                }
+            }
+        } catch (IOException e) {
+            throw new BusinessException("读取文件出错" + e.getMessage());
+        } finally {
+            if (streamReader != null) {
+                try {
+                    streamReader.close();
+                } catch (IOException e) {
+                }
+            }
+            if (bufferedReader != null) {
+                try {
+                    bufferedReader.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+        return content.toString();
+    }
+
+    /**
+     * 创建文件目录
+     */
+    public static boolean makeDirs(String path) {
+        if (path == null || "".equals(path)) {
+            return false;
+        }
+        File folder = new File(path);
+        if (!folder.exists()) {
+            return folder.mkdirs();
+        }
+        return true;
+    }
+
+    /**
+     * 保存字符串到文件中 @throws IOException @throws
+     */
+    public static void saveAsFile(String path, String content) {
+        saveAsFile(path, content, null);
+    }
+
+    public static void saveAsFile(String path, String content, String encoding) {
+        if (path == null || content == null) {
+            return;
+        }
+
+        if (encoding == null) {
+            encoding = Constants.CHARSET_NAME;
+        }
+        BufferedWriter bw = null;
+        try {
+            File file = new File(path);
+            if (!file.exists()) {
+                if (FileUtil.makeDirs(file.getParent())) {
+                    boolean ok = file.createNewFile();
+                    if (!ok) {
+                        throw new BusinessException("文件创建失败!");
+                    }
+                }
+            }
+
+            FileOutputStream fos = new FileOutputStream(file);
+            OutputStreamWriter write = new OutputStreamWriter(fos, encoding);
+            bw = new BufferedWriter(write);
+            bw.write(content);
+            bw.flush();
+        } catch (IOException e) {
+            throw new BusinessException("保存文件出错" + e.getMessage());
+        } finally {
+            if (bw != null) {
+                try {
+                    bw.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+    }
+
+    /**
+     * 解压文件
+     *
+     * @param targetDir 解压目录
+     * @param zipFile   待解压的ZIP文件
+     * @throws IOException
+     */
+    public static List<File> unZip(File targetDir, File zipFile) throws IOException {
+        if (targetDir == null) {
+            throw new BusinessException("解压目录不能为空!");
+        }
+
+        if (zipFile == null) {
+            throw new BusinessException("待解压的文件不能为空!");
+        }
+
+        if (!zipFile.exists()) {
+            throw new BusinessException("待解压的文件不存在!" + zipFile.getAbsolutePath());
+        }
+
+        String zipName = zipFile.getName().toLowerCase();
+        if (zipFile.isDirectory() || zipName.indexOf(".zip") < 0) {
+            throw new BusinessException("待解压的文件格式错误!");
+        }
+
+        if (!targetDir.exists()) {
+            targetDir.mkdir();
+        }
+
+        List<File> result = new LinkedList<>();
+
+        try (ZipFile zip = new ZipFile(zipFile, StandardCharsets.UTF_8);) {
+
+            Enumeration entries = zip.entries();
+            while (entries.hasMoreElements()) {
+                ZipEntry entry = (ZipEntry) entries.nextElement();
+
+                // Linux中需要替换掉路径的反斜杠
+                String entryName = (File.separator + entry.getName()).replaceAll("\\\\", "/");
+
+                String filePath = targetDir.getAbsolutePath() + entryName;
+                File target = new File(filePath);
+                if (entry.isDirectory()) {
+                    target.mkdirs();
+                } else {
+                    File dir = target.getParentFile();
+                    if (!dir.exists()) {
+                        dir.mkdirs();
+                    }
+
+                    try (OutputStream os = new FileOutputStream(target); InputStream is = zip.getInputStream(entry);) {
+                        IOUtils.copy(is, os);
+                        os.flush();
+                    }
+                    result.add(target);
+                }
+            }
+
+        }
+
+        return result;
+    }
+
+    /**
+     * 文件压缩
+     *
+     * @param target 目录或文件 @param zipFile 压缩后的ZIP文件 @throws IOException @throws
+     */
+    public static boolean doZip(File target, File zipFile) throws IOException {
+        if (target == null || !target.exists()) {
+            throw new BusinessException("目录或文件不能为空!");
+        }
+
+        if (zipFile == null) {
+            throw new BusinessException("待压缩的文件不能为空!");
+        }
+
+        try (OutputStream outStream = new FileOutputStream(zipFile);
+             ZipOutputStream zipOutStream = new ZipOutputStream(outStream, StandardCharsets.UTF_8);) {
+            if (!zipFile.exists()) {
+                boolean ok = zipFile.createNewFile();
+                if (!ok) {
+                    throw new BusinessException("压缩的文件创建失败!");
+                }
+            }
+
+            if (target.isDirectory()) {
+                File[] files = target.listFiles();
+                if (files.length == 0) {
+                    throw new BusinessException("文件夹内未找到任何文件!");
+                }
+
+                for (File file : files) {
+                    doZip(zipOutStream, file, null);
+                }
+            } else {
+                doZip(zipOutStream, target, null);
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * @param resultFile
+     * @param sourseFiles
+     * @return
+     * @throws IOException
+     */
+    public static boolean doZip(File resultFile, List<File> sourseFiles) {
+        if (sourseFiles == null || sourseFiles.size() == 0) {
+            throw new BusinessException("待压缩的文件不能为空!");
+        }
+
+        if (resultFile == null) {
+            throw new BusinessException("压缩后的文件不能为空!");
+        }
+        ZipOutputStream zipOutStream = null;
+        try {
+            OutputStream outStream = new FileOutputStream(resultFile);
+            zipOutStream = new ZipOutputStream(outStream, StandardCharsets.UTF_8);
+            if (!resultFile.exists()) {
+                boolean ok = resultFile.createNewFile();
+                if (!ok) {
+                    throw new BusinessException("压缩的文件创建失败!");
+                }
+            }
+
+            for (File file : sourseFiles) {
+                doZip(zipOutStream, file, null);
+            }
+        } catch (IOException e) {
+            throw new BusinessException("压缩的文件创建失败!" + e.getMessage());
+        } finally {
+            if (zipOutStream != null) {
+                try {
+                    zipOutStream.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+
+        return true;
+    }
+
+    private static void doZip(ZipOutputStream zipOutStream, File target, String parentDir) throws IOException {
+        if (parentDir == null) {
+            parentDir = "";
+        }
+
+        if (!"".equals(parentDir) && !parentDir.endsWith(File.separator)) {
+            parentDir += File.separator;
+        }
+
+        if (target.isDirectory()) {
+            File[] files = target.listFiles();
+            if (files.length > 0) {
+                for (File file : files) {
+                    doZip(zipOutStream, file, parentDir + target.getName());
+                }
+            } else {
+                zipOutStream.putNextEntry(new ZipEntry(parentDir + target.getName()));
+                zipOutStream.closeEntry();
+            }
+        } else {
+            try (InputStream is = new FileInputStream(target);) {
+                zipOutStream.putNextEntry(new ZipEntry(parentDir + target.getName()));
+                int len;
+                byte[] bytes = new byte[1024];
+                while ((len = is.read(bytes)) > 0) {
+                    zipOutStream.write(bytes, 0, len);
+                }
+            }
+            zipOutStream.closeEntry();
+        }
+    }
+
+    public static void deleteFolder(String path) {
+
+        File file = new File(path);
+        if (file.exists()) {
+            if (file.isFile()) {
+                deleteFile(path);
+            } else {
+                deleteDirectory(path);
+            }
+        }
+    }
+
+    public static void deleteFile(String path) {
+        File file = new File(path);
+        deleteFile(file);
+    }
+
+    public static void deleteFile(File file) {
+        if (file.isFile() && file.exists()) {
+            file.delete();
+        }
+    }
+
+    public static void deleteDirectory(File dirFile) {
+        if (!dirFile.exists() || !dirFile.isDirectory()) {
+            return;
+        }
+        File[] files = dirFile.listFiles();
+        if (files != null) {
+            for (int i = 0; i < files.length; i++) {
+                if (files[i].isFile()) {
+                    deleteFile(files[i]);
+                } else {
+                    deleteDirectory(files[i]);
+                }
+            }
+        }
+
+        dirFile.delete();
+    }
+
+    public static void deleteDirectory(String path) {
+        if (!path.endsWith(File.separator)) {
+            path = path + File.separator;
+        }
+        File dirFile = new File(path);
+        deleteDirectory(dirFile);
+    }
+
+    private static Cipher initAESCipher(String sKey, String vector, int cipherMode) throws Exception {
+        byte[] raw;
+        raw = sKey.getBytes();
+        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+        IvParameterSpec iv = new IvParameterSpec(vector.getBytes());
+        cipher.init(cipherMode, skeySpec, iv);
+        return cipher;
+    }
+
+    /**
+     * 解密文件
+     *
+     * @param sourceFile  源文件
+     * @param decryptFile 解密后的文件
+     * @param sKey        密钥
+     * @param vc          向量
+     * @throws Exception
+     */
+    public static void decryptFile(File sourceFile, File decryptFile, String sKey, String vc) {
+        decryptOrEncryptFile(Cipher.DECRYPT_MODE, sourceFile, decryptFile, sKey, vc);
+    }
+
+    /**
+     * 加密文件
+     *
+     * @param sourceFile  源文件
+     * @param encryptFile 加密后的文件
+     * @param sKey        密钥
+     * @param vc          向量
+     * @throws Exception
+     */
+    public static void encryptFile(File sourceFile, File encryptFile, String sKey, String vc) {
+        decryptOrEncryptFile(Cipher.ENCRYPT_MODE, sourceFile, encryptFile, sKey, vc);
+    }
+
+    private static void decryptOrEncryptFile(int cipherMode, File sourceFile, File targetFile, String sKey, String vc) {
+        InputStream inputStream = null;
+        OutputStream outputStream = null;
+        try {
+            Cipher cipher = initAESCipher(sKey, vc, cipherMode);
+            inputStream = new FileInputStream(sourceFile);
+            outputStream = new FileOutputStream(targetFile);
+            CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
+            byte[] buffer = new byte[1024];
+            int r;
+            while ((r = inputStream.read(buffer)) >= 0) {
+                cipherOutputStream.write(buffer, 0, r);
+            }
+            cipherOutputStream.close();
+        } catch (Exception e) {
+            throw new BusinessException("加解密文件失败!" + e.getMessage());
+        } finally {
+            try {
+                if (inputStream != null) {
+                    inputStream.close();
+                }
+            } catch (IOException e) {
+            }
+            try {
+                if (outputStream != null) {
+                    outputStream.close();
+                }
+            } catch (IOException e) {
+            }
+        }
+    }
+
+    /**
+     * 文件转数组
+     * @param file
+     * @return
+     * @throws IOException
+     */
+    public static byte[] fileConvertToByteArray(File file) throws IOException {
+        byte[] data = null;
+        FileInputStream fis = null;
+        ByteArrayOutputStream baos = null;
+        try {
+            fis = new FileInputStream(file);
+            baos = new ByteArrayOutputStream();
+            int len;
+            byte[] buffer = new byte[1024];
+            while ((len = fis.read(buffer)) != -1) {
+                baos.write(buffer, 0, len);
+            }
+            data = baos.toByteArray();
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            if (Objects.nonNull(fis)) {
+                fis.close();
+            }
+            if (Objects.nonNull(baos)) {
+                baos.flush();
+                baos.close();
+            }
+        }
+        return data;
+    }
 }

+ 2 - 1
themis-exam/src/main/java/com/qmth/themis/exam/api/TEExamController.java

@@ -33,6 +33,7 @@ import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
+import java.io.IOException;
 import java.util.*;
 import java.util.concurrent.ConcurrentHashMap;
 
@@ -318,7 +319,7 @@ public class TEExamController {
     @ApiOperation(value = "获取试卷下载信息")
     @RequestMapping(value = "/paper/download", method = RequestMethod.POST)
     @ApiResponses({@ApiResponse(code = 200, message = "试卷信息")})
-    public Result paperDownload(@RequestBody ResultParamBean param) {
+    public Result paperDownload(@RequestBody ResultParamBean param) throws IOException {
         if (Objects.isNull(param.getRecordId()) || Objects.equals(param.getRecordId(), "")) {
             throw new BusinessException(ExceptionResultEnum.RECORD_ID_IS_NULL);
         }