Kaynağa Gözat

merge from examcloud-R

deason 5 yıl önce
ebeveyn
işleme
b2587d778b
18 değiştirilmiş dosya ile 820 ekleme ve 1044 silme
  1. 1 3
      examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/AudioTimeConfigController.java
  2. 8 8
      examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/ExportPaperController.java
  3. 1 47
      examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/ExportTemplateController.java
  4. 30 23
      examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/ExtractConfigController.java
  5. 22 36
      examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/ImportPaperController.java
  6. 4 4
      examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/PaperController.java
  7. 1 1
      examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/FileDisposeUtil.java
  8. 0 35
      examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/bean/ExportServiceManageBean.java
  9. 1 1
      examcloud-core-questions-dao/src/main/java/cn/com/qmth/examcloud/core/questions/dao/ExportServiceManageRepo.java
  10. 0 3
      examcloud-core-questions-dao/src/main/java/cn/com/qmth/examcloud/core/questions/dao/entity/QuestionPkgPath.java
  11. 10 11
      examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/cache/ExtractConfigPaperCache.java
  12. 10 11
      examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/cache/QuestionCache.java
  13. 9 9
      examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/impl/ExtractConfigFileServiceImpl.java
  14. 16 28
      examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/impl/PaperDetailUnitServiceImpl.java
  15. 24 28
      examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/impl/PaperServiceImpl.java
  16. 652 741
      examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/temp/CqdxService.java
  17. 30 54
      examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/util/ExportPaperUtil.java
  18. 1 1
      examcloud-core-questions-starter/src/main/resources/security.properties

+ 1 - 3
examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/AudioTimeConfigController.java

@@ -65,9 +65,7 @@ public class AudioTimeConfigController extends ControllerSupport {
             audioTimeConfigService.saveAudioTimeConfig(audioTimeConfigList, user);
             //清除缓存
             for(AudioTimeConfig ep:audioTimeConfigList) {
-                Object[] keys=new Object[]{ep.getPaper().getId()};
-                Object[] subkeys=new Object[]{Long.valueOf(ep.getExamId()), ep.getCourseCode(),ep.getGroupCode()};
-                extractConfigPaperCache.refresh(keys,subkeys);
+            	extractConfigPaperCache.refresh(Long.valueOf(ep.getExamId()), ep.getCourseCode(),ep.getGroupCode(),ep.getPaper().getId());
             }
             return new ResponseEntity<>(HttpStatus.OK);
         }

+ 8 - 8
examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/ExportPaperController.java

