소스 검색

修改导入导出部分bug

宋悦 8 년 전
부모
커밋
218436267d

+ 14 - 0
cqb-comm-utils/src/main/java/com/qmth/cqb/utils/exception/PaperException.java

@@ -0,0 +1,14 @@
+package com.qmth.cqb.utils.exception;
+
+/**
+ * Created by songyue on 17/5/2.
+ */
+public class PaperException extends Exception{
+    private static final long serialVersionUID = 8857929143713319678L;
+
+    public PaperException(){super();}
+
+    public PaperException(String message) {
+        super(message);
+    }
+}

+ 15 - 0
cqb-comm-utils/src/main/java/com/qmth/cqb/utils/exception/QuesException.java

@@ -0,0 +1,15 @@
+package com.qmth.cqb.utils.exception;
+
+/**
+ * Created by songyue on 17/5/2.
+ */
+public class QuesException extends Exception{
+
+    private static final long serialVersionUID = -2651610766615418315L;
+
+    public QuesException(){super();}
+
+    public QuesException(String message) {
+        super(message);
+    }
+}

+ 95 - 130
cqb-comm-utils/src/main/java/com/qmth/cqb/utils/word/DocxProcessUtil.java

@@ -335,7 +335,7 @@ public final class DocxProcessUtil {
      * @param omml
      * @return
      */
-    public static String omml2mml(String omml) {
+    public static String omml2mml(String omml)throws Exception {
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         InputStream stylesheet = ClassLoader.getSystemResourceAsStream(OMML2MML_XSL);
         StringReader sr = new StringReader(omml);
@@ -344,21 +344,16 @@ public final class DocxProcessUtil {
         org.w3c.dom.Document document = null;
         DocumentBuilder builder = null;
         Transformer transformer = null;
-        try {
-            builder = factory.newDocumentBuilder();
-            document = builder.parse(ommldata);
-            TransformerFactory tFactory = new TransformerFactoryImpl();
-            StreamSource stylesource = new StreamSource(stylesheet);
-            transformer = tFactory.newTransformer(stylesource);
-            DOMSource source = new DOMSource(document);
-            StreamResult result = new StreamResult(writer);
-            transformer.transform(source, result);
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            IOUtils.closeQuietly(sr);
-            IOUtils.closeQuietly(writer);
-        }
+        builder = factory.newDocumentBuilder();
+        document = builder.parse(ommldata);
+        TransformerFactory tFactory = new TransformerFactoryImpl();
+        StreamSource stylesource = new StreamSource(stylesheet);
+        transformer = tFactory.newTransformer(stylesource);
+        DOMSource source = new DOMSource(document);
+        StreamResult result = new StreamResult(writer);
+        transformer.transform(source, result);
+        IOUtils.closeQuietly(sr);
+        IOUtils.closeQuietly(writer);
         String mml = writer.toString();
         mml = ("<mml:math" + StringUtils.substringAfter(mml, "<mml:math")).replace("mml:", "");
         return mml;
@@ -370,25 +365,20 @@ public final class DocxProcessUtil {
      * @param htmlStr
      * @return
      */
-    public static String formatHtml(String htmlStr) {
-        try {
-            org.jsoup.nodes.Document doc = Jsoup.parse(htmlStr);
-            Elements divs = doc.select("div[class='document");
-            doc.select("p").removeAttr("class").removeAttr("style");
-            doc.select("div").removeAttr("class").removeAttr("style");
-            doc.select("span").removeAttr("class").removeAttr("style");
-            doc.select("span").stream().forEach(element -> {
-                if (!element.hasText())
-                    element.remove();
-            });
-            if (divs.size() > 0) {
-                htmlStr = divs.html();
-            } else {
-                htmlStr = doc.html();
-            }
-            return htmlStr;
-        } catch (Exception e) {
-            e.printStackTrace();
+    public static String formatHtml(String htmlStr) throws Exception {
+        org.jsoup.nodes.Document doc = Jsoup.parse(htmlStr);
+        Elements divs = doc.select("div[class='document");
+        doc.select("p").removeAttr("class").removeAttr("style");
+        doc.select("div").removeAttr("class").removeAttr("style");
+        doc.select("span").removeAttr("class").removeAttr("style");
+        doc.select("span").stream().forEach(element -> {
+            if (!element.hasText())
+                element.remove();
+        });
+        if (divs.size() > 0) {
+            htmlStr = divs.html();
+        } else {
+            htmlStr = doc.html();
         }
         return htmlStr;
     }
@@ -399,7 +389,7 @@ public final class DocxProcessUtil {
      * @param htmlStr
      * @return
      */
-    public static String getTextInHtml(String htmlStr) {
+    public static String getTextInHtml(String htmlStr){
         try {
             org.jsoup.nodes.Document doc = Jsoup.parse(htmlStr);
             String textStr = "";
@@ -420,37 +410,31 @@ public final class DocxProcessUtil {
      * @param htmlPath
      * @return
      */
-    public static String formatHtmlByPath(String htmlPath) {
+    public static String formatHtmlByPath(String htmlPath) throws Exception {
         String htmlStr = "";
-        File htmlFile;
-        try {
-            htmlFile = new File(htmlPath);
-            org.jsoup.nodes.Document doc = Jsoup.parse(htmlFile, ENCODING);
-            Elements divs = doc.select("div[class='document']");
-            doc.select("p").removeAttr("class").removeAttr("style");
-            doc.select("div").removeAttr("class").removeAttr("style");
-            doc.select("span").removeAttr("class").removeAttr("style");
-            doc.select("span").stream().forEach(element -> {
-                if (!element.hasText() && element.childNodeSize() == 0) {
-                    element.remove();
-                }
-            });
-            Elements imgs = doc.select("img");
-            for (org.jsoup.nodes.Element img : imgs) {
-                String imgSrc = img.attr("src");
-                if (!StringUtils.isEmpty(imgSrc)) {
-                    String imgBase64 = new String(getBase64ByPath(htmlFile.getParent() + "/" + imgSrc));
-                    img.attr("src", BASE64_HEADER + imgBase64);
-                }
+        File htmlFile = new File(htmlPath);
+        org.jsoup.nodes.Document doc = Jsoup.parse(htmlFile, ENCODING);
+        Elements divs = doc.select("div[class='document']");
+        doc.select("p").removeAttr("class").removeAttr("style");
+        doc.select("div").removeAttr("class").removeAttr("style");
+        doc.select("span").removeAttr("class").removeAttr("style");
+        doc.select("span").stream().forEach(element -> {
+            if (!element.hasText() && element.childNodeSize() == 0) {
+                element.remove();
             }
-            if (divs.size() > 0) {
-                htmlStr = divs.html();
-            } else {
-                htmlStr = doc.html();
+        });
+        Elements imgs = doc.select("img");
+        for (org.jsoup.nodes.Element img : imgs) {
+            String imgSrc = img.attr("src");
+            if (!StringUtils.isEmpty(imgSrc)) {
+                String imgBase64 = new String(getBase64ByPath(htmlFile.getParent() + "/" + imgSrc));
+                img.attr("src", BASE64_HEADER + imgBase64);
             }
-            return htmlStr;
-        } catch (Exception e) {
-            e.printStackTrace();
+        }
+        if (divs.size() > 0) {
+            htmlStr = divs.html();
+        } else {
+            htmlStr = doc.html();
         }
         return htmlStr;
     }
@@ -461,26 +445,21 @@ public final class DocxProcessUtil {
      * @param mathMlStr
      * @return
      */
-    public static byte[] convertMathml2Img(String mathMlStr) {
+    public static byte[] convertMathml2Img(String mathMlStr) throws Exception {
         File xmlFile = null;
         File imgFile = null;
         FileOutputStream xmlFos = null;
         byte[] base64Byte = new byte[0];
-        try {
-            xmlFile = new File(TEMP_FILE_IMP, UUID.randomUUID().toString());
-            imgFile = new File(TEMP_FILE_IMP, UUID.randomUUID().toString());
-            xmlFos = new FileOutputStream(xmlFile);
-            IOUtils.write(mathMlStr, xmlFos, ENCODING);
-            xmlFos.flush();
-            Converter.getInstance().convert(xmlFile, imgFile, IMG_OUT_TYPE, IMG_LAYOUT);
-            base64Byte = IOUtils.toByteArray(new FileInputStream(imgFile));
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            IOUtils.closeQuietly(xmlFos);
-            FileUtils.deleteQuietly(xmlFile);
-            FileUtils.deleteQuietly(imgFile);
-        }
+        xmlFile = new File(TEMP_FILE_IMP, UUID.randomUUID().toString());
+        imgFile = new File(TEMP_FILE_IMP, UUID.randomUUID().toString());
+        xmlFos = new FileOutputStream(xmlFile);
+        IOUtils.write(mathMlStr, xmlFos, ENCODING);
+        xmlFos.flush();
+        Converter.getInstance().convert(xmlFile, imgFile, IMG_OUT_TYPE, IMG_LAYOUT);
+        base64Byte = IOUtils.toByteArray(new FileInputStream(imgFile));
+        IOUtils.closeQuietly(xmlFos);
+        FileUtils.deleteQuietly(xmlFile);
+        FileUtils.deleteQuietly(imgFile);
         return base64Byte;
     }
 
@@ -490,21 +469,16 @@ public final class DocxProcessUtil {
      * @param imgFilePath
      * @return
      */
-    public static byte[] getBase64ByPath(String imgFilePath) {
+    public static byte[] getBase64ByPath(String imgFilePath) throws Exception {
         InputStream is = null;
         byte[] base64Byte = new byte[0];
         byte[] imgByte;
         File imgFile = new File(imgFilePath);
-        try {
-            is = new FileInputStream(imgFile);
-            imgByte = IOUtils.toByteArray(is);
-            base64Byte = Base64.encodeBase64(imgByte);
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            IOUtils.closeQuietly(is);
-            FileUtils.deleteQuietly(imgFile);
-        }
+        is = new FileInputStream(imgFile);
+        imgByte = IOUtils.toByteArray(is);
+        base64Byte = Base64.encodeBase64(imgByte);
+        IOUtils.closeQuietly(is);
+        FileUtils.deleteQuietly(imgFile);
         return base64Byte;
     }
 
@@ -514,19 +488,14 @@ public final class DocxProcessUtil {
      * @param imgFile
      * @return
      */
-    public static byte[] getBase64ByFile(File imgFile) {
+    public static byte[] getBase64ByFile(File imgFile) throws Exception {
         InputStream is = null;
         byte[] base64Byte = new byte[0];
         byte[] imgByte;
-        try {
-            is = new FileInputStream(imgFile);
-            imgByte = IOUtils.toByteArray(is);
-            base64Byte = Base64.encodeBase64(imgByte);
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            IOUtils.closeQuietly(is);
-        }
+        is = new FileInputStream(imgFile);
+        imgByte = IOUtils.toByteArray(is);
+        base64Byte = Base64.encodeBase64(imgByte);
+        IOUtils.closeQuietly(is);
         return base64Byte;
     }
 
@@ -569,7 +538,8 @@ public final class DocxProcessUtil {
 
                 for (Object rChild : rContent) {
 
-                    rChild = ((JAXBElement<?>) rChild).getValue();
+                    if (rChild instanceof JAXBElement)
+                        rChild = ((JAXBElement<?>) rChild).getValue();
 
                     if (rChild.getClass().equals(Text.class)) {
                         ++index;
@@ -632,32 +602,27 @@ public final class DocxProcessUtil {
      * @param dataMap
      * @param fileName
      */
-    public static void exportWord(Map dataMap, String fileName, String templatePath) {
+    public static void exportWord(Map dataMap, String fileName, String templatePath)throws Exception {
         Writer out = null;
-        try {
-            // 创建配置实例
-            Configuration configuration = new Configuration(Configuration.VERSION_2_3_25);
-            // 设置编码
-            configuration.setDefaultEncoding("UTF-8");
-            // 设置ftl模板路径
-            configuration.setClassForTemplateLoading(DocxProcessUtil.class, "/");
-            // 获取模板
-            Template template = configuration.getTemplate(templatePath, ENCODING);
-            // 输出文件
-            File outFile = new File(TEMP_FILE_EXP + fileName + DOCX_SUFFIX);
-
-            // 将模板和数据模型合并生成文件
-            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), ENCODING));
-            // 生成文件
-            template.process(dataMap, out);
-
-            out.flush();
-
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            IOUtils.closeQuietly(out);
-        }
+        // 创建配置实例
+        Configuration configuration = new Configuration(Configuration.VERSION_2_3_25);
+        // 设置编码
+        configuration.setDefaultEncoding("UTF-8");
+        // 设置ftl模板路径
+        configuration.setClassForTemplateLoading(DocxProcessUtil.class, "/");
+        // 获取模板
+        Template template = configuration.getTemplate(templatePath, ENCODING);
+        // 输出文件
+        File outFile = new File(TEMP_FILE_EXP + fileName + DOCX_SUFFIX);
+
+        // 将模板和数据模型合并生成文件
+        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), ENCODING));
+        // 生成文件
+        template.process(dataMap, out);
+
+        out.flush();
+
+        IOUtils.closeQuietly(out);
     }
 
     /**
@@ -666,7 +631,7 @@ public final class DocxProcessUtil {
      * @param dataMap
      * @param fileName
      */
-    public static void exportPaper(Map dataMap, String fileName) {
+    public static void exportPaper(Map dataMap, String fileName) throws Exception {
         exportWord(dataMap, fileName, PAPER_TEMPLATE);
     }
 
@@ -676,7 +641,7 @@ public final class DocxProcessUtil {
      * @param dataMap
      * @param fileName
      */
-    public static void exportAnswer(Map dataMap, String fileName) {
+    public static void exportAnswer(Map dataMap, String fileName) throws Exception {
         exportWord(dataMap, fileName, ANSWER_TEMPLATE);
     }
 
@@ -824,7 +789,7 @@ public final class DocxProcessUtil {
      * @return
      * @throws Exception
      */
-    public static String html2Docx(WordprocessingMLPackage wordMLPackage,String html)throws Exception{
+    public static String html2Docx(WordprocessingMLPackage wordMLPackage,String html)throws Exception {
         initPkgImage(wordMLPackage);
         XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
         String wordMl = "";

+ 15 - 24
cqb-paper/src/main/java/com/qmth/cqb/paper/service/ExportPaperService.java

@@ -15,6 +15,7 @@ import com.qmth.cqb.question.model.QuesOption;
 import com.qmth.cqb.question.model.Question;
 import com.qmth.cqb.utils.BeanCopierUtil;
 import com.qmth.cqb.utils.CommonUtils;
+import com.qmth.cqb.utils.exception.PaperException;
 import com.qmth.cqb.utils.word.DocxProcessUtil;
 import org.docx4j.XmlUtils;
 import org.docx4j.jaxb.Context;
@@ -63,7 +64,7 @@ public class ExportPaperService {
      * @param id
      * @return
      */
-    public Map initExportPaper(String id)throws Exception{
+    public Map initExportPaper(String id) throws Exception{
         //创建返回Map
         Map returnMap = new HashMap();
         //获取paper
@@ -72,8 +73,7 @@ public class ExportPaperService {
         paperService.formatPaper(paper,null);
 
         if(paper == null){
-            returnMap.put("errorInfo","该试卷不存在");
-            return returnMap;
+            throw new PaperException("该试卷不存在");
         }
 
         //创建paperDto
@@ -119,36 +119,27 @@ public class ExportPaperService {
      * 导出试卷
      * @param id
      */
-    public String exportPaper(String id) throws Exception {
+    public void exportPaper(String id) throws Exception {
         Map dataMap = initExportPaper(id);
-        if(dataMap.get("errorInfo")!=null){
-            return (String)dataMap.get("errorInfo");
+        if(dataMap.get("fileName") != null){
+            String fileName = (String)dataMap.get("fileName");
+            DocxProcessUtil.exportPaper(dataMap,fileName);
+            DocxProcessUtil.processImage(fileName,getPkgList(id));
         }
-        String fileName = (String)dataMap.get("fileName");
-        DocxProcessUtil.exportPaper(dataMap,fileName);
-        DocxProcessUtil.processImage(fileName,getPkgList(id));
-        return "success";
     }
 
     /**
      * 下载试卷
      * @param id
      */
-    public Map downloadPaper(String id, HttpServletResponse response){
-        Map dataMap = null;
-        try {
-            dataMap = initExportPaper(id);
-            if(dataMap.get("errorInfo")!=null){
-                return dataMap;
-            }
-            String fileName = (String)dataMap.get("fileName");
-            DocxProcessUtil.exportPaper(dataMap,fileName);
-            DocxProcessUtil.processImage(fileName,getPkgList(id));
-            DocxProcessUtil.processDownload(fileName,response);
-        } catch (Exception e) {
-            e.printStackTrace();
+    public void downloadPaper(String id, HttpServletResponse response) throws Exception {
+        Map dataMap = initExportPaper(id);
+        if (dataMap.get("fileName") != null) {
+            String fileName = (String) dataMap.get("fileName");
+            DocxProcessUtil.exportPaper(dataMap, fileName);
+            DocxProcessUtil.processImage(fileName, getPkgList(id));
+            DocxProcessUtil.processDownload(fileName, response);
         }
-        return dataMap;
     }
 
     /**

+ 128 - 142
cqb-paper/src/main/java/com/qmth/cqb/paper/service/ImportPaperService.java

@@ -11,6 +11,7 @@ import java.util.UUID;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import com.qmth.cqb.utils.exception.PaperException;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.ArrayUtils;
@@ -76,19 +77,13 @@ public class ImportPaperService {
      * @param file
      * @return
      */
-    public File getUploadFile(CommonsMultipartFile file) {
+    public File getUploadFile(CommonsMultipartFile file) throws Exception{
         String fileName = file.getOriginalFilename();
         File tempFile = new File(DocxProcessUtil.TEMP_FILE_IMP + fileName);
         OutputStream os = null;
-        try {
-            os = new FileOutputStream(tempFile);
-            IOUtils.copyLarge(file.getInputStream(), os);
-        } catch (Exception e) {
-            e.printStackTrace();
-            log.error("上传文件异常:" + e.getMessage());
-        } finally {
-            IOUtils.closeQuietly(os);
-        }
+        os = new FileOutputStream(tempFile);
+        IOUtils.copyLarge(file.getInputStream(), os);
+        IOUtils.closeQuietly(os);
         return tempFile;
     }
 
@@ -104,7 +99,7 @@ public class ImportPaperService {
                               String courseNo,
                               String courseName,
                               AccessUser user,
-                              File file) {
+                              File file) throws Exception{
         String errorInfo = paperService.checkPaperName(paperName, user.getOrgId().toString());
         if (errorInfo == null) {
             errorInfo = "";
@@ -165,149 +160,140 @@ public class ImportPaperService {
      * @param file
      * @return
      */
-    public String processImportPaper(String paperName, String courseNo, String courseName, AccessUser user, File file) {
+    public String processImportPaper(String paperName, String courseNo, String courseName, AccessUser user, File file) throws Exception {
 
         WordprocessingMLPackage wordMLPackage;
         WordprocessingMLPackage tmpWordMlPackage;
         WordprocessingMLPackage writePkg;
         ImportPaperCheck importPaperCheck = new ImportPaperCheck();
 
-        try {
-            wordMLPackage = WordprocessingMLPackage.load(file);
-            // 初始化图片路径
-            DocxProcessUtil.initPkgImage(wordMLPackage);
-            // 深拷贝临时pkg与最终写入数据库pkg
-            tmpWordMlPackage = DocxProcessUtil.getTmpPackage(wordMLPackage);
-            writePkg = DocxProcessUtil.getTmpPackage(wordMLPackage);
-
-            // 获取word文档中所有段落
-            List<Object> pList = DocxProcessUtil.getAllElementFromObject(wordMLPackage.getMainDocumentPart(), P.class);
-
-            // 创建试卷类
-            Paper paper = new Paper();
-
-            paper.setCourseNo(courseNo);
-
-            paper.setCourseName(courseName);
-
-            paper.setOrgId(user.getOrgId().toString());
-
-            paper.setCreator(user.getName());
-
-            // 设置试卷
-            initPaper(paper, paperName);
-
-            // 创建空大题类
-            PaperDetail paperDetail = null;
-
-            // 创建大题集合
-            List<PaperDetail> paperDetails = new ArrayList<PaperDetail>();
-
-            // 创建小题集合
-            List<PaperDetailUnit> paperDetailUnits = new ArrayList<PaperDetailUnit>();
-
-            // 创建试题集合
-            List<Question> questions = new ArrayList<Question>();
-
-            // 大题号
-            int mainQuesNum = 0;
-
-            // 小题号
-            int subQuesNum = 0;
-
-            for (int i = 0; i < pList.size(); i++) {
-                P p = (P) pList.get(i);
-                String pText = DocxProcessUtil.getPText(p);
-
-
-                if(StringUtils.isEmpty(pText)){
-                    // 跳过空白段落
-                    continue;
-
-                }else if (pText.startsWith("[试题分类]")) {
-                    // 处理大题头信息
-                    processMainQuesHeader(pList, importPaperCheck.index, importPaperCheck);
-
-                    // 校验大题头信息
-                    if (!checkQuesHeader(importPaperCheck)) {
-                        return importPaperCheck.errorInfo;
-                    }
-
-                    // 创建大题类
-                    paperDetail = new PaperDetail();
-
-                    // 设置大题类
-                    initQuesHeader(paper, paperDetail, paperDetails, ++mainQuesNum, importPaperCheck);
-
-                } else if (pText.matches("^\\d{1,}\\.[\\s\\S]*")
-                        || (isNested(importPaperCheck) && !pText.startsWith("["))) {
-                    // 处理试题
-
-                    // 创建小题类和试题类
-                    PaperDetailUnit paperDetailUnit = new PaperDetailUnit();
-                    Question question = new Question();
-
-                    // 初始化小题类和试题类
-                    initPaperDetail(paper, paperDetail, paperDetailUnit, question, ++subQuesNum, importPaperCheck);
-
-                    // 处理客观题
-                    if (importPaperCheck.quesType.equals("单选") || importPaperCheck.quesType.equals("多选")) {
-
-                        // 处理题干
-                        processQuesBody(pList, importPaperCheck.index, question, importPaperCheck, tmpWordMlPackage);
-                        // 处理选项
-                        processQuesOption(pList, importPaperCheck.index, subQuesNum, question, importPaperCheck,
-                                tmpWordMlPackage);
-                        // 处理尾信息
-                        processQuesTail(pList, importPaperCheck.index, subQuesNum, question, paperDetailUnit,
-                                importPaperCheck, tmpWordMlPackage, false);
-                        // 处理选择题的option--chenken 20170425
-                        processSelectOption(question);
-                    } else if (importPaperCheck.quesType.equals("套题")) {
-                        // 处理套题
-                        processNestedQues(pList, importPaperCheck.index, question, paperDetailUnit, importPaperCheck,
-                                tmpWordMlPackage);
-                    } else {
-                        // 处理其他题型
-                        processQuesBody(pList, importPaperCheck.index, question, importPaperCheck, tmpWordMlPackage);
-                        processQuesTail(pList, importPaperCheck.index, subQuesNum, question, paperDetailUnit,
-                                importPaperCheck, tmpWordMlPackage, false);
-                    }
-                    // 设置WordMlPackage二进制数据
-                    setPkgByte(question, writePkg);
-                    // 设置question与Unit集合数据
-                    question.setCourseNo(paper.getCourseNo());
-                    question.setCourseName(paper.getCourseName());
-                    question.setOrgId(user.getOrgId().toString());
-                    questions.add(question);
-                    paperDetailUnits.add(paperDetailUnit);
+        wordMLPackage = WordprocessingMLPackage.load(file);
+        // 初始化图片路径
+        DocxProcessUtil.initPkgImage(wordMLPackage);
+        // 深拷贝临时pkg与最终写入数据库pkg
+        tmpWordMlPackage = DocxProcessUtil.getTmpPackage(wordMLPackage);
+        writePkg = DocxProcessUtil.getTmpPackage(wordMLPackage);
+
+        // 获取word文档中所有段落
+        List<Object> pList = DocxProcessUtil.getAllElementFromObject(wordMLPackage.getMainDocumentPart(), P.class);
+
+        // 创建试卷类
+        Paper paper = new Paper();
+
+        paper.setCourseNo(courseNo);
+
+        paper.setCourseName(courseName);
+
+        paper.setOrgId(user.getOrgId().toString());
+
+        paper.setCreator(user.getName());
+
+        // 设置试卷
+        initPaper(paper, paperName);
+
+        // 创建空大题类
+        PaperDetail paperDetail = null;
+
+        // 创建大题集合
+        List<PaperDetail> paperDetails = new ArrayList<PaperDetail>();
+
+        // 创建小题集合
+        List<PaperDetailUnit> paperDetailUnits = new ArrayList<PaperDetailUnit>();
+
+        // 创建试题集合
+        List<Question> questions = new ArrayList<Question>();
+
+        // 大题号
+        int mainQuesNum = 0;
+
+        // 小题号
+        int subQuesNum = 0;
+
+        for (int i = 0; i < pList.size(); i++) {
+            P p = (P) pList.get(i);
+            String pText = DocxProcessUtil.getPText(p);
 
-                    // 设置当前索引,防止多余循环
-                    i = importPaperCheck.index - 1;
+
+            if (StringUtils.isEmpty(pText)) {
+                // 跳过空白段落
+                continue;
+
+            } else if (pText.startsWith("[试题分类]")) {
+                // 处理大题头信息
+                processMainQuesHeader(pList, importPaperCheck.index, importPaperCheck);
+
+                // 校验大题头信息
+                if (!checkQuesHeader(importPaperCheck)) {
+                    throw new PaperException(importPaperCheck.errorInfo);
                 }
-                if (!StringUtils.isEmpty(importPaperCheck.errorInfo)) {
-                    return importPaperCheck.errorInfo;
+
+                // 创建大题类
+                paperDetail = new PaperDetail();
+
+                // 设置大题类
+                initQuesHeader(paper, paperDetail, paperDetails, ++mainQuesNum, importPaperCheck);
+
+            } else if (pText.matches("^\\d{1,}\\.[\\s\\S]*")
+                    || (isNested(importPaperCheck) && !pText.startsWith("["))) {
+                // 处理试题
+
+                // 创建小题类和试题类
+                PaperDetailUnit paperDetailUnit = new PaperDetailUnit();
+                Question question = new Question();
+
+                // 初始化小题类和试题类
+                initPaperDetail(paper, paperDetail, paperDetailUnit, question, ++subQuesNum, importPaperCheck);
+
+                // 处理客观题
+                if (importPaperCheck.quesType.equals("单选") || importPaperCheck.quesType.equals("多选")) {
+
+                    // 处理题干
+                    processQuesBody(pList, importPaperCheck.index, question, importPaperCheck, tmpWordMlPackage);
+                    // 处理选项
+                    processQuesOption(pList, importPaperCheck.index, subQuesNum, question, importPaperCheck,
+                            tmpWordMlPackage);
+                    // 处理尾信息
+                    processQuesTail(pList, importPaperCheck.index, subQuesNum, question, paperDetailUnit,
+                            importPaperCheck, tmpWordMlPackage, false);
+                    // 处理选择题的option--chenken 20170425
+                    processSelectOption(question);
+                } else if (importPaperCheck.quesType.equals("套题")) {
+                    // 处理套题
+                    processNestedQues(pList, importPaperCheck.index, question, paperDetailUnit, importPaperCheck,
+                            tmpWordMlPackage);
+                } else {
+                    // 处理其他题型
+                    processQuesBody(pList, importPaperCheck.index, question, importPaperCheck, tmpWordMlPackage);
+                    processQuesTail(pList, importPaperCheck.index, subQuesNum, question, paperDetailUnit,
+                            importPaperCheck, tmpWordMlPackage, false);
                 }
+                // 设置WordMlPackage二进制数据
+                setPkgByte(question, writePkg);
+                // 设置question与Unit集合数据
+                question.setCourseNo(paper.getCourseNo());
+                question.setCourseName(paper.getCourseName());
+                question.setOrgId(user.getOrgId().toString());
+                questions.add(question);
+                paperDetailUnits.add(paperDetailUnit);
+
+                // 设置当前索引,防止多余循环
+                i = importPaperCheck.index - 1;
             }
-            if(paperDetails.size() == 0){
-                importPaperCheck.setErrorInfo("导入文件格式有误!");
-                log.error("导入处理异常:格式错误");
-                return importPaperCheck.errorInfo;
+            if (!StringUtils.isEmpty(importPaperCheck.errorInfo)) {
+                throw new PaperException(importPaperCheck.errorInfo);
             }
-            paper.setPaperDetailCount(mainQuesNum);
-            // 保存导入试卷信息
-            savePaper(paper, paperDetails, paperDetailUnits, questions, importPaperCheck);
-
-        } catch (Exception e) {
-            e.printStackTrace();
-            importPaperCheck.setErrorInfo(e.getMessage());
-            log.error("导入处理异常:" + e.getMessage());
-        } finally {
-            wordMLPackage = null;
-            tmpWordMlPackage = null;
-            writePkg = null;
-            FileUtils.deleteQuietly(file);
         }
+        if (paperDetails.size() == 0) {
+            importPaperCheck.setErrorInfo("导入文件格式有误!");
+            throw new PaperException("导入文件格式有误!");
+        }
+        paper.setPaperDetailCount(mainQuesNum);
+        // 保存导入试卷信息
+        savePaper(paper, paperDetails, paperDetailUnits, questions, importPaperCheck);
+        wordMLPackage = null;
+        tmpWordMlPackage = null;
+        writePkg = null;
+        FileUtils.deleteQuietly(file);
         return importPaperCheck.errorInfo;
     }
 

+ 13 - 1
cqb-paper/src/main/java/com/qmth/cqb/paper/web/ExportPaperController.java

@@ -2,6 +2,8 @@ package com.qmth.cqb.paper.web;
 
 import com.qmth.cqb.paper.service.ExportPaperService;
 import io.swagger.annotations.ApiOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -17,6 +19,8 @@ import javax.servlet.http.HttpServletResponse;
 @RequestMapping("${api_cqb}/")
 public class ExportPaperController {
 
+    protected static final Logger log = LoggerFactory.getLogger(ExportPaperController.class);
+
     @Autowired
     ExportPaperService exportPaperService;
 
@@ -28,6 +32,14 @@ public class ExportPaperController {
     @ApiOperation(value="导出试卷",notes="导出试卷")
     @GetMapping(value = "/paper/export/{id}")
     public void getPaperById(@PathVariable String id, HttpServletResponse response){
-        exportPaperService.downloadPaper(id,response);
+        log.info("导出开始");
+        try {
+            exportPaperService.downloadPaper(id,response);
+        } catch (Exception e) {
+            e.printStackTrace();
+            log.error("导出异常:"+e.getMessage());
+        }finally {
+            log.info("导出结束");
+        }
     }
 }

+ 19 - 8
cqb-paper/src/main/java/com/qmth/cqb/paper/web/ImportPaperController.java

@@ -66,15 +66,26 @@ public class ImportPaperController {
             @RequestParam("file") CommonsMultipartFile file) {
         AccessUser user = (AccessUser) request.getAttribute("accessUser");
         log.info("导入开始");
-        File tempFile = importPaperService.getUploadFile(file);
-        String returnStr  = importPaperService.ImportPaper(paperName, courseNo, courseName, user, tempFile);
-        log.info("导入结束");
-        if (returnStr.equals("success")) {
-            return new ResponseEntity(returnStr, HttpStatus.OK);
-        } else {
-            Map map = new HashMap();
-            map.put("errorMsg", returnStr);
+        File tempFile = null;
+        String returnStr = "";
+        Map map = new HashMap();
+        try {
+            tempFile = importPaperService.getUploadFile(file);
+            returnStr  = importPaperService.ImportPaper(paperName, courseNo, courseName, user, tempFile);
+            if (returnStr.equals("success")) {
+                return new ResponseEntity(returnStr, HttpStatus.OK);
+            } else {
+                map.put("errorMsg", returnStr);
+                log.info("导入异常:"+returnStr);
+                return new ResponseEntity(map, HttpStatus.INTERNAL_SERVER_ERROR);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            map.put("errorMsg", e.getMessage());
+            log.info("导入异常:"+e.getMessage());
             return new ResponseEntity(map, HttpStatus.INTERNAL_SERVER_ERROR);
+        }finally {
+            log.info("导入结束");
         }
     }
 

+ 1 - 1
cqb-starter/src/main/resources/log4j2.xml

@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<Configuration status="WARN">
+<Configuration status="info">
     <Appenders>
         <Console name="Console" target="SYSTEM_OUT" follow="true">
             <PatternLayout charset="UTF-8">