@@ -50,16 +50,16 @@ public class ExportPaperController extends ControllerSupport {
      * @return
      */
     @ApiOperation(value = "导出试卷", notes = "导出试卷")
-    @GetMapping(value = "/paper/export/{id}/{exportContentList}/{orgId}/{loginName}/{examType}")
+    @GetMapping(value = "/paper/export/{id}/{exportContentList}/{orgName}/{loginName}/{examType}")
     public void getPaperById(HttpServletRequest request, HttpServletResponse response, @PathVariable String id,
-            @PathVariable String orgId, @PathVariable String exportContentList, @PathVariable String loginName,
+            @PathVariable String orgName, @PathVariable String exportContentList, @PathVariable String loginName,
             @PathVariable String examType) {
         log.info("导出开始");
         String psw = request.getParameter("psw");
-        ExportServiceManage esm = exportServiceManageRepo.findByOrgId(orgId);
+        ExportServiceManage esm = exportServiceManageRepo.findByOrgName(orgName);
 
         if (esm == null) {
-            throw new StatusException("500", "尚未配置导出功能!");
+            throw new StatusException("500", String.format("学校【%s】尚未配置导出模板!", orgName));
         }
         User user = getAccessUser();
         exportPaperService.exportPaperFile(id, esm.getExportServiceName(), exportContentList, response, loginName,
@@ -78,16 +78,16 @@ public class ExportPaperController extends ControllerSupport {
      * @param loginName
      */
     @ApiOperation(value = "批量导出试卷", notes = "批量导出")
-    @GetMapping(value = "/paper/batch_export/{paperIds}/{exportContentList}/{orgId}/{loginName}/{examType}")
+    @GetMapping(value = "/paper/batch_export/{paperIds}/{exportContentList}/{orgName}/{loginName}/{examType}")
     public void getPaperByIds(HttpServletRequest request, HttpServletResponse response, @PathVariable String paperIds,
-            @PathVariable String orgId, @PathVariable String exportContentList, @PathVariable String loginName,
+            @PathVariable String orgName, @PathVariable String exportContentList, @PathVariable String loginName,
             @PathVariable String examType) {
         log.info("批量导出");
         List<String> paperList = Stream.of(paperIds.split(",")).collect(Collectors.toList());
-        ExportServiceManage esm = exportServiceManageRepo.findByOrgId(orgId);
+        ExportServiceManage esm = exportServiceManageRepo.findByOrgName(orgName);
 
         if (esm == null) {
-            throw new StatusException("500", "尚未配置导出功能!");
+            throw new StatusException("500", String.format("学校【%s】尚未配置导出模板!", orgName));
         }
 
         try {

+ 1 - 47
examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/ExportTemplateController.java

@@ -2,7 +2,6 @@ package cn.com.qmth.examcloud.core.questions.api.controller;
 
 import javax.validation.constraints.NotNull;
 
-import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.Page;
 import org.springframework.web.bind.annotation.DeleteMapping;
@@ -18,10 +17,7 @@ import org.springframework.web.multipart.MultipartFile;
 
 import cn.com.qmth.examcloud.api.commons.security.bean.User;
 import cn.com.qmth.examcloud.commons.exception.StatusException;
-import cn.com.qmth.examcloud.core.questions.base.bean.ExportServiceManageBean;
 import cn.com.qmth.examcloud.core.questions.base.dto.ExportTemplateDto;
-import cn.com.qmth.examcloud.core.questions.dao.ExportServiceManageRepo;
-import cn.com.qmth.examcloud.core.questions.dao.entity.ExportServiceManage;
 import cn.com.qmth.examcloud.core.questions.service.ExportTemplateService;
 import cn.com.qmth.examcloud.web.support.ControllerSupport;
 import io.swagger.annotations.Api;
@@ -31,8 +27,7 @@ import io.swagger.annotations.ApiOperation;
 @RestController
 @RequestMapping("${api_cqb}/exportTemplate")
 public class ExportTemplateController extends ControllerSupport {
-    @Autowired
-    ExportServiceManageRepo exportServiceManageRepo;
+
     @Autowired
     private ExportTemplateService exportTemplateService;
 
@@ -99,45 +94,4 @@ public class ExportTemplateController extends ControllerSupport {
         }
         exportTemplateService.disenable(rootOrgId, id);
     }
-    
-    @ApiOperation(value = "查询配置")
-    @GetMapping("/config/{rootOrgId}")
-    public ExportServiceManageBean getConfig(@PathVariable Long rootOrgId) {
-        User accessUser = getAccessUser();
-        if (!isSuperAdmin()) {
-            if (!rootOrgId.equals(accessUser.getRootOrgId())) {
-                throw new StatusException("100005", "无效的请求");
-            }
-        }
-        ExportServiceManage esm = exportServiceManageRepo.findByOrgId(String.valueOf(rootOrgId));
-        ExportServiceManageBean bean=new ExportServiceManageBean();
-        if(esm!=null) {
-            bean.setOrgId(esm.getOrgId());
-            bean.setId(esm.getId());
-            bean.setExportServiceName(esm.getExportServiceName());
-        }
-        return bean;
-    }
-
-    @ApiOperation(value = "新增/修改配置")
-    @PutMapping("/config/{rootOrgId}")
-    public void modifyConfig(@RequestParam @NotNull(message = "配置名称不能为空!") String serviceName,
-            @PathVariable Long rootOrgId) {
-        User accessUser = getAccessUser();
-        if (!isSuperAdmin()) {
-            if (!rootOrgId.equals(accessUser.getRootOrgId())) {
-                throw new StatusException("100006", "无效的请求");
-            }
-        }
-        if(StringUtils.isBlank(serviceName)) {
-            throw new StatusException("100007", "配置名称不能为空!");
-        }
-        ExportServiceManage esm = exportServiceManageRepo.findByOrgId(String.valueOf(rootOrgId));
-        if(esm==null) {
-            esm=new ExportServiceManage();
-            esm.setOrgId(String.valueOf(rootOrgId));
-        }
-        esm.setExportServiceName(serviceName.trim());
-        exportServiceManageRepo.save(esm);
-    }
 }

+ 30 - 23
examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/ExtractConfigController.java

@@ -1,6 +1,28 @@
 package cn.com.qmth.examcloud.core.questions.api.controller;
 
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+
 import cn.com.qmth.examcloud.api.commons.security.bean.User;
 import cn.com.qmth.examcloud.commons.exception.StatusException;
 import cn.com.qmth.examcloud.core.questions.base.enums.ExportWay;
@@ -15,21 +37,6 @@ import cn.com.qmth.examcloud.core.questions.service.cache.ExtractConfigCache;
 import cn.com.qmth.examcloud.web.support.ControllerSupport;
 import cn.com.qmth.examcloud.web.support.Naked;
 import io.swagger.annotations.ApiOperation;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.domain.Page;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.*;
-
-import javax.servlet.http.HttpServletResponse;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
 
 
 /**
@@ -43,7 +50,7 @@ import java.util.Map;
 @RequestMapping("${api_cqb}/")
 public class ExtractConfigController extends ControllerSupport {
     private static final Logger logger = LoggerFactory.getLogger(ExtractConfigController.class);
-
+    
     @Autowired
     private ExtractConfigService extractConfigService;
 
@@ -80,7 +87,7 @@ public class ExtractConfigController extends ControllerSupport {
 
             //清除缓存
             extractConfigCache.remove(extractConfig.getExamId(), extractConfig.getCourseCode());
-
+            
             return new ResponseEntity<>(HttpStatus.OK);
         } catch (Exception e) {
             logger.error(e.getMessage(), e);
@@ -176,10 +183,10 @@ public class ExtractConfigController extends ControllerSupport {
 
     @Naked
     @ApiOperation(value = "导出单张考试试卷、答案、试卷结构", notes = "导出单张考试试卷、答案、试卷结构")
-    @GetMapping(value = "/exportSingleExamPaperInfo/{orgId}/{exportWay}/{examId}/{courseId}/{exportContentList}/{loginName}")
+    @GetMapping(value = "/exportSingleExamPaperInfo/{orgName}/{exportWay}/{examId}/{courseId}/{exportContentList}/{loginName}")
     public void exportSingleExamPaperInfo(HttpServletResponse response,
                                           @PathVariable String exportWay,
-                                          @PathVariable String orgId,
+                                          @PathVariable String orgName,
                                           @PathVariable String examId,
                                           @PathVariable String courseId,
                                           @PathVariable String exportContentList,
@@ -196,7 +203,7 @@ public class ExtractConfigController extends ControllerSupport {
         }
         exportModel.setExportContentList(list);
         try {
-            extractConfigFileService.exportExamPaperInfo(exportModel, response, loginName, orgId, psw);
+            extractConfigFileService.exportExamPaperInfo(exportModel, response, loginName, orgName, psw);
         } catch (Exception e) {
             log.error(e.getMessage(), e);
         }
@@ -221,10 +228,10 @@ public class ExtractConfigController extends ControllerSupport {
 
     @Naked
     @ApiOperation(value = "导出整个考试下所有 课程的试卷、答案、试卷结构", notes = "导出整个考试下所有 课程的试卷、答案、试卷结构")
-    @GetMapping(value = "/exportBatchExamPaperInfo/{orgId}/{exportWay}/{examId}/{exportContentList}/{loginName}")
+    @GetMapping(value = "/exportBatchExamPaperInfo/{orgName}/{exportWay}/{examId}/{exportContentList}/{loginName}")
     public void exportBatchExamPaperInfo(HttpServletResponse response,
                                          @PathVariable String exportWay,
-                                         @PathVariable String orgId,
+                                         @PathVariable String orgName,
                                          @PathVariable String examId,
                                          @PathVariable String exportContentList,
                                          @PathVariable String loginName) {
@@ -238,7 +245,7 @@ public class ExtractConfigController extends ControllerSupport {
         }
         exportModel.setExportContentList(list);
         try {
-            extractConfigFileService.exportExamPaperInfo(exportModel, response, loginName, orgId, null);
+            extractConfigFileService.exportExamPaperInfo(exportModel, response, loginName, orgName, null);
         } catch (Exception e) {
             log.error(e.getMessage(), e);
         }

+ 22 - 36
examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/ImportPaperController.java

@@ -1,36 +1,30 @@
 package cn.com.qmth.examcloud.core.questions.api.controller;
 
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.validation.constraints.NotNull;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.ModelAttribute;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RequestPart;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.multipart.MultipartFile;
-import org.springframework.web.multipart.commons.CommonsMultipartFile;
-
 import cn.com.qmth.examcloud.api.commons.security.bean.User;
 import cn.com.qmth.examcloud.commons.exception.StatusException;
 import cn.com.qmth.examcloud.core.questions.base.exception.PaperException;
+import cn.com.qmth.examcloud.core.questions.dao.PaperRepo;
 import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
 import cn.com.qmth.examcloud.core.questions.service.ClonePaperService;
 import cn.com.qmth.examcloud.core.questions.service.ImportDdCollegePaperService;
 import cn.com.qmth.examcloud.core.questions.service.ImportPaperService;
-import cn.com.qmth.examcloud.core.questions.service.temp.CqdxService;
+import cn.com.qmth.examcloud.core.questions.service.PaperService;
 import cn.com.qmth.examcloud.web.support.ControllerSupport;
 import io.swagger.annotations.ApiOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.commons.CommonsMultipartFile;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.validation.constraints.NotNull;
 
 /**
  * @author weiwenhai
@@ -46,11 +40,13 @@ public class ImportPaperController extends ControllerSupport {
 	@Autowired
 	private ClonePaperService clonePaperService;
 	@Autowired
-	private ImportPaperService importPaperService;
+	ImportPaperService importPaperService;
 	@Autowired
 	private ImportDdCollegePaperService importDdCollegePaperService;
 	@Autowired
-	private CqdxService cqdxService;
+	PaperRepo paperRepo;
+	@Autowired
+	PaperService paperService;
 
 	/**
 	 * 导入试卷
@@ -120,19 +116,9 @@ public class ImportPaperController extends ControllerSupport {
 	@ApiOperation(value = "导入地大试卷", notes = "导入地大试卷")
 	@PostMapping(value = "/importDdCollegePaper")
 	public ResponseEntity<Object> importDdCollegePaper(
-			@RequestPart @NotNull(message = "上传文件不能为空!") MultipartFile dataFile, @RequestParam Long rootOrgId) {
-		User user = getAccessUser();
-		importDdCollegePaperService.importDdCollegePaper(dataFile, user, rootOrgId);
-		return new ResponseEntity<>(HttpStatus.OK);
-	}
-
-	@ApiOperation(value = "导入重庆试卷", notes = "导入重庆试卷")
-	@PostMapping(value = "/importCqCollegePaper")
-	public ResponseEntity<Object> importCqCollegePaper(
-			@RequestPart @NotNull(message = "上传文件不能为空!") MultipartFile dataFile, @RequestParam Long rootOrgId,
-			@RequestParam String paperNameSuffix, @RequestParam String impType) {
+			@RequestPart @NotNull(message = "上传文件不能为空!") MultipartFile dataFile,@RequestParam Long rootOrgId) {
 		User user = getAccessUser();
-		cqdxService.bulidPaper(dataFile, user, rootOrgId, paperNameSuffix,impType);
+		importDdCollegePaperService.importDdCollegePaper(dataFile,user, rootOrgId);
 		return new ResponseEntity<>(HttpStatus.OK);
 	}
 

+ 4 - 4
examcloud-core-questions-api-provider/src/main/java/cn/com/qmth/examcloud/core/questions/api/controller/PaperController.java

@@ -104,7 +104,7 @@ public class PaperController extends ControllerSupport {
         if ("success".equals(msgMap.get("msg"))) {
             return new ResponseEntity<>(msgMap, HttpStatus.OK);
         } else {
-            throw new StatusException("1000",msgMap.get("msg").toString());
+            return new ResponseEntity<>(msgMap, HttpStatus.INTERNAL_SERVER_ERROR);
         }
     }
 
@@ -210,7 +210,7 @@ public class PaperController extends ControllerSupport {
         if (msgMap.get("msg").equals("success")) {
             return new ResponseEntity<>(msgMap, HttpStatus.OK);
         } else {
-            throw new StatusException("1001","试卷["+msgMap.get("paperName")+"]中有试题被组卷使用,不能删除!");
+            return new ResponseEntity<>(msgMap, HttpStatus.INTERNAL_SERVER_ERROR);
         }
 
     }
@@ -553,13 +553,13 @@ public class PaperController extends ControllerSupport {
                 Paper oldpaper = cn.com.qmth.examcloud.core.questions.base.Model.of(paperRepo.findById(paperIdArray[i]));
                 boolean result = paperService.checkPaperName(oldpaper.getName(), PaperType.GENERATE, user.getRootOrgId() + "");
                 if (!result) {
-                    throw new StatusException("160565", "考试试卷:" + oldpaper.getName() + "已经存在");
+                    throw new StatusException("Q-160565", "考试试卷:" + oldpaper.getName() + "已经存在");
                 }
             }
             paperService.useBasePaper(paperIds, user.getDisplayName());
             return new ResponseEntity<>(HttpStatus.OK);
         } catch (Exception e) {
-            throw new StatusException("160537", e.getMessage());
+            throw new StatusException("Q-160537", e.getMessage());
         }
     }
 

+ 1 - 1
examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/FileDisposeUtil.java

@@ -52,7 +52,7 @@ public class FileDisposeUtil {
         try {
             url = new URL(fileUrl);
         } catch (MalformedURLException e) {
-            logger.error("fileUrl:"+fileUrl, e);
+            logger.error(e.getMessage(), e);
             return false;
         }
 

+ 0 - 35
examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/bean/ExportServiceManageBean.java

@@ -1,35 +0,0 @@
-package cn.com.qmth.examcloud.core.questions.base.bean;
-
-public class ExportServiceManageBean {
-
-    private String id;
-
-    private String orgId;
-
-    private String exportServiceName;
-
-    public String getId() {
-        return id;
-    }
-
-    public void setId(String id) {
-        this.id = id;
-    }
-
-    public String getExportServiceName() {
-        return exportServiceName;
-    }
-
-    public void setExportServiceName(String exportServiceName) {
-        this.exportServiceName = exportServiceName;
-    }
-
-    public String getOrgId() {
-        return orgId;
-    }
-
-    public void setOrgId(String orgId) {
-        this.orgId = orgId;
-    }
-
-}

+ 1 - 1
examcloud-core-questions-dao/src/main/java/cn/com/qmth/examcloud/core/questions/dao/ExportServiceManageRepo.java

@@ -5,7 +5,7 @@ import org.springframework.data.mongodb.repository.MongoRepository;
 import org.springframework.data.repository.query.QueryByExampleExecutor;
 
 public interface ExportServiceManageRepo extends MongoRepository<ExportServiceManage, Long>, QueryByExampleExecutor<ExportServiceManage> {
-//    ExportServiceManage findByOrgName(String orgName);
+    ExportServiceManage findByOrgName(String orgName);
 
     ExportServiceManage findByOrgId(String orgId);
 }

+ 0 - 3
examcloud-core-questions-dao/src/main/java/cn/com/qmth/examcloud/core/questions/dao/entity/QuestionPkgPath.java

@@ -4,10 +4,7 @@ import cn.com.qmth.examcloud.core.questions.dao.entity.base.IdBase;
 
 /**
  * Created by songyue on 17/11/19.
- * 
  */
-//新方案导出不存word字节信息
-@Deprecated
 public class QuestionPkgPath extends IdBase {
 
     private byte[] quesPkg;

+ 10 - 11
examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/cache/ExtractConfigPaperCache.java

@@ -1,25 +1,24 @@
 package cn.com.qmth.examcloud.core.questions.service.cache;
 
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
 import cn.com.qmth.examcloud.commons.exception.StatusException;
 import cn.com.qmth.examcloud.core.questions.service.ExtractConfigProviderService;
 import cn.com.qmth.examcloud.support.cache.bean.ExtractConfigPaperCacheBean;
-import cn.com.qmth.examcloud.web.cache.HashRedisCache;
+import cn.com.qmth.examcloud.web.cache.RandomObjectRedisCache;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
 
 @Component
-public class ExtractConfigPaperCache extends HashRedisCache<ExtractConfigPaperCacheBean> {
+public class ExtractConfigPaperCache extends RandomObjectRedisCache<ExtractConfigPaperCacheBean> {
     @Autowired
     private ExtractConfigProviderService extractConfigProviderService;
 
     @Override
-    public ExtractConfigPaperCacheBean loadFromResource(Object[] keys,Object[] subkeys) {
-        Long examId = (Long) subkeys[0];
-        String courseCode = String.valueOf(subkeys[1]);
-        String groupCode = String.valueOf(subkeys[2]);
-        String paperId = String.valueOf(keys[0]);
+    public ExtractConfigPaperCacheBean loadFromResource(Object... keys) {
+        Long examId = (Long) keys[0];
+        String courseCode = String.valueOf(keys[1]);
+        String groupCode = String.valueOf(keys[2]);
+        String paperId = String.valueOf(keys[3]);
 
         if (examId == null) {
             throw new StatusException("400", "examId is null");

+ 10 - 11
examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/cache/QuestionCache.java

@@ -1,26 +1,25 @@
 package cn.com.qmth.examcloud.core.questions.service.cache;
 
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
 import cn.com.qmth.examcloud.commons.exception.StatusException;
 import cn.com.qmth.examcloud.core.questions.service.ExtractConfigProviderService;
 import cn.com.qmth.examcloud.question.commons.core.question.DefaultQuestion;
 import cn.com.qmth.examcloud.support.cache.bean.QuestionCacheBean;
-import cn.com.qmth.examcloud.web.cache.HashRedisCache;
+import cn.com.qmth.examcloud.web.cache.RandomObjectRedisCache;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
 
 @Component
-public class QuestionCache extends HashRedisCache<QuestionCacheBean> {
+public class QuestionCache extends RandomObjectRedisCache<QuestionCacheBean> {
     @Autowired
     private ExtractConfigProviderService extractConfigProviderService;
 
     @Override
-    public QuestionCacheBean loadFromResource(Object[] keys,Object[] subkeys) {
-        Long examId = (Long) subkeys[0];
-        String courseCode = String.valueOf(subkeys[1]);
-        String groupCode = String.valueOf(subkeys[2]);
-        String questionId = String.valueOf(keys[0]);
+    public QuestionCacheBean loadFromResource(Object... keys) {
+        Long examId = (Long) keys[0];
+        String courseCode = String.valueOf(keys[1]);
+        String groupCode = String.valueOf(keys[2]);
+        String questionId = String.valueOf(keys[3]);
 
         if (examId == null) {
             throw new StatusException("400", "examId is null");

+ 9 - 9
examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/impl/ExtractConfigFileServiceImpl.java

@@ -165,9 +165,9 @@ public class ExtractConfigFileServiceImpl implements ExtractConfigFileService {
      * @throws Exception
      */
     private void uploadPaperFile(ExtractConfig extractConfig, String paperId, ExportStructure exportStructure, User user, ExamPaper examPaper) throws Exception {
-        ExportServiceManage esm = exportServiceManageRepo.findByOrgId(String.valueOf(user.getRootOrgId()));
+        ExportServiceManage esm = exportServiceManageRepo.findByOrgName(user.getRootOrgName());
         if (esm == null) {
-            throw new StatusException("500", "尚未配置导出功能!");
+            esm = exportServiceManageRepo.findByOrgName("天津大学");
         }
         ExportPaperAbstractService exportPaperAbstractService = (ExportPaperAbstractService) SpringContextUtils.getBeanById(esm.getExportServiceName());
         exportPaperAbstractService.uploadFile(extractConfig, paperId, exportStructure, user, examPaper);
@@ -188,7 +188,7 @@ public class ExtractConfigFileServiceImpl implements ExtractConfigFileService {
     }
 
     @Override
-    public void exportExamPaperInfo(ExportPaperInfoModel exportModel, HttpServletResponse response, String loginName, String orgId, String psw) throws Exception {
+    public void exportExamPaperInfo(ExportPaperInfoModel exportModel, HttpServletResponse response, String loginName, String orgName, String psw) throws Exception {
         String tempDir = loginName + System.currentTimeMillis();
         String downloadDir = sysProperty.getDownloadDirectory() + "/" + tempDir;
         String downZipDir = sysProperty.getZipDirectory() + "/" + tempDir;
@@ -252,7 +252,7 @@ public class ExtractConfigFileServiceImpl implements ExtractConfigFileService {
                             String groupCode = examPaper.getGroupCode();
                             String paperId = examPaper.getPaper().getId();
                             if (groupCode.equals(examFile.getGroupCode())) {
-                                downloadAudio(paperId, examFile, downloadDir, orgId);
+                                downloadAudio(paperId, examFile, downloadDir, orgName);
                             }
 
                         }
@@ -287,11 +287,11 @@ public class ExtractConfigFileServiceImpl implements ExtractConfigFileService {
      *
      * @throws Exception
      */
-    private void downloadAudio(String paperId, ExamFile examFile, String downloadDir, String orgId) throws Exception {
+    private void downloadAudio(String paperId, ExamFile examFile, String downloadDir, String orgName) throws Exception {
         //Paper paper = paperRepo.findOne(paperId);
-        ExportServiceManage esm = exportServiceManageRepo.findByOrgId(orgId);
+        ExportServiceManage esm = exportServiceManageRepo.findByOrgName(orgName);
         if (esm == null) {
-            throw new StatusException("500", "尚未配置导出功能!");
+            esm = exportServiceManageRepo.findByOrgName("陕西师范大学");
         }
         ExportPaperAbstractService exportPaperAbstractService = (ExportPaperAbstractService) SpringContextUtils.getBeanById(esm.getExportServiceName());
         PaperExp paperExp = exportPaperAbstractService.initPaperExp(paperId);
@@ -504,9 +504,9 @@ public class ExtractConfigFileServiceImpl implements ExtractConfigFileService {
         //主观题集合
         List<SubjectiveQuestionStructure> subjectiveQuestionStructureList = new ArrayList<>();
 
-        ExportServiceManage esm = exportServiceManageRepo.findByOrgId(exportStructure.getOrgId());
+        ExportServiceManage esm = exportServiceManageRepo.findByOrgName(exportStructure.getOrgName());
         if (esm == null) {
-            throw new StatusException("500", "尚未配置导出功能!");
+            esm = exportServiceManageRepo.findByOrgName("陕西师范大学");
         }
         ExportPaperAbstractService exportPaperAbstractService = (ExportPaperAbstractService) SpringContextUtils.getBeanById(esm.getExportServiceName());
         Set<Entry<String, String>> entrySet = paperIds.entrySet();

+ 16 - 28
examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/impl/PaperDetailUnitServiceImpl.java

@@ -1,9 +1,14 @@
 package cn.com.qmth.examcloud.core.questions.service.impl;
 
+import static cn.com.qmth.examcloud.core.questions.service.cache.Constants.CACHE_KEY_PAPER;
+import static cn.com.qmth.examcloud.core.questions.service.cache.Constants.CACHE_KEY_QUESTION;
+
 import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
+import org.apache.commons.collections.CollectionUtils;
 import org.bson.types.ObjectId;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.Sort;
@@ -28,10 +33,6 @@ import cn.com.qmth.examcloud.core.questions.service.PaperDetailUnitService;
 import cn.com.qmth.examcloud.core.questions.service.PaperService;
 import cn.com.qmth.examcloud.core.questions.service.QuesService;
 import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperDetailUnitExp;
-import cn.com.qmth.examcloud.core.questions.service.cache.BasePaperCache;
-import cn.com.qmth.examcloud.core.questions.service.cache.ExtractConfigPaperCache;
-import cn.com.qmth.examcloud.core.questions.service.cache.QuestionAnswerCache;
-import cn.com.qmth.examcloud.core.questions.service.cache.QuestionCache;
 
 /**
  * @author chenken
@@ -40,16 +41,7 @@ import cn.com.qmth.examcloud.core.questions.service.cache.QuestionCache;
  */
 @Service("paperDetailUnitService")
 public class PaperDetailUnitServiceImpl implements PaperDetailUnitService {
-    @Autowired
-    private ExtractConfigPaperCache extractConfigPaperCache;
-    @Autowired
-    private BasePaperCache basePaperCache;
-    @Autowired
-    private QuestionCache questionCache;
-    @Autowired
-    private QuestionAnswerCache questionAnswerCache;
-    
-    
+
     @Autowired
     PaperDetailUnitRepo paperDetailUnitRepo;
 
@@ -348,24 +340,20 @@ public class PaperDetailUnitServiceImpl implements PaperDetailUnitService {
     @Override
     public void clearQuestionCache(String questionId) {
         //清理与当前试题相关的缓存
-//        final String patternKey = CACHE_KEY_QUESTION + "*" + questionId;
-//        Set<String> keys = redisTemplate.keys(patternKey);
-//        if (CollectionUtils.isNotEmpty(keys)) {
-//            redisTemplate.delete(keys);
-//        }
-        questionCache.remove(questionId);
-        questionAnswerCache.remove(questionId);
+        final String patternKey = CACHE_KEY_QUESTION + "*" + questionId;
+        Set<String> keys = redisTemplate.keys(patternKey);
+        if (CollectionUtils.isNotEmpty(keys)) {
+            redisTemplate.delete(keys);
+        }
         //根据questionId清空相关联的paper缓存
         List<PaperDetailUnit> list=findByQuestionId(questionId);
         if(list!=null&&list.size()>0) {
         	for(PaperDetailUnit pd:list) {
-//        		String paperKey = CACHE_KEY_PAPER + "*" + pd.getPaper().getId();
-//                Set<String> paperKeys = redisTemplate.keys(paperKey);
-//                if (CollectionUtils.isNotEmpty(paperKeys)) {
-//                    redisTemplate.delete(paperKeys);
-//                }
-        	    extractConfigPaperCache.remove(pd.getPaper().getId());
-        	    basePaperCache.remove(pd.getPaper().getId());
+        		String paperKey = CACHE_KEY_PAPER + "*" + pd.getPaper().getId();
+                Set<String> paperKeys = redisTemplate.keys(paperKey);
+                if (CollectionUtils.isNotEmpty(paperKeys)) {
+                    redisTemplate.delete(paperKeys);
+                }
         	}
         }
     }

+ 24 - 28
examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/impl/PaperServiceImpl.java

@@ -1,5 +1,8 @@
 package cn.com.qmth.examcloud.core.questions.service.impl;
 
+import static cn.com.qmth.examcloud.core.questions.service.cache.Constants.CACHE_KEY_PAPER;
+import static cn.com.qmth.examcloud.core.questions.service.cache.Constants.CACHE_KEY_QUESTION;
+
 import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -35,6 +38,7 @@ import org.springframework.data.domain.Sort.Order;
 import org.springframework.data.mongodb.core.MongoTemplate;
 import org.springframework.data.mongodb.core.query.Criteria;
 import org.springframework.data.mongodb.core.query.Query;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Service;
 import org.springframework.util.Assert;
 import org.springframework.web.multipart.MultipartFile;
@@ -60,6 +64,7 @@ import cn.com.qmth.examcloud.core.questions.base.enums.PaperType;
 import cn.com.qmth.examcloud.core.questions.base.exception.PaperException;
 import cn.com.qmth.examcloud.core.questions.base.question.enums.QuesStructType;
 import cn.com.qmth.examcloud.core.questions.dao.ExamPaperRepo;
+import cn.com.qmth.examcloud.core.questions.dao.ExportServiceManageRepo;
 import cn.com.qmth.examcloud.core.questions.dao.PaperDetailRepo;
 import cn.com.qmth.examcloud.core.questions.dao.PaperDetailUnitRepo;
 import cn.com.qmth.examcloud.core.questions.dao.PaperRepo;
@@ -67,6 +72,7 @@ import cn.com.qmth.examcloud.core.questions.dao.QuesBakRepo;
 import cn.com.qmth.examcloud.core.questions.dao.QuesRepo;
 import cn.com.qmth.examcloud.core.questions.dao.entity.Course;
 import cn.com.qmth.examcloud.core.questions.dao.entity.ExamPaper;
+import cn.com.qmth.examcloud.core.questions.dao.entity.ExportServiceManage;
 import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
 import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetail;
 import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetailUnit;
@@ -87,10 +93,6 @@ import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperDetailUnitExp;
 import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperExp;
 import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperQuestionStructureInfo;
 import cn.com.qmth.examcloud.core.questions.service.bean.dto.SubjectiveQuestionStructure;
-import cn.com.qmth.examcloud.core.questions.service.cache.BasePaperCache;
-import cn.com.qmth.examcloud.core.questions.service.cache.ExtractConfigPaperCache;
-import cn.com.qmth.examcloud.core.questions.service.cache.QuestionAnswerCache;
-import cn.com.qmth.examcloud.core.questions.service.cache.QuestionCache;
 import cn.com.qmth.examcloud.core.questions.service.config.SysProperty;
 import cn.com.qmth.examcloud.core.questions.service.export.ExportPaperAbstractService;
 import cn.com.qmth.examcloud.support.filestorage.FileStorageUtil;
@@ -147,23 +149,20 @@ public class PaperServiceImpl implements PaperService {
     @Autowired
     private QuestionAudioServiceImpl questionAudioService;
 
+    @Autowired
+    private ExportServiceManageRepo exportServiceManageRepo;
+
     @Autowired
     private SysProperty sysProperty;
 
+    @Autowired
+    private RedisTemplate<String, Object> redisTemplate;
+
     @Autowired
     private CoursePaperCloudService coursePaperCloudService;
 
     @Autowired
     private CourseService courseService;
-    
-    @Autowired
-    private ExtractConfigPaperCache extractConfigPaperCache;
-    @Autowired
-    private BasePaperCache basePaperCache;
-    @Autowired
-    private QuestionCache questionCache;
-    @Autowired
-    private QuestionAnswerCache questionAnswerCache;
 
     private Random random = new Random();
 
@@ -1451,7 +1450,8 @@ public class PaperServiceImpl implements PaperService {
     @Override
     public String findQuestionStructure(String paperId) throws Exception {
         //根据paperId查询新的对象
-        ExportPaperAbstractService exportPaperAbstractService = (ExportPaperAbstractService) SpringContextUtils.getBeanById("sxsfExportPaperService");
+        ExportServiceManage esm = exportServiceManageRepo.findByOrgName("陕西师范大学");
+        ExportPaperAbstractService exportPaperAbstractService = (ExportPaperAbstractService) SpringContextUtils.getBeanById(esm.getExportServiceName());
         PaperExp paperExp = exportPaperAbstractService.initPaperExp(paperId);
         log.info("已经获取试卷");
         //得到试卷中的客观大题
@@ -1849,24 +1849,20 @@ public class PaperServiceImpl implements PaperService {
 
     private void clearPaperCache(String paperId) {
         //清理与当前试卷相关的缓存
-//        final String patternKey = CACHE_KEY_PAPER + "*" + paperId;
-//        Set<String> keys = redisTemplate.keys(patternKey);
-//        if (CollectionUtils.isNotEmpty(keys)) {
-//            redisTemplate.delete(keys);
-//        }
-        extractConfigPaperCache.remove(paperId);
-        basePaperCache.remove(paperId);
+        final String patternKey = CACHE_KEY_PAPER + "*" + paperId;
+        Set<String> keys = redisTemplate.keys(patternKey);
+        if (CollectionUtils.isNotEmpty(keys)) {
+            redisTemplate.delete(keys);
+        }
     }
 
     private void clearQuestionCache(String questionId) {
         //清理与当前试题相关的缓存
-//        final String patternKey = CACHE_KEY_QUESTION + "*" + questionId;
-//        Set<String> keys = redisTemplate.keys(patternKey);
-//        if (CollectionUtils.isNotEmpty(keys)) {
-//            redisTemplate.delete(keys);
-//        }
-        questionCache.remove(questionId);
-        questionAnswerCache.remove(questionId);
+        final String patternKey = CACHE_KEY_QUESTION + "*" + questionId;
+        Set<String> keys = redisTemplate.keys(patternKey);
+        if (CollectionUtils.isNotEmpty(keys)) {
+            redisTemplate.delete(keys);
+        }
     }
 
 }

+ 652 - 741
examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/temp/CqdxService.java

@@ -2,11 +2,9 @@ package cn.com.qmth.examcloud.core.questions.service.temp;
 
 import java.io.File;
 import java.io.UnsupportedEncodingException;
-import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
-import java.util.UUID;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -17,759 +15,672 @@ import org.apache.commons.collections4.map.HashedMap;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
-import org.springframework.web.multipart.MultipartFile;
 import org.w3c.dom.Document;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-import cn.com.qmth.examcloud.api.commons.security.bean.User;
-import cn.com.qmth.examcloud.commons.exception.StatusException;
-import cn.com.qmth.examcloud.core.questions.base.CommonUtils;
-import cn.com.qmth.examcloud.core.questions.base.IdUtils;
-import cn.com.qmth.examcloud.core.questions.base.converter.utils.FileUtil;
-import cn.com.qmth.examcloud.core.questions.base.enums.PaperStatus;
-import cn.com.qmth.examcloud.core.questions.base.enums.PaperType;
 import cn.com.qmth.examcloud.core.questions.base.question.enums.QuesStructType;
-import cn.com.qmth.examcloud.core.questions.dao.PaperDetailRepo;
-import cn.com.qmth.examcloud.core.questions.dao.PaperDetailUnitRepo;
-import cn.com.qmth.examcloud.core.questions.dao.PaperRepo;
-import cn.com.qmth.examcloud.core.questions.dao.QuesRepo;
-import cn.com.qmth.examcloud.core.questions.dao.entity.Course;
-import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
-import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetail;
-import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetailUnit;
-import cn.com.qmth.examcloud.core.questions.dao.entity.QuesOption;
-import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
-import cn.com.qmth.examcloud.core.questions.service.QuesTypeNameService;
-import cn.com.qmth.examcloud.core.questions.service.impl.CourseService;
-import cn.com.qmth.examcloud.web.bootstrap.PropertyHolder;
 
 @Component
 public class CqdxService {
-	private static final Logger log = LoggerFactory.getLogger(CqdxService.class);
-//	final Long rootOrgId = 1407L;
-//	final String rootDir = "D:/paper/cqu/temps";
-	@Autowired
-	private CourseService courseService;
-	@Autowired
-	private QuesRepo quesRepo;
-	@Autowired
-	private PaperRepo paperRepo;
-	@Autowired
-	private PaperDetailRepo paperDetailRepo;
-	@Autowired
-	private PaperDetailUnitRepo paperDetailUnitRepo;
-//	@Autowired
-//	private QuesPkgPathRepo quesPkgPathRepo;
-	@Autowired
-	private QuesTypeNameService quesTypeNameService;
-
-	public void bulidPaper(MultipartFile dataFile, User user, Long rootOrgId, String paperNameSuffix, String impType) {
-		String tempDir = PropertyHolder.getString("examcloud.web.sys.tempDataDir");
-		String dir = tempDir + File.separator + UUID.randomUUID() + File.separator;
-		try {
-			File dfile = new File(dir);
-			dfile.mkdirs();
-			File zfile = new File(dir + dataFile.getOriginalFilename());
-			zfile.createNewFile();
-			dataFile.transferTo(zfile);
-			Map<Object, Object> paperInfoMap = this.readXml(zfile.getAbsolutePath(), paperNameSuffix, impType);
-			// 查询课程
-			Course course = courseService.getCourse(rootOrgId, paperInfoMap.get("courseCode").toString());
-			// 初始化试卷
-			Paper paper = initPaper(paperInfoMap, course, user);
-			// 大题集合
-			List<PaperDetail> paperDetails = initPaperDetails(paperInfoMap, paper, user);
-			// 试题---资源 对应关系
-			List<Question> questionLists = new ArrayList<>();
-
-			// 定义小题集合
-			List<PaperDetailUnit> paperDetailUnits;
-			paperDetailUnits = initpaperDetailUnits(paper, paperDetails, questionLists, paperInfoMap, course, user);
-			if (paperDetailUnits == null) {
-				throw new StatusException("100001", "有错误的XML");
-			}
-
-			// 保存试题资源
-//			quesPkgPathRepo.saveAll(questionMaps.values());
-//			for (Map.Entry<Question, QuestionPkgPath> entry : questionMaps.entrySet()) {
-//				entry.getKey().setQuesPkgPathId(entry.getValue().getId());
-//			}
-			quesRepo.saveAll(questionLists);
-			paperRepo.save(paper);
-			paperDetailRepo.saveAll(paperDetails);
-			paperDetailUnitRepo.saveAll(paperDetailUnits);
-			if (paperDetailUnits.size() > 0) {
-				quesTypeNameService.saveQuesTypeName(paperDetailUnits);
-			}
-		} catch (StatusException e) {
-			throw e;
-		} catch (Exception e) {
-			throw new StatusException("100002", "导入试卷失败:" + e.getMessage(), e);
-		} finally {
-			FileUtil.deleteFolder(dir);
-		}
-	}
-
-	public void bulidPaper() throws Exception {
-		// 获取所有xml的路径
-//		List<String> files = this.loadFiles();
-
-		// 试卷名称(后缀)
-//		final String paperNameSuffix = "192";
-
-//		int i = 0;
-//		log.debug("XML的文件数:" + files.size());
-//		for (String filePath : files) {
-//			log.debug("第" + (++i) + "个xml文件开始处理,文件名为:" + filePath);
-
-//            if (i < 30) {
-//                continue;
+    private static final Logger log = LoggerFactory.getLogger(CqdxService.class);
+    final Long rootOrgId = 1407L;
+    final String rootDir = "D:/paper/cqu/temps";
+//    @Autowired
+//    private CourseService courseService;
+//    @Autowired
+//    private QuesRepo quesRepo;
+//    @Autowired
+//    private PaperRepo paperRepo;
+//    @Autowired
+//    private PaperDetailRepo paperDetailRepo;
+//    @Autowired
+//    private PaperDetailUnitRepo paperDetailUnitRepo;
+//    @Autowired
+//    private QuesPkgPathRepo quesPkgPathRepo;
+
+//    public void bulidPaper() throws Exception {
+//        // 获取所有xml的路径
+//        List<String> files = this.loadFiles();
+//
+//        //试卷名称(后缀)
+//        final String paperNameSuffix = "192";
+//
+//        int i = 0;
+//        log.debug("XML的文件数:" + files.size());
+//        for (String filePath : files) {
+//            log.debug("第" + (++i) + "个xml文件开始处理,文件名为:" + filePath);
+//
+////            if (i < 30) {
+////                continue;
+////            }
+//
+//            Map<Object, Object> paperInfoMap = this.readXml(filePath, paperNameSuffix);
+//            // 查询课程
+//            Course course = courseService.getCourse(rootOrgId, paperInfoMap.get("courseCode").toString());
+//            // 初始化试卷
+//            Paper paper = initPaper(paperInfoMap, course);
+//            // 大题集合
+//            List<PaperDetail> paperDetails = initPaperDetails(paperInfoMap, paper);
+//            // 试题---资源 对应关系
+//            Map<Question, QuestionPkgPath> questionMaps = new HashMap<>();
+//
+//            // 定义小题集合
+//            List<PaperDetailUnit> paperDetailUnits;
+//            try {
+//                paperDetailUnits = initpaperDetailUnits(paper, paperDetails, questionMaps, paperInfoMap, course);
+//                if (paperDetailUnits == null) {
+//                    log.debug("-->有错误的XML:" + filePath);
+//                    break;
+//                }
+//            } catch (Exception e) {
+//                log.debug("==>有错误的XML:" + filePath + " Error:" + e.getMessage());
+//                break;
 //            }
-
-//			Map<Object, Object> paperInfoMap = this.readXml(filePath, paperNameSuffix);
-//			// 查询课程
-//			Course course = courseService.getCourse(rootOrgId, paperInfoMap.get("courseCode").toString());
-//			// 初始化试卷
-//			Paper paper = initPaper(paperInfoMap, course);
-//			// 大题集合
-//			List<PaperDetail> paperDetails = initPaperDetails(paperInfoMap, paper);
-//			// 试题---资源 对应关系
-//			Map<Question, QuestionPkgPath> questionMaps = new HashMap<>();
 //
-//			// 定义小题集合
-//			List<PaperDetailUnit> paperDetailUnits;
-//			try {
-//				paperDetailUnits = initpaperDetailUnits(paper, paperDetails, questionMaps, paperInfoMap, course);
-//				if (paperDetailUnits == null) {
-//					log.debug("-->有错误的XML:" + filePath);
-//					break;
-//				}
-//			} catch (Exception e) {
-//				log.debug("==>有错误的XML:" + filePath + " Error:" + e.getMessage());
-//				break;
-//			}
+//            // 保存试题资源
+//            /*quesPkgPathRepo.saveAll(questionMaps.values());
+//            for (Map.Entry<Question, QuestionPkgPath> entry : questionMaps.entrySet()) {
+//                entry.getKey().setQuesPkgPathId(entry.getValue().getId());
+//            }
+//            quesRepo.saveAll(questionMaps.keySet());
+//            paperRepo.save(paper);
+//            paperDetailRepo.saveAll(paperDetails);
+//            paperDetailUnitRepo.saveAll(paperDetailUnits);*/
 //
-//			// 保存试题资源
-//			quesPkgPathRepo.saveAll(questionMaps.values());
-//			for (Map.Entry<Question, QuestionPkgPath> entry : questionMaps.entrySet()) {
-//				entry.getKey().setQuesPkgPathId(entry.getValue().getId());
-//			}
-//			quesRepo.saveAll(questionMaps.keySet());
-//			paperRepo.save(paper);
-//			paperDetailRepo.saveAll(paperDetails);
-//			paperDetailUnitRepo.saveAll(paperDetailUnits);
+//            // 将正常文件移动到新目录
+//            /*File okFile = new File(rootDir + "/" + filePath);
+//            String newFilePath = rootDir + "/ok/" + okFile.getName();
+//            File newFile = new File(newFilePath);
+//            okFile.renameTo(newFile);*/
 //
-//			// 将正常文件移动到新目录
-//			File okFile = new File(rootDir + "/" + filePath);
-//			String newFilePath = rootDir + "/ok/" + okFile.getName();
-//			File newFile = new File(newFilePath);
-//			okFile.renameTo(newFile);
+//            log.debug("第" + i + "个xml文件已经处理完,文件名为:" + filePath);
+//        }
+//        log.debug("处理完成...");
+//    }
+
+    // 初始化试卷
+//    private Paper initPaper(Map<Object, Object> paperInfoMap, Course course) {
+//        Paper paper = new Paper();
+//        paper.setName((String) paperInfoMap.get("name"));
+//        paper.setTitle((String) paperInfoMap.get("name"));
+//        paper.setPaperType(PaperType.IMPORT);
+//        paper.setPaperStatus(PaperStatus.DRAFT);
+//        paper.setOrgId(course.getOrgId());
+//        paper.setCreator("feng");
+//        paper.setTotalScore(Double.valueOf((String) paperInfoMap
+//                .get("totalScore")));
+//        paper.setCourse(course);
+//        paper.setCourseName(course.getName());
+//        paper.setCourseNo(course.getCode());
+//        paper.setCreateTime(CommonUtils.getCurDateTime());
+//        paper.setPaperDetailCount(Integer.valueOf((String) paperInfoMap
+//                .get("detailCount")));
+//        paper.setUnitCount(Integer.valueOf((String) paperInfoMap
+//                .get("unitCount")));
+//        paper.setDifficultyDegree(0.5);
+//        return paper;
+//    }
 //
-//			log.debug("第" + i + "个xml文件已经处理完,文件名为:" + filePath);
-//		}
-//		log.debug("处理完成...");
-	}
-
-	// 初始化试卷
-	private Paper initPaper(Map<Object, Object> paperInfoMap, Course course, User user) {
-		Paper paper = new Paper();
-		paper.setName((String) paperInfoMap.get("name"));
-		paper.setTitle((String) paperInfoMap.get("name"));
-		paper.setPaperType(PaperType.IMPORT);
-		paper.setPaperStatus(PaperStatus.DRAFT);
-		paper.setOrgId(course.getOrgId());
-		paper.setCreator(user.getDisplayName());
-		paper.setTotalScore(Double.valueOf((String) paperInfoMap.get("totalScore")));
-		paper.setCourse(course);
-		paper.setCourseName(course.getName());
-		paper.setCourseNo(course.getCode());
-		paper.setCreateTime(CommonUtils.getCurDateTime());
-		paper.setPaperDetailCount(Integer.valueOf((String) paperInfoMap.get("detailCount")));
-		paper.setUnitCount(Integer.valueOf((String) paperInfoMap.get("unitCount")));
-		paper.setDifficultyDegree(0.5);
-		return paper;
-	}
-
-	// 初始化大题集合
-	private List<PaperDetail> initPaperDetails(Map<Object, Object> paperInfoMap, Paper paper, User user) {
-		// 定义大题集合
-		List<PaperDetail> paperDetails = new ArrayList<PaperDetail>();
-		int length = paperInfoMap.size() - 5;
-		for (int i = 0; i < length; i++) {
-			QuestionsTemp detailInfo = (QuestionsTemp) paperInfoMap.get(String.valueOf(i + 1));
-			PaperDetail paperDetail = new PaperDetail();
-			paperDetail.setPaper(paper);
-			paperDetail.setNumber(Integer.valueOf(detailInfo.getNumber()));
-			paperDetail.setName(detailInfo.getName());
-			paperDetail.setScore(Double.valueOf(detailInfo.getTotalScore()));
-			paperDetail.setUnitCount(Integer.valueOf(detailInfo.getCount()));
-			paperDetail.setCreator(user.getDisplayName());
-			paperDetail.setCreateTime(CommonUtils.getCurDateTime());
-			paperDetails.add(paperDetail);
-		}
-		return paperDetails;
-	}
-
-	private String transProblemDocumentName(String problemDocumentName, String impType) {
-		if ("old".equals(impType)) {
-			String s1 = problemDocumentName.substring(0, 1);
-			String s2 = problemDocumentName.substring(1);
-			if ("A".equals(s1)) {
-				return "G"+s2;
-			}
-			if ("B".equals(s1)) {
-				return "H"+s2;
-			}
-			if ("C".equals(s1)) {
-				return "I"+s2;
-			}
-		}
-		return problemDocumentName;
-	}
-
-	public Map<Object, Object> readXml(String xmlPath, String paperNameSuffix, String impType) throws Exception {
-		Map<Object, Object> paperInfoMap = new HashedMap<>();
-		DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();
-		DocumentBuilder b = a.newDocumentBuilder();
-
-		// “file:///”表示是本地计算机,否则报错“unknown protocol”
-		Document document = b.parse("file:///" + xmlPath);
-		NodeList exerciseDocuments = document.getElementsByTagName("ExerciseDocument");
-		// 遍历exerciseDocument节点
-		for (int i = 0; i < exerciseDocuments.getLength(); i++) {
-			// 获取第一个exerciseDocument
-			Node node = exerciseDocuments.item(i);
-			// 获取exerciseDocument节点下的所有属性
-			NamedNodeMap namedNodeMap = node.getAttributes();
-			// 课程代码
-			paperInfoMap.put("courseCode", namedNodeMap.getNamedItem("CourseId").getTextContent());
-			// 试卷名称(后缀)
-			paperInfoMap.put("name", namedNodeMap.getNamedItem("CourseName").getTextContent() + "(" + paperNameSuffix
-					+ ")" + transProblemDocumentName(namedNodeMap.getNamedItem("ProblemDocumentName").getTextContent(),impType));
-			// 试卷总分
-			paperInfoMap.put("totalScore", namedNodeMap.getNamedItem("Score").getTextContent());
-			// 大题数量
-			paperInfoMap.put("detailCount", namedNodeMap.getNamedItem("ProblemCollectionCount").getTextContent());
-			// 小题数量
-			paperInfoMap.put("unitCount", namedNodeMap.getNamedItem("ProblemCount").getTextContent());
-			// 获取ProblemCollection所有节点
-			NodeList problemList = node.getChildNodes();
-			for (int j = 0; j < problemList.getLength(); j++) {
-				// 大题节点
-				Node detailNode = problemList.item(j);
-				if (detailNode.getNodeName().equals("ProblemCollection")) {
-					Map<Object, Object> detailInfoMap = new HashedMap<Object, Object>();
-					QuestionsTemp detailInfo = new QuestionsTemp();
-					// 大题序号
-					detailInfo.setNumber(detailNode.getAttributes().getNamedItem("Index").getTextContent());
-					// 大题名称
-					detailInfo.setName(detailNode.getAttributes().getNamedItem("ProblemTypeName").getTextContent());
-					// 大题总分
-					detailInfo.setTotalScore(detailNode.getAttributes().getNamedItem("Score").getTextContent());
-					// 大题总数
-					detailInfo.setCount(detailNode.getAttributes().getNamedItem("ProblemCount").getTextContent());
-					// 获取所有Problem节点
-					NodeList unitList = detailNode.getChildNodes();
-					for (int k = 0; k < unitList.getLength(); k++) {
-						Node unitNode = unitList.item(k);
-						if (unitNode.getNodeName().equals("Problem")) {
-							QuestionsTemp unitInfo = new QuestionsTemp();
-							// 小题分数
-							unitInfo.setScore(unitNode.getAttributes().getNamedItem("Score").getTextContent());
-							// 小题序号
-							unitInfo.setNumber(unitNode.getAttributes().getNamedItem("Index").getTextContent());
-							// 小题题型
-							String type = unitNode.getAttributes().getNamedItem("ProblemClassType").getTextContent();
-							// 获取题目文本节点
-							NodeList unitInfoList = unitNode.getChildNodes();
-							for (int z = 0; z < unitInfoList.getLength(); z++) {
-								Node unitInfoNode = unitInfoList.item(z);
-								if (unitInfoNode.getNodeName().equals("Content")) {
-									// 小题题干
-									unitInfo.setBody(unitInfoNode.getTextContent());
-								}
-								// 选择题
-								if (unitInfoNode.getNodeName().equals("ChoiceItem")) {
-									NodeList optionsInfoList = unitInfoNode.getChildNodes();
-									String answer = "";
-									if (type.equals("MonomialChoice")) {
-										unitInfo.setType(QuesStructType.SINGLE_ANSWER_QUESTION);
-									}
-									if (type.equals("MultipleChoice")) {
-										unitInfo.setType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
-									}
-									Map<Object, Object> options = new HashedMap<Object, Object>();
-									for (int u = 0; u < optionsInfoList.getLength(); u++) {
-										Node optionsInfoNode = optionsInfoList.item(u);
-										if (optionsInfoNode.getNodeName().equals("Options")) {
-											// 所有选项节点
-											NodeList optionInfoList = optionsInfoNode.getChildNodes();
-											for (int r = 0; r < optionInfoList.getLength(); r++) {
-												Node optionInfoNode = optionInfoList.item(r);
-												if (optionInfoNode.getNodeName().equals("Option")) {
-													// 选项序号,内容
-													options.put(optionInfoNode.getAttributes().getNamedItem("Index")
-															.getTextContent(), optionInfoNode.getTextContent());
-													if (optionInfoNode.getAttributes().getNamedItem("Selected")
-															.getTextContent().equals("True")) {
-														if (StringUtils.isBlank(answer)) {
-															answer = optionInfoNode.getAttributes()
-																	.getNamedItem("Index").getTextContent();
-														} else {
-															answer = answer + "," + optionInfoNode.getAttributes()
-																	.getNamedItem("Index").getTextContent();
-														}
-													}
-												}
-											}
-											// 小题选项
-											unitInfo.setOptions(options);
-											unitInfo.setAnswer(answer);
-										}
-									}
-								}
-								// 完形填空,单选类的阅读理解
-								if (unitInfoNode.getNodeName().equals("ChoiceItems")) {
-									unitInfo.setType(QuesStructType.NESTED_ANSWER_QUESTION);
-									Map<Object, Object> subQues = new HashedMap<Object, Object>();
-									Map<Object, Object> subOptions = new HashedMap<Object, Object>();
-									NodeList choiceItemsList = unitInfoNode.getChildNodes();
-									int number = 1;
-									for (int h = 0; h < choiceItemsList.getLength(); h++) {
-										Node subUnitInfoNode = choiceItemsList.item(h);
-										String answer = "";
-										if (subUnitInfoNode.getNodeName().equals("ChoiceItem")) {
-											// 每一个子题选项
-											QuestionsTemp subUnit = new QuestionsTemp();
-											NodeList subOptionsInfoList = subUnitInfoNode.getChildNodes();
-											for (int hu = 0; hu < subOptionsInfoList.getLength(); hu++) {
-												Node subOptionsInfoNode = subOptionsInfoList.item(hu);
-												if (subOptionsInfoNode.getNodeName().equals("Options")) {
-													// 所有选项节点
-													NodeList subOptionInfoList = subOptionsInfoNode.getChildNodes();
-													for (int hr = 0; hr < subOptionInfoList.getLength(); hr++) {
-														Node subOptionInfoNode = subOptionInfoList.item(hr);
-														if (subOptionInfoNode.getNodeName().equals("Option")) {
-															// 子题选项序号,内容
-															subOptions.put(
-																	subOptionInfoNode.getAttributes()
-																			.getNamedItem("Index").getTextContent(),
-																	subOptionInfoNode.getTextContent());
-															if (subOptionInfoNode.getAttributes()
-																	.getNamedItem("Selected").getTextContent()
-																	.equals("True")) {
-																if (StringUtils.isBlank(answer)) {
-																	answer = subOptionInfoNode.getAttributes()
-																			.getNamedItem("Index").getTextContent();
-																} else {
-																	answer = answer + ","
-																			+ subOptionInfoNode.getAttributes()
-																					.getNamedItem("Index")
-																					.getTextContent();
-																}
-															}
-														}
-													}
-													// 子题选项
-													subUnit.setOptions(subOptions);
-													// 子题答案
-													subUnit.setAnswer(answer);
-													if (answer.contains(",")) {
-														subUnit.setType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
-													} else {
-														subUnit.setType(QuesStructType.SINGLE_ANSWER_QUESTION);
-													}
-												}
-												if (subOptionsInfoNode.getNodeName().equals("Content")) {
-													subUnit.setBody(subOptionsInfoNode.getTextContent());
-												}
-												if (subOptionsInfoNode.getNodeName().equals("Answer")) {
-													subUnit.setType(QuesStructType.TEXT_ANSWER_QUESTION);
-													subUnit.setAnswer(subOptionsInfoNode.getTextContent());
-												}
-											}
-											if (StringUtils.isBlank(subUnit.getBody())) {
-												subUnit.setBody("__________");
-											}
-											subUnit.setNumber(String.valueOf(number));
-											subQues.put(subUnit.getNumber(), subUnit);
-											number++;
-										}
-									}
-									unitInfo.setSubQues(subQues);
-								}
-								// 普通答案
-								if (unitInfoNode.getNodeName().equals("Answer")) {
-									// 判断题
-									if (type.equals("TrueOrFalse")) {
-										unitInfo.setType(QuesStructType.BOOL_ANSWER_QUESTION);
-										String answerString = unitInfoNode.getTextContent();
-										if (answerString.contains("False")) {
-											unitInfo.setAnswer("错误");
-										} else {
-											unitInfo.setAnswer("正确");
-										}
-									}
-									// 主观题
-									if (type.equals("EssayQuestion")) {
-										unitInfo.setType(QuesStructType.TEXT_ANSWER_QUESTION);
-										unitInfo.setAnswer(unitInfoNode.getTextContent());
-									}
-								}
-							}
-							// 添加小题到大题
-							detailInfoMap.put(unitInfo.getNumber(), unitInfo);
-						}
-					}
-					detailInfo.setQues(detailInfoMap);
-					// 添加大题到试卷
-					paperInfoMap.put(detailInfo.getNumber(), detailInfo);
-				}
-			}
-		}
-		return paperInfoMap;
-	}
-
-	// 初始化小题集合
-	private List<PaperDetailUnit> initpaperDetailUnits(Paper paper, List<PaperDetail> paperDetails,
-			List<Question> questionLists, Map<Object, Object> paperInfoMap, Course course, User user)
-			throws Exception {
-		List<PaperDetailUnit> paperDetailUnits = new ArrayList<PaperDetailUnit>();
-		int detailCount = paperDetails.size();
-		int nm = 0;
-		for (int i = 0; i < detailCount; i++) {
-			PaperDetail detail = paperDetails.get(i);
-			QuestionsTemp detailTemp = (QuestionsTemp) paperInfoMap.get(String.valueOf(i + 1));
-			Map<Object, Object> detailInfoMap = detailTemp.getQues();
-			int quesCount = detailInfoMap.size();
-			for (int j = 0; j < quesCount; j++) {
-//				WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
-				QuestionsTemp quesTemp = (QuestionsTemp) detailInfoMap.get(String.valueOf(j + 1));
-				Question question = new Question();
-				question.setCreateTime(CommonUtils.getCurDateTime());
-				question.setScore(Double.valueOf(quesTemp.getScore()));
-				question.setCourse(course);
-				question.setOrgId(course.getOrgId());
-				question.setHasAudio(false);
-				question.setDifficulty("中");
-				question.setDifficultyDegree(0.5);
-				question.setPublicity(true);
-				question.setQuestionType(quesTemp.getType());
-
-				String body = imgList(quesTemp.getBody());
-				question.setQuesBody(replaceBlank(body));
-				try {
-//					question.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(question.getQuesBody())));
-				} catch (Exception e) {
-					log.error("错误题干信息:" + question.getQuesBody());
-					throw new IllegalArgumentException("题干信息错误!"+e.getMessage());
-				}
-				if (question.getQuestionType() == QuesStructType.BOOL_ANSWER_QUESTION) {
-					question.setQuesAnswer(quesTemp.getAnswer());
-//					question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml("<p>" + question.getQuesAnswer() + "</p>")));
-				} else {
-					question.setQuesAnswer(imgList(quesTemp.getAnswer()));
-					try {
-//						question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(question.getQuesAnswer())));
-					} catch (Exception e) {
-						log.error("错误答案信息:" + question.getQuesAnswer());
-						throw new IllegalArgumentException("答案信息错误!"+e.getMessage());
-					}
-				}
-				// 存在选项
-				if (question.getQuestionType() == QuesStructType.SINGLE_ANSWER_QUESTION
-						|| question.getQuestionType() == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
-					List<QuesOption> quesOptions = new ArrayList<QuesOption>();
-					Map<Object, Object> optionMap = quesTemp.getOptions();
-					int optionCount = optionMap.size();
-					for (int k = 0; k < optionCount; k++) {
-						QuesOption quesOption = new QuesOption();
-						quesOption.setNumber(String.valueOf(k + 1));
-
-						String optionBody = imgList((String) optionMap.get(String.valueOf(k + 1)));
-						if (optionBody.startsWith("<p><p") || optionBody.startsWith("<P><P")) {
-							quesOption.setOptionBody(replaceFirstP(optionBody));
-						} else {
-							quesOption.setOptionBody(optionBody);
-						}
-
-						try {
-//							quesOption.setOptionBodyWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(quesOption.getOptionBody())));
-						} catch (Exception e) {
-							log.error("错误的选项:" + quesOption.getOptionBody());
-							throw new IllegalArgumentException("选项信息错误!"+e.getMessage());
-						}
-						if (question.getQuesAnswer().contains(String.valueOf(k + 1))) {
-							quesOption.setIsCorrect((short) 1);
-						} else {
-							quesOption.setIsCorrect((short) 0);
-						}
-						quesOptions.add(quesOption);
-					}
-					question.setQuesOptions(quesOptions);
-					String[] answers = question.getQuesAnswer().replaceAll("<p>", "").replaceAll("</p>", "")
-							.replaceAll("<P>", "").replaceAll("</P>", "").split(",");
-					String answer = "";
-					for (int a = 0; a < answers.length; a++) {
-						char c1 = (char) (Integer.valueOf(answers[a]) + 64);
-						if (a == 0) {
-							answer = String.valueOf(c1);
-						} else {
-							answer = answer + "," + c1;
-						}
-					}
-					question.setQuesAnswer("<p>" + answer + "</p>");
-//					question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(question.getQuesAnswer())));
-				}
-				// 存在子题
-				if (question.getQuestionType() == QuesStructType.NESTED_ANSWER_QUESTION) {
-					List<Question> subQuestions = new ArrayList<>();
-					int subQuesCount = quesTemp.getSubQues().size();
-					BigDecimal totalScore = BigDecimal.valueOf(question.getScore());
-					BigDecimal sum = BigDecimal.valueOf(subQuesCount);
-					double score = totalScore.divide(sum).doubleValue();
-					for (int s = 0; s < subQuesCount; s++) {
-						QuestionsTemp subQuesTmp = (QuestionsTemp) quesTemp.getSubQues().get(String.valueOf(s + 1));
-						Question subQuestion = new Question();
-						subQuestion.setId(IdUtils.uuid());
-						subQuestion.setQuestionType(subQuesTmp.getType());
-						subQuestion.setDifficulty("中");
-						subQuestion.setDifficultyDegree(0.5);
-						subQuestion.setPublicity(true);
-						subQuestion.setScore(score);
-
-						String subBody = imgList(subQuesTmp.getBody());
-						question.setQuesBody(replaceBlank(body));
-						subQuestion.setQuesBody(subBody);
-
-//						subQuestion.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(subQuestion.getQuesBody())));
-						subQuestion.setQuesAnswer(imgList(subQuesTmp.getAnswer()));
-//						subQuestion.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(subQuestion.getQuesAnswer())));
-						// 存在选项
-						if (subQuestion.getQuestionType() == QuesStructType.SINGLE_ANSWER_QUESTION
-								|| subQuestion.getQuestionType() == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
-							List<QuesOption> subQuesOptions = new ArrayList<QuesOption>();
-							Map<Object, Object> subOptionMap = subQuesTmp.getOptions();
-							int subOptionCount = subOptionMap.size();
-							for (int k = 0; k < subOptionCount; k++) {
-								QuesOption subQuesOption = new QuesOption();
-								subQuesOption.setNumber(String.valueOf(k));
-
-								String optionBody = imgList((String) subOptionMap.get(String.valueOf(k + 1)));
-								if (optionBody.startsWith("<p><p") || optionBody.startsWith("<P><P")) {
-									subQuesOption.setOptionBody(replaceFirstP(optionBody));
-								} else {
-									subQuesOption.setOptionBody(optionBody);
-								}
-
-//								subQuesOption.setOptionBodyWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(subQuesOption.getOptionBody())));
-								if (subQuestion.getQuesAnswer().contains(String.valueOf(k + 1))) {
-									subQuesOption.setIsCorrect((short) 1);
-								} else {
-									subQuesOption.setIsCorrect((short) 0);
-								}
-								subQuesOptions.add(subQuesOption);
-							}
-							subQuestion.setQuesOptions(subQuesOptions);
-							String[] answers = subQuestion.getQuesAnswer().replaceAll("<p>", "").replaceAll("</p>", "")
-									.replaceAll("<P>", "").replaceAll("</P>", "").split(",");
-							String answer = "";
-							for (int a = 0; a < answers.length; a++) {
-								char c1 = (char) (Integer.valueOf(answers[a]) + 64);
-								if (a == 0) {
-									answer = String.valueOf(c1);
-								} else {
-									answer = answer + "," + c1;
-								}
-							}
-							subQuestion.setQuesAnswer(answer);
-//							subQuestion.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml("<p>" + subQuestion.getQuesAnswer() + "</p>")));
-						}
-						subQuestions.add(subQuestion);
-					}
-					question.setSubQuestions(subQuestions);
-				}
-//				byte[] pkgByte = DocxProcessUtil.getPkgByte(wordMLPackage);
-//				QuestionPkgPath quesPkgPath = new QuestionPkgPath(pkgByte);
-				questionLists.add(question);
-				// 包装小题
-				PaperDetailUnit paperDetailUnit = new PaperDetailUnit();
-				paperDetailUnit.setPaper(paper);
-				paperDetailUnit.setNumber(nm + 1);
-				paperDetailUnit.setScore(question.getScore());
-				paperDetailUnit.setPaperDetail(detail);
-				paperDetailUnit.setQuestionType(question.getQuestionType());
-				paperDetailUnit.setCreator(user.getDisplayName());
-				paperDetailUnit.setCreateTime(CommonUtils.getCurDateTime());
-				paperDetailUnit.setQuestion(question);
-				paperDetailUnits.add(paperDetailUnit);
-				paperDetailUnit.setPaperType(PaperType.IMPORT);
-				nm++;
-			}
-		}
-		return paperDetailUnits;
-	}
-
-	public String imgList(String str) throws Exception {
-		if (StringUtils.isBlank(str)) {
-			str = "<p></p>";
-		}
-		str = str.trim().replace("<br>", "").replace("</br>", "");
-		if (!str.contains("<p>") && !str.contains("</P>")) {
-			str = "<p>" + str + "</p>";
-		}
-		// 先处理span标签
-		List<String> spans = parseSpans(str);
-		if (spans != null && spans.size() > 0) {
-			for (String span : spans) {
-				str = str.replace(span, "").replace("</span>", "").replace("</SPAN>", "");
-			}
-		}
-		str = str.replace("<o:p>", "").replace("</o:p>", "").replace("border=0", "").replace("class=MsoNormal", "")
-				.replace("&phiv;", "").replace("</SPAN>", "");
-		// 获取img标签
-		List<String> srcList = ImgDataUtils.parseImages(str);
-		if (srcList != null && srcList.size() > 0) {
-			for (String img : srcList) {
-				// 获取height,width值
-				List<String> height = getTagAHei(img);
-				List<String> width = getTagAWid(img);
-				List<String> parseImageSrc = ImgDataUtils.parseImageSrc(img);
-				if (parseImageSrc != null && parseImageSrc.size() > 0) {
-					String src = parseImageSrc.get(0).replace("{ResourcePath}", "http://file.5any.com/UniversityV4.0");
-					String url = regexCH(src);
-					log.info("img url:" + url);
-					url = url.replaceAll("\\\\", "/");
-
-					String base64 = ImgDataUtils.loadImageToBase64(url);
-					if (base64 == null) {
-						throw new Exception("图片下载失败!" + url);
-					} else {
-						if (src.contains("jpg")) {
-							str = str.replace(parseImageSrc.get(0), "data:image/jpg;base64," + base64);
-						} else {
-							str = str.replace(parseImageSrc.get(0), "data:image/png;base64," + base64);
-						}
-						if (height != null && height.size() > 0) {
-							str = str.replace("height=" + height.get(0), "height=\"" + height.get(0) + "\"");
-						}
-						if (width != null && width.size() > 0) {
-							str = str.replace("width=" + width.get(0), "width=\"" + width.get(0) + "\"");
-						}
-					}
-				}
-			}
-		}
-		return str.replace("<IMG", "<img");
-	}
-
-	// 將url路徑中的中文转码
-	public String regexCH(String str) throws UnsupportedEncodingException {
-		StringBuffer s = new StringBuffer();
-		Pattern pat = Pattern.compile("[\u4E00-\u9FA5]");
-		Matcher mat = pat.matcher(str);
-		while (mat.find()) {
-			s.append(mat.group());
-		}
-		String url = java.net.URLEncoder.encode(s.toString(), "utf-8");
-		return str.replace(s.toString(), url);
-	}
-
-//	public List<String> loadFiles() {
-	// 获取某文件夹下所有XML文件的路径
-//		List<String> paths = new ArrayList<>();
-//		File dir = new File(rootDir);
-//		this.loadMoreFiles(dir, paths);
-//		return paths;
-//	}
-
-	private void loadMoreFiles(File file, List<String> paths) {
-		if (file.isDirectory()) {
-			File[] subFiles = file.listFiles();
-			for (File subFile : subFiles) {
-				this.loadMoreFiles(subFile, paths);
-			}
-		} else {
-			String path = file.getPath().replaceAll("\\\\", "/");
-
-			if (file.getName().endsWith(".xml")) {
-				paths.add(path);
-			} else {
-				log.error("无效文件:" + path);
-			}
-		}
-	}
-
-	public static List<String> parseSpans(String content) {
-		if (content == null) {
-			return new ArrayList<>();
-		}
-		List<String> spans = new ArrayList<>();
-		String reg = "<(span|SPAN)(.*?)(/>|>)";
-		Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
-		Matcher matcher = pattern.matcher(content);
-		while (matcher.find()) {
-			String span = matcher.group();
-			spans.add(span);
-		}
-		return spans;
-	}
-
-	public List<String> getTagAHei(String htmlString) {
-		List<String> list = new ArrayList<String>();
-		Pattern p = Pattern.compile("<IMG[^<>]*\\s+height=([0-9A-Za-z-_.]+)\\s*");
-		Matcher m = p.matcher(htmlString);
-		while (m.find()) {
-			String str = m.group(1);
-			list.add(str);
-		}
-		return list;
-	}
-
-	public List<String> getTagAWid(String htmlString) {
-		List<String> list = new ArrayList<String>();
-		Pattern p = Pattern.compile("<IMG[^<>]*\\s+width=([0-9A-Za-z-_.]+)\\s*");
-		Matcher m = p.matcher(htmlString);
-		while (m.find()) {
-			String str = m.group(1);
-			list.add(str);
-		}
-		return list;
-	}
-
-	/**
-	 * 将[BLANK] 替换为 ###
-	 */
-	public static String replaceBlank(String str) {
-		if (str == null) {
-			return null;
-		}
-		str=str.replaceAll("<div>", "<p>");
-		str=str.replaceAll("</div>", "</p>");
-		return str.replaceAll("[BLANK]", "###");
-	}
-
-	/**
-	 * 替换首个P标签
-	 */
-	public static String replaceFirstP(String str) {
-		if (str == null) {
-			return null;
-		}
-		if (str.startsWith("<p>") && str.endsWith("</p>")) {
-			// 去掉头<p >
-			str = str.replaceFirst("<p>", "");
-			// 去掉尾</p>
-			int index = str.lastIndexOf("</p>");
-			if (index > 0) {
-				str = str.substring(0, index);
-			}
-		}
-		return str;
-	}
+//    // 初始化大题集合
+//    private List<PaperDetail> initPaperDetails(
+//            Map<Object, Object> paperInfoMap, Paper paper) {
+//        // 定义大题集合
+//        List<PaperDetail> paperDetails = new ArrayList<PaperDetail>();
+//        int length = paperInfoMap.size() - 5;
+//        for (int i = 0; i < length; i++) {
+//            QuestionsTemp detailInfo = (QuestionsTemp) paperInfoMap.get(String
+//                    .valueOf(i + 1));
+//            PaperDetail paperDetail = new PaperDetail();
+//            paperDetail.setPaper(paper);
+//            paperDetail.setNumber(Integer.valueOf(detailInfo.getNumber()));
+//            paperDetail.setName(detailInfo.getName());
+//            paperDetail.setScore(Double.valueOf(detailInfo.getTotalScore()));
+//            paperDetail.setUnitCount(Integer.valueOf(detailInfo.getCount()));
+//            paperDetail.setCreator("feng");
+//            paperDetail.setCreateTime(CommonUtils.getCurDateTime());
+//            paperDetails.add(paperDetail);
+//        }
+//        return paperDetails;
+//    }
+
+    public Map<Object, Object> readXml(String xmlPath, String paperNameSuffix) throws Exception {
+        Map<Object, Object> paperInfoMap = new HashedMap<>();
+        DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();
+        DocumentBuilder b = a.newDocumentBuilder();
+
+        // “file:///”表示是本地计算机,否则报错“unknown protocol”
+        Document document = b.parse("file:///" + xmlPath);
+        NodeList exerciseDocuments = document
+                .getElementsByTagName("ExerciseDocument");
+        // 遍历exerciseDocument节点
+        for (int i = 0; i < exerciseDocuments.getLength(); i++) {
+            // 获取第一个exerciseDocument
+            Node node = exerciseDocuments.item(i);
+            // 获取exerciseDocument节点下的所有属性
+            NamedNodeMap namedNodeMap = node.getAttributes();
+            // 课程代码
+            paperInfoMap.put("courseCode", namedNodeMap.getNamedItem("CourseId").getTextContent());
+            // 试卷名称(后缀)
+            paperInfoMap.put("name", namedNodeMap.getNamedItem("CourseName").getTextContent() + namedNodeMap.getNamedItem("ProblemDocumentName").getTextContent() + "(" + paperNameSuffix + ")");
+            // 试卷总分
+            paperInfoMap.put("totalScore", namedNodeMap.getNamedItem("Score").getTextContent());
+            // 大题数量
+            paperInfoMap.put("detailCount", namedNodeMap.getNamedItem("ProblemCollectionCount").getTextContent());
+            // 小题数量
+            paperInfoMap.put("unitCount", namedNodeMap.getNamedItem("ProblemCount").getTextContent());
+            // 获取ProblemCollection所有节点
+            NodeList problemList = node.getChildNodes();
+            for (int j = 0; j < problemList.getLength(); j++) {
+                // 大题节点
+                Node detailNode = problemList.item(j);
+                if (detailNode.getNodeName().equals("ProblemCollection")) {
+                    Map<Object, Object> detailInfoMap = new HashedMap<Object, Object>();
+                    QuestionsTemp detailInfo = new QuestionsTemp();
+                    // 大题序号
+                    detailInfo.setNumber(detailNode.getAttributes().getNamedItem("Index").getTextContent());
+                    // 大题名称
+                    detailInfo.setName(detailNode.getAttributes().getNamedItem("ProblemTypeName").getTextContent());
+                    // 大题总分
+                    detailInfo.setTotalScore(detailNode.getAttributes().getNamedItem("Score").getTextContent());
+                    // 大题总数
+                    detailInfo.setCount(detailNode.getAttributes().getNamedItem("ProblemCount").getTextContent());
+                    // 获取所有Problem节点
+                    NodeList unitList = detailNode.getChildNodes();
+                    for (int k = 0; k < unitList.getLength(); k++) {
+                        Node unitNode = unitList.item(k);
+                        if (unitNode.getNodeName().equals("Problem")) {
+                            QuestionsTemp unitInfo = new QuestionsTemp();
+                            // 小题分数
+                            unitInfo.setScore(unitNode.getAttributes().getNamedItem("Score").getTextContent());
+                            // 小题序号
+                            unitInfo.setNumber(unitNode.getAttributes().getNamedItem("Index").getTextContent());
+                            // 小题题型
+                            String type = unitNode.getAttributes().getNamedItem("ProblemClassType").getTextContent();
+                            // 获取题目文本节点
+                            NodeList unitInfoList = unitNode.getChildNodes();
+                            for (int z = 0; z < unitInfoList.getLength(); z++) {
+                                Node unitInfoNode = unitInfoList.item(z);
+                                if (unitInfoNode.getNodeName().equals("Content")) {
+                                    // 小题题干
+                                    unitInfo.setBody(unitInfoNode.getTextContent());
+                                }
+                                // 选择题
+                                if (unitInfoNode.getNodeName().equals("ChoiceItem")) {
+                                    NodeList optionsInfoList = unitInfoNode.getChildNodes();
+                                    String answer = "";
+                                    if (type.equals("MonomialChoice")) {
+                                        unitInfo.setType(QuesStructType.SINGLE_ANSWER_QUESTION);
+                                    }
+                                    if (type.equals("MultipleChoice")) {
+                                        unitInfo.setType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
+                                    }
+                                    Map<Object, Object> options = new HashedMap<Object, Object>();
+                                    for (int u = 0; u < optionsInfoList.getLength(); u++) {
+                                        Node optionsInfoNode = optionsInfoList.item(u);
+                                        if (optionsInfoNode.getNodeName().equals("Options")) {
+                                            // 所有选项节点
+                                            NodeList optionInfoList = optionsInfoNode.getChildNodes();
+                                            for (int r = 0; r < optionInfoList.getLength(); r++) {
+                                                Node optionInfoNode = optionInfoList.item(r);
+                                                if (optionInfoNode.getNodeName().equals("Option")) {
+                                                    // 选项序号,内容
+                                                    options.put(optionInfoNode.getAttributes().getNamedItem("Index").getTextContent(), optionInfoNode.getTextContent());
+                                                    if (optionInfoNode.getAttributes().getNamedItem("Selected").getTextContent().equals("True")) {
+                                                        if (StringUtils.isBlank(answer)) {
+                                                            answer = optionInfoNode.getAttributes().getNamedItem("Index").getTextContent();
+                                                        } else {
+                                                            answer = answer + "," + optionInfoNode.getAttributes().getNamedItem("Index").getTextContent();
+                                                        }
+                                                    }
+                                                }
+                                            }
+                                            // 小题选项
+                                            unitInfo.setOptions(options);
+                                            unitInfo.setAnswer(answer);
+                                        }
+                                    }
+                                }
+                                // 完形填空,单选类的阅读理解
+                                if (unitInfoNode.getNodeName().equals("ChoiceItems")) {
+                                    unitInfo.setType(QuesStructType.NESTED_ANSWER_QUESTION);
+                                    Map<Object, Object> subQues = new HashedMap<Object, Object>();
+                                    Map<Object, Object> subOptions = new HashedMap<Object, Object>();
+                                    NodeList choiceItemsList = unitInfoNode.getChildNodes();
+                                    int number = 1;
+                                    for (int h = 0; h < choiceItemsList.getLength(); h++) {
+                                        Node subUnitInfoNode = choiceItemsList.item(h);
+                                        String answer = "";
+                                        if (subUnitInfoNode.getNodeName().equals("ChoiceItem")) {
+                                            // 每一个子题选项
+                                            QuestionsTemp subUnit = new QuestionsTemp();
+                                            NodeList subOptionsInfoList = subUnitInfoNode.getChildNodes();
+                                            for (int hu = 0; hu < subOptionsInfoList.getLength(); hu++) {
+                                                Node subOptionsInfoNode = subOptionsInfoList.item(hu);
+                                                if (subOptionsInfoNode.getNodeName().equals("Options")) {
+                                                    // 所有选项节点
+                                                    NodeList subOptionInfoList = subOptionsInfoNode.getChildNodes();
+                                                    for (int hr = 0; hr < subOptionInfoList.getLength(); hr++) {
+                                                        Node subOptionInfoNode = subOptionInfoList.item(hr);
+                                                        if (subOptionInfoNode.getNodeName().equals("Option")) {
+                                                            // 子题选项序号,内容
+                                                            subOptions.put(subOptionInfoNode.getAttributes().getNamedItem("Index").getTextContent(), subOptionInfoNode.getTextContent());
+                                                            if (subOptionInfoNode.getAttributes().getNamedItem("Selected").getTextContent().equals("True")) {
+                                                                if (StringUtils.isBlank(answer)) {
+                                                                    answer = subOptionInfoNode.getAttributes().getNamedItem("Index").getTextContent();
+                                                                } else {
+                                                                    answer = answer + "," + subOptionInfoNode.getAttributes().getNamedItem("Index").getTextContent();
+                                                                }
+                                                            }
+                                                        }
+                                                    }
+                                                    // 子题选项
+                                                    subUnit.setOptions(subOptions);
+                                                    // 子题答案
+                                                    subUnit.setAnswer(answer);
+                                                    if (answer.contains(",")) {
+                                                        subUnit.setType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
+                                                    } else {
+                                                        subUnit.setType(QuesStructType.SINGLE_ANSWER_QUESTION);
+                                                    }
+                                                }
+                                                if (subOptionsInfoNode.getNodeName().equals("Content")) {
+                                                    subUnit.setBody(subOptionsInfoNode.getTextContent());
+                                                }
+                                                if (subOptionsInfoNode.getNodeName().equals("Answer")) {
+                                                    subUnit.setType(QuesStructType.TEXT_ANSWER_QUESTION);
+                                                    subUnit.setAnswer(subOptionsInfoNode.getTextContent());
+                                                }
+                                            }
+                                            if (StringUtils.isBlank(subUnit.getBody())) {
+                                                subUnit.setBody("__________");
+                                            }
+                                            subUnit.setNumber(String.valueOf(number));
+                                            subQues.put(subUnit.getNumber(), subUnit);
+                                            number++;
+                                        }
+                                    }
+                                    unitInfo.setSubQues(subQues);
+                                }
+                                // 普通答案
+                                if (unitInfoNode.getNodeName().equals("Answer")) {
+                                    // 判断题
+                                    if (type.equals("TrueOrFalse")) {
+                                        unitInfo.setType(QuesStructType.BOOL_ANSWER_QUESTION);
+                                        String answerString = unitInfoNode.getTextContent();
+                                        if (answerString.contains("False")) {
+                                            unitInfo.setAnswer("错误");
+                                        } else {
+                                            unitInfo.setAnswer("正确");
+                                        }
+                                    }
+                                    // 主观题
+                                    if (type.equals("EssayQuestion")) {
+                                        unitInfo.setType(QuesStructType.TEXT_ANSWER_QUESTION);
+                                        unitInfo.setAnswer(unitInfoNode.getTextContent());
+                                    }
+                                }
+                            }
+                            // 添加小题到大题
+                            detailInfoMap.put(unitInfo.getNumber(), unitInfo);
+                        }
+                    }
+                    detailInfo.setQues(detailInfoMap);
+                    // 添加大题到试卷
+                    paperInfoMap.put(detailInfo.getNumber(), detailInfo);
+                }
+            }
+        }
+        return paperInfoMap;
+    }
+
+    // 初始化小题集合
+//    private List<PaperDetailUnit> initpaperDetailUnits(Paper paper, List<PaperDetail> paperDetails, Map<Question, QuestionPkgPath> map,
+//                                                       Map<Object, Object> paperInfoMap, Course course) throws Exception {
+//        List<PaperDetailUnit> paperDetailUnits = new ArrayList<PaperDetailUnit>();
+//        int detailCount = paperDetails.size();
+//        int nm = 0;
+//        for (int i = 0; i < detailCount; i++) {
+//            PaperDetail detail = paperDetails.get(i);
+//            QuestionsTemp detailTemp = (QuestionsTemp) paperInfoMap.get(String
+//                    .valueOf(i + 1));
+//            Map<Object, Object> detailInfoMap = detailTemp.getQues();
+//            int quesCount = detailInfoMap.size();
+//            for (int j = 0; j < quesCount; j++) {
+//                WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
+//                        .createPackage();
+//                QuestionsTemp quesTemp = (QuestionsTemp) detailInfoMap
+//                        .get(String.valueOf(j + 1));
+//                Question question = new Question();
+//                question.setCreateTime(CommonUtils.getCurDateTime());
+//                question.setScore(Double.valueOf(quesTemp.getScore()));
+//                question.setCourse(course);
+//                question.setOrgId(course.getOrgId());
+//                question.setHasAudio(false);
+//                question.setDifficulty("中");
+//                question.setDifficultyDegree(0.5);
+//                question.setPublicity(true);
+//                question.setQuestionType(quesTemp.getType());
+//
+//                String body = imgList(quesTemp.getBody());
+//                question.setQuesBody(replaceBlank(body));
+//                try {
+//                    question.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(question.getQuesBody())));
+//                } catch (Exception e) {
+//                    log.debug("错误题干信息:" + question.getQuesBody());
+//                    throw new IllegalArgumentException("题干信息错误!");
+//                }
+//                if (question.getQuestionType() == QuesStructType.BOOL_ANSWER_QUESTION) {
+//                    question.setQuesAnswer(quesTemp.getAnswer());
+//                    question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml("<p>" + question.getQuesAnswer() + "</p>")));
+//                } else {
+//                    question.setQuesAnswer(imgList(quesTemp.getAnswer()));
+//                    try {
+//                        question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(question.getQuesAnswer())));
+//                    } catch (Exception e) {
+//                        log.debug("错误答案信息:" + question.getQuesAnswer());
+//                        throw new IllegalArgumentException("答案信息错误!");
+//                    }
+//                }
+//                // 存在选项
+//                if (question.getQuestionType() == QuesStructType.SINGLE_ANSWER_QUESTION
+//                        || question.getQuestionType() == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
+//                    List<QuesOption> quesOptions = new ArrayList<QuesOption>();
+//                    Map<Object, Object> optionMap = quesTemp.getOptions();
+//                    int optionCount = optionMap.size();
+//                    for (int k = 0; k < optionCount; k++) {
+//                        QuesOption quesOption = new QuesOption();
+//                        quesOption.setNumber(String.valueOf(k + 1));
+//
+//                        String optionBody = imgList((String) optionMap.get(String.valueOf(k + 1)));
+//                        if (optionBody.startsWith("<p><p") || optionBody.startsWith("<P><P")) {
+//                            quesOption.setOptionBody(replaceFirstP(optionBody));
+//                        } else {
+//                            quesOption.setOptionBody(optionBody);
+//                        }
+//
+//                        try {
+//                            quesOption.setOptionBodyWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(quesOption.getOptionBody())));
+//                        } catch (Exception e) {
+//                            log.debug("错误的选项:" + quesOption.getOptionBody());
+//                            throw new IllegalArgumentException("选项信息错误!");
+//                        }
+//                        if (question.getQuesAnswer().contains(String.valueOf(k + 1))) {
+//                            quesOption.setIsCorrect((short) 1);
+//                        } else {
+//                            quesOption.setIsCorrect((short) 0);
+//                        }
+//                        quesOptions.add(quesOption);
+//                    }
+//                    question.setQuesOptions(quesOptions);
+//                    String[] answers = question.getQuesAnswer()
+//                            .replaceAll("<p>", "").replaceAll("</p>", "")
+//                            .replaceAll("<P>", "").replaceAll("</P>", "")
+//                            .split(",");
+//                    String answer = "";
+//                    for (int a = 0; a < answers.length; a++) {
+//                        char c1 = (char) (Integer.valueOf(answers[a]) + 64);
+//                        if (a == 0) {
+//                            answer = String.valueOf(c1);
+//                        } else {
+//                            answer = answer + "," + c1;
+//                        }
+//                    }
+//                    question.setQuesAnswer("<p>" + answer + "</p>");
+//                    question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(question.getQuesAnswer())));
+//                }
+//                // 存在子题
+//                if (question.getQuestionType() == QuesStructType.NESTED_ANSWER_QUESTION) {
+//                    List<Question> subQuestions = new ArrayList<>();
+//                    int subQuesCount = quesTemp.getSubQues().size();
+//                    BigDecimal totalScore = BigDecimal.valueOf(question.getScore());
+//                    BigDecimal sum = BigDecimal.valueOf(subQuesCount);
+//                    double score = totalScore.divide(sum).doubleValue();
+//                    for (int s = 0; s < subQuesCount; s++) {
+//                        QuestionsTemp subQuesTmp = (QuestionsTemp) quesTemp.getSubQues().get(String.valueOf(s + 1));
+//                        Question subQuestion = new Question();
+//                        subQuestion.setId(IdUtils.uuid());
+//                        subQuestion.setQuestionType(subQuesTmp.getType());
+//                        subQuestion.setDifficulty("中");
+//                        subQuestion.setDifficultyDegree(0.5);
+//                        subQuestion.setPublicity(true);
+//                        subQuestion.setScore(score);
+//
+//                        String subBody = imgList(subQuesTmp.getBody());
+//                        question.setQuesBody(replaceBlank(body));
+//                        subQuestion.setQuesBody(subBody);
+//
+//                        subQuestion.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(subQuestion.getQuesBody())));
+//                        subQuestion.setQuesAnswer(imgList(subQuesTmp.getAnswer()));
+//                        subQuestion.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(subQuestion.getQuesAnswer())));
+//                        // 存在选项
+//                        if (subQuestion.getQuestionType() == QuesStructType.SINGLE_ANSWER_QUESTION
+//                                || subQuestion.getQuestionType() == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
+//                            List<QuesOption> subQuesOptions = new ArrayList<QuesOption>();
+//                            Map<Object, Object> subOptionMap = subQuesTmp.getOptions();
+//                            int subOptionCount = subOptionMap.size();
+//                            for (int k = 0; k < subOptionCount; k++) {
+//                                QuesOption subQuesOption = new QuesOption();
+//                                subQuesOption.setNumber(String.valueOf(k));
+//
+//                                String optionBody = imgList((String) subOptionMap.get(String.valueOf(k + 1)));
+//                                if (optionBody.startsWith("<p><p") || optionBody.startsWith("<P><P")) {
+//                                    subQuesOption.setOptionBody(replaceFirstP(optionBody));
+//                                } else {
+//                                    subQuesOption.setOptionBody(optionBody);
+//                                }
+//
+//                                subQuesOption.setOptionBodyWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(subQuesOption.getOptionBody())));
+//                                if (subQuestion.getQuesAnswer().contains(String.valueOf(k + 1))) {
+//                                    subQuesOption.setIsCorrect((short) 1);
+//                                } else {
+//                                    subQuesOption.setIsCorrect((short) 0);
+//                                }
+//                                subQuesOptions.add(subQuesOption);
+//                            }
+//                            subQuestion.setQuesOptions(subQuesOptions);
+//                            String[] answers = subQuestion.getQuesAnswer()
+//                                    .replaceAll("<p>", "").replaceAll("</p>", "")
+//                                    .replaceAll("<P>", "").replaceAll("</P>", "")
+//                                    .split(",");
+//                            String answer = "";
+//                            for (int a = 0; a < answers.length; a++) {
+//                                char c1 = (char) (Integer.valueOf(answers[a]) + 64);
+//                                if (a == 0) {
+//                                    answer = String.valueOf(c1);
+//                                } else {
+//                                    answer = answer + "," + c1;
+//                                }
+//                            }
+//                            subQuestion.setQuesAnswer(answer);
+//                            subQuestion.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml("<p>" + subQuestion.getQuesAnswer() + "</p>")));
+//                        }
+//                        subQuestions.add(subQuestion);
+//                    }
+//                    question.setSubQuestions(subQuestions);
+//                }
+//                byte[] pkgByte = DocxProcessUtil.getPkgByte(wordMLPackage);
+//                QuestionPkgPath quesPkgPath = new QuestionPkgPath(pkgByte);
+//                map.put(question, quesPkgPath);
+//                // 包装小题
+//                PaperDetailUnit paperDetailUnit = new PaperDetailUnit();
+//                paperDetailUnit.setPaper(paper);
+//                paperDetailUnit.setNumber(nm + 1);
+//                paperDetailUnit.setScore(question.getScore());
+//                paperDetailUnit.setPaperDetail(detail);
+//                paperDetailUnit.setQuestionType(question.getQuestionType());
+//                paperDetailUnit.setCreator("feng");
+//                paperDetailUnit.setCreateTime(CommonUtils.getCurDateTime());
+//                paperDetailUnit.setQuestion(question);
+//                paperDetailUnits.add(paperDetailUnit);
+//                nm++;
+//            }
+//        }
+//        return paperDetailUnits;
+//    }
+
+    public String imgList(String str) throws Exception {
+        if (StringUtils.isBlank(str)) {
+            str = "<p></p>";
+        }
+        str = str.trim().replace("<br>", "").replace("</br>", "");
+        if (!str.contains("<p>") && !str.contains("</P>")) {
+            str = "<p>" + str + "</p>";
+        }
+        //先处理span标签
+        List<String> spans = parseSpans(str);
+        if (spans != null && spans.size() > 0) {
+            for (String span : spans) {
+                str = str.replace(span, "").replace("</span>", "").replace("</SPAN>", "");
+            }
+        }
+        str = str.replace("<o:p>", "").replace("</o:p>", "").replace("border=0", "").replace("class=MsoNormal", "").replace("&phiv;", "").replace("</SPAN>", "");
+        // 获取img标签
+        List<String> srcList = ImgDataUtils.parseImages(str);
+        if (srcList != null && srcList.size() > 0) {
+            for (String img : srcList) {
+                // 获取height,width值
+                List<String> height = getTagAHei(img);
+                List<String> width = getTagAWid(img);
+                List<String> parseImageSrc = ImgDataUtils.parseImageSrc(img);
+                if (parseImageSrc != null && parseImageSrc.size() > 0) {
+                    String src = parseImageSrc.get(0).replace("{ResourcePath}", "http://file.5any.com/UniversityV4.0");
+                    String url = regexCH(src);
+                    log.info("img url:" + url);
+                    url = url.replaceAll("\\\\", "/");
+
+                    String base64 = ImgDataUtils.loadImageToBase64(url);
+                    if (base64 == null) {
+                        throw new Exception("图片下载失败!" + url);
+                    } else {
+                        if (src.contains("jpg")) {
+                            str = str.replace(parseImageSrc.get(0),
+                                    "data:image/jpg;base64," + base64);
+                        } else {
+                            str = str.replace(parseImageSrc.get(0),
+                                    "data:image/png;base64," + base64);
+                        }
+                        if (height != null && height.size() > 0) {
+                            str = str.replace("height=" + height.get(0),
+                                    "height=\"" + height.get(0) + "\"");
+                        }
+                        if (width != null && width.size() > 0) {
+                            str = str.replace("width=" + width.get(0),
+                                    "width=\"" + width.get(0) + "\"");
+                        }
+                    }
+                }
+            }
+        }
+        return str.replace("<IMG", "<img");
+    }
+
+    // 將url路徑中的中文转码
+    public String regexCH(String str) throws UnsupportedEncodingException {
+        StringBuffer s = new StringBuffer();
+        Pattern pat = Pattern.compile("[\u4E00-\u9FA5]");
+        Matcher mat = pat.matcher(str);
+        while (mat.find()) {
+            s.append(mat.group());
+        }
+        String url = java.net.URLEncoder.encode(s.toString(), "utf-8");
+        return str.replace(s.toString(), url);
+    }
+
+    public List<String> loadFiles() {
+        // 获取某文件夹下所有XML文件的路径
+        List<String> paths = new ArrayList<>();
+        File dir = new File(rootDir);
+        this.loadMoreFiles(dir, paths);
+        return paths;
+    }
+
+    private void loadMoreFiles(File file, List<String> paths) {
+        if (file.isDirectory()) {
+            File[] subFiles = file.listFiles();
+            for (File subFile : subFiles) {
+                this.loadMoreFiles(subFile, paths);
+            }
+        } else {
+            String path = file.getPath()
+                    .replaceAll("\\\\", "/");
+
+            if (file.getName().endsWith(".xml")) {
+                paths.add(path);
+            } else {
+                log.debug("无效文件:" + path);
+            }
+        }
+    }
+
+    public static List<String> parseSpans(String content) {
+        if (content == null) {
+            return new ArrayList<>();
+        }
+        List<String> spans = new ArrayList<>();
+        String reg = "<(span|SPAN)(.*?)(/>|>)";
+        Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
+        Matcher matcher = pattern.matcher(content);
+        while (matcher.find()) {
+            String span = matcher.group();
+            spans.add(span);
+        }
+        return spans;
+    }
+
+    public List<String> getTagAHei(String htmlString) {
+        List<String> list = new ArrayList<String>();
+        Pattern p = Pattern
+                .compile("<IMG[^<>]*\\s+height=([0-9A-Za-z-_.]+)\\s*");
+        Matcher m = p.matcher(htmlString);
+        while (m.find()) {
+            String str = m.group(1);
+            list.add(str);
+        }
+        return list;
+    }
+
+    public List<String> getTagAWid(String htmlString) {
+        List<String> list = new ArrayList<String>();
+        Pattern p = Pattern
+                .compile("<IMG[^<>]*\\s+width=([0-9A-Za-z-_.]+)\\s*");
+        Matcher m = p.matcher(htmlString);
+        while (m.find()) {
+            String str = m.group(1);
+            list.add(str);
+        }
+        return list;
+    }
+
+    /**
+     * 将[BLANK] 替换为 ###
+     */
+    public static String replaceBlank(String str) {
+        if (str == null) {
+            return null;
+        }
+        return str.replace("[BLANK]", "###");
+    }
+
+    /**
+     * 替换首个P标签
+     */
+    public static String replaceFirstP(String str) {
+        if (str == null) {
+            return null;
+        }
+        if (str.startsWith("<p>") && str.endsWith("</p>")) {
+            //去掉头<p >
+            str = str.replaceFirst("<p>", "");
+            //去掉尾</p>
+            int index = str.lastIndexOf("</p>");
+            if (index > 0) {
+                str = str.substring(0, index);
+            }
+        }
+        return str;
+    }
 
 }

+ 30 - 54
examcloud-core-questions-service/src/main/java/cn/com/qmth/examcloud/core/questions/service/util/ExportPaperUtil.java

@@ -496,27 +496,20 @@ public class ExportPaperUtil {
 
     private static void disposeQuestion(Question qes, ExportTempDataDto dto) {
         if (qes != null) {
-            //处理题干
             List<JSection> slist1 = getSections(qes.getQuesBody(),false);
-            if (slist1 == null||slist1.size()==0) {
-                slist1=new ArrayList<JSection>();
-                JSection sec=new JSection();
-                List<SectionElement> ses=new ArrayList<SectionElement>();
-                sec.setElements(ses);
-                slist1.add(sec);
-            }
-            if (qes.getSubQuestions() == null || qes.getSubQuestions().size() == 0) {// 套题题干不加题号
-                dto.setSubNum(dto.getSubNum() + 1);
-                SectionElement se = new SectionElement();
-                se.setType(ELEMENT_TYPE_TEXT);
-                se.setValue(dto.getSubNum() + ".");
-                slist1.get(0).getElements().add(0, se);
-            }
+            if (slist1 != null && slist1.size() > 0) {
+                if (qes.getSubQuestions() == null || qes.getSubQuestions().size() == 0) {// 套题题干不加题号
+                    dto.setSubNum(dto.getSubNum() + 1);
+                    SectionElement se = new SectionElement();
+                    se.setType(ELEMENT_TYPE_TEXT);
+                    se.setValue(dto.getSubNum() + ".");
+                    slist1.get(0).getElements().add(0, se);
+                }
 
-            htmlToDoc(slist1, dto);
-            qes.setQuesBodyWord(getQuestionDoc(slist1));
+                htmlToDoc(slist1, dto);
+                qes.setQuesBodyWord(getQuestionDoc(slist1));
+            }
 
-            //处理选项
             if (qes.getQuesOptions() != null && qes.getQuesOptions().size() > 0) {
                 int index = 0;
                 for (QuesOption qo : qes.getQuesOptions()) {
@@ -533,15 +526,13 @@ public class ExportPaperUtil {
 
                 }
             }
-            
-            //处理答案
             List<JSection> slist3 = getSections(qes.getQuesAnswer());
             if (slist3 == null||slist3.size()==0) {
-                slist3=new ArrayList<JSection>();
-                JSection sec=new JSection();
-                List<SectionElement> ses=new ArrayList<SectionElement>();
-                sec.setElements(ses);
-                slist3.add(sec);
+            	slist3=new ArrayList<JSection>();
+            	JSection sec=new JSection();
+            	List<SectionElement> ses=new ArrayList<SectionElement>();
+            	sec.setElements(ses);
+            	slist3.add(sec);
             }
             SectionElement se = new SectionElement();
             se.setType(ELEMENT_TYPE_TEXT);
@@ -577,26 +568,19 @@ public class ExportPaperUtil {
             if (qes.getSubQuestions() == null || qes.getSubQuestions().size() == 0) {// 套题题干不加题号
                 dto.setSubNum(dto.getSubNum() + 1);
             }
-            //处理题干
             List<JSection> slist1 = getSections(qes.getQuesBody(),true);
-            if (slist1 == null||slist1.size()==0) {
-                slist1=new ArrayList<JSection>();
-                JSection sec=new JSection();
-                List<SectionElement> ses=new ArrayList<SectionElement>();
-                sec.setElements(ses);
-                slist1.add(sec);
-            }
-            if (qes.getSubQuestions() == null || qes.getSubQuestions().size() == 0) {// 套题题干不加题号
-                SectionElement se = new SectionElement();
-                se.setType(ELEMENT_TYPE_TEXT);
-                se.setValue(dto.getSubNum() + ".");
-                slist1.get(0).getElements().add(0, se);
-            }
+            if (slist1 != null && slist1.size() > 0) {
+                if (qes.getSubQuestions() == null || qes.getSubQuestions().size() == 0) {// 套题题干不加题号
+                    SectionElement se = new SectionElement();
+                    se.setType(ELEMENT_TYPE_TEXT);
+                    se.setValue(dto.getSubNum() + ".");
+                    slist1.get(0).getElements().add(0, se);
+                }
 
-            htmlToDoc(slist1, dto);
-            qes.setQuesBodyWord(getQuestionDoc(slist1));
+                htmlToDoc(slist1, dto);
+                qes.setQuesBodyWord(getQuestionDoc(slist1));
+            }
 
-            //处理选项
             if (qes.getQuesOptions() != null && qes.getQuesOptions().size() > 0) {
                 int index = 0;
                 JOptionDto joDto = new JOptionDto();
@@ -619,18 +603,11 @@ public class ExportPaperUtil {
                 disposeQuesOptions(joDto);// 处理选项列数
                 qes.setQuesOptionsWord(getPaperQuestionDoc(joDto.getOptions()));
             }
-            
-            //处理答案
-            if (qes.getSubQuestions() == null || qes.getSubQuestions().size() == 0) {// 套题不加答案及序号
+            if (qes.getSubQuestions() == null || qes.getSubQuestions().size() == 0) {// 套题不加答案序号
                 dto.setAnswerNum(dto.getAnswerNum() + 1);
-                List<JSection> slist3 = getSections(qes.getQuesAnswer());
-                if (slist3 == null||slist3.size()==0) {
-                    slist3=new ArrayList<JSection>();
-                    JSection sec=new JSection();
-                    List<SectionElement> ses=new ArrayList<SectionElement>();
-                    sec.setElements(ses);
-                    slist3.add(sec);
-                }
+            }
+            List<JSection> slist3 = getSections(qes.getQuesAnswer());
+            if (slist3 != null && slist3.size() > 0) {
                 SectionElement se = new SectionElement();
                 se.setType(ELEMENT_TYPE_TEXT);
                 se.setValue(dto.getAnswerNum() + ".");
@@ -639,7 +616,6 @@ public class ExportPaperUtil {
                 htmlToDoc(slist3, dto);
                 qes.setQuesAnswerWord(getQuestionDoc(slist3));
             }
-            
 
             if (qes.getSubQuestions() != null && qes.getSubQuestions().size() > 0) {
                 dto.setSubNum(0);

+ 1 - 1
examcloud-core-questions-starter/src/main/resources/security.properties

@@ -1,2 +1,2 @@
-[s][${api_cqb}/][/paper/export/{id}/{exportContentList}/{orgId}/{loginName}/{examType}][GET]=true
+[s][${api_cqb}/][/paper/export/{id}/{exportContentList}/{orgName}/{loginName}/{examType}][GET]=true
 [s][${api_cqb}/default_question][/question][POST]=true