Examination_system/Examination_system-1/.svn/pristine/55/55af79f7cdfea5918f698fad163...

541 lines
17 KiB
Plaintext
Raw Normal View History

2023-10-30 13:10:40 +08:00
package com.bonus.question.controller;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.bonus.question.beans.QuestionBean;
import com.bonus.question.service.QuestionService;
import com.bonus.sys.AjaxRes;
import com.bonus.sys.BaseController;
import com.bonus.sys.GlobalConst;
import com.bonus.sys.Page;
import com.bonus.sys.beans.UserBean;
import com.bonus.sys.service.UserService;
@Controller
@RequestMapping("/backstage/question/")
public class QuestionController extends BaseController<QuestionBean> {
@Autowired
QuestionService service;
@Autowired
UserService userService;
@RequestMapping("questionList")
public String questionList(Model model) {
return "/question/questionTree";
}
@RequestMapping("findByPage")
public String findByPage(@RequestBody Page<QuestionBean> page, QuestionBean o, Model model) {
try {
o = page.getObj();
page = service.findByPage(o, page);
if (page.getResults() != null && page.getResults().size() != 0) {
for (int i = 0; i < page.getResults().size(); i++) {
QuestionBean bean = page.getResults().get(i);
if (bean.getContent().trim().length() > 14) {
String temp = bean.getContent().trim().substring(0, 14);
temp += "..";
bean.setContent(temp);
}
if (bean.getOperation().length() > 12) {
String temp = bean.getOperation().trim().substring(0, 12);
temp += "..";
bean.setOperation(temp);
}
if (bean.getAnswer() != null && bean.getAnswer().length() > 4) {
String temp = bean.getAnswer().trim().substring(0, 4);
temp += "..";
bean.setAnswer(temp);
}
page.getResults().set(i, bean);
}
}
model.addAttribute("page", page);
} catch (Exception e) {
e.printStackTrace();
}
return "/question/questionDetails";
}
@RequestMapping("questionFormPage")
public String questionFormPage(Model model) {
return "/question/questionForm";
}
@RequestMapping("findQuestionForm")
public String questionFormPage(QuestionBean o, Model model) {
try {
String type = o.getType();
o = service.findById(o);
o.setType(type);
model.addAttribute("question", o);
} catch (Exception e) {
e.printStackTrace();
}
return "/question/questionForm";
}
@RequestMapping("addQuestion")
@ResponseBody
public AjaxRes addQuestion(@RequestBody QuestionBean o) {
AjaxRes ar = getAjaxRes();
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
String date = df.format(new Date());
o.setUploadTime(date);
if (o.getClassification().equals("4") || o.getClassification().equals("5")
|| o.getClassification().equals("6")) {
o.setOperation("无");
}
ar = service.addQuestion(o);
} catch (Exception e) {
e.printStackTrace();
ar.setFailMsg("新增题目失败!");
}
return ar;
}
@RequestMapping("updateQuestion")
@ResponseBody
public AjaxRes updateQuestion(@RequestBody QuestionBean o) {
AjaxRes ar = getAjaxRes();
try {
if ((o.getOperation() == null || o.getOperation() == "")
&& (o.getClassification().equals("4") || o.getClassification().equals("5"))) {
o.setOperation("无");
}
ar = service.updateQuestion(o);
} catch (Exception e) {
e.printStackTrace();
ar.setFailMsg("修改题目失败!");
}
return ar;
}
@RequestMapping("deleteApply")
@ResponseBody
public AjaxRes deleteApply(QuestionBean o) {
AjaxRes ar = getAjaxRes();
try {
String ids = o.getIds();
String idsss = toChangeString(ids);
o.setIds(idsss);
ar = service.deleteApply(o);
} catch (Exception e) {
logger.error(e.toString(), e);
ar.setFailMsg("删除失败!");
}
return ar;
}
@RequestMapping(value = "import", method = RequestMethod.POST)
@ResponseBody
public AjaxRes export(@RequestParam("file") MultipartFile file) {
AjaxRes ar = getAjaxRes();
int errorNum = 0;
int result = 0;
try {
// @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件
// 创建workbook对象读取整个文档
InputStream inputStream = file.getInputStream();
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
HSSFWorkbook wb = new HSSFWorkbook(poifsFileSystem);
// Sheet sheet1 = wb.getSheet("sheet1"); // excel文件的工作簿的名称
// 读取页脚sheet 第一页工作表
HSSFSheet hssfSheet = wb.getSheetAt(0);
// 判断Sheet是否为空
if (hssfSheet != null) {
// 判断不为空 打印
System.out.println(hssfSheet.getLastRowNum());
// 获得数据的总行数
int totalRowNum = hssfSheet.getLastRowNum();
// 要获得的值
String content = ""; // 题目
String operation = ""; // 选项
String answer = ""; // 正确答案
String classification = ""; // 题目类型
String questionType = ""; // 题目分类
String questionLevel = ""; // 题目难易程度
// 遍历每一行rowcontinue只是终止本次循环接着还执行后面的循环
for (int rownum = 2; rownum <= hssfSheet.getLastRowNum(); rownum++) { // 从第三行开始
// 获取到每一行
errorNum = rownum;
HSSFRow sheetRow = hssfSheet.getRow(rownum);
if (sheetRow != null && !isRowEmpty(sheetRow)) {
// 获得第i行对象
Row row = hssfSheet.getRow(rownum);
// 获得获得第i行第1列的 String类型对象
Cell cell = row.getCell((short) 1);
content = cell.getStringCellValue().toString();
// 获得获得第i行第2列的 String类型对象
Cell cell1 = row.getCell((short) 2);
operation = cell1.getStringCellValue().toString();
if (row.getCell(3) != null) {
row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
answer = (row.getCell(3).getStringCellValue());
}
// 获取题目类型 int类型的值转换为string类型再由对象接收转换后的值
if (row.getCell(5) != null) {
row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
classification = (row.getCell(5).getStringCellValue());
}
// 获取题目分类 int类型的值转换为string类型再由对象接收转换后的值
if (row.getCell(6) != null) {
row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
questionType = (row.getCell(6).getStringCellValue());
}
// 获取题目难易程度 int类型的值转换为string类型再由对象接收转换后的值
if (row.getCell(7) != null) {
row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
questionLevel = (row.getCell(7).getStringCellValue());
}
if (content.isEmpty() || operation.isEmpty() || classification.isEmpty()
|| questionType.isEmpty() || questionLevel.isEmpty()) {
ar.setFailMsg("导入失败,第" + (rownum + 1) + "行有空值");
System.out.println("判断为空 已进入");
result = 1;
break;
}
// 判断难易程度是否符合规则
boolean isRule = isQuestionLevelTypeRule(questionLevel);
if (!isRule) {
ar.setFailMsg("导入失败,第" + (rownum + 1) + "行,难易程度不符合规则!");
result = 1;
break;
}
// 判断题目分类(题库id)是否符合规则
isRule = isQuestionTypeRule(questionType);
if (!isRule) {
ar.setFailMsg("导入失败,第" + (rownum + 1) + "行,题目分类(题库id)不符合规则!");
result = 1;
break;
}
// 判断题目类型是否符合规则
isRule = isClassificationRule(classification);
if (!isRule) {
ar.setFailMsg("导入失败,第" + (rownum + 1) + "行,题目类型不符合规则!");
result = 1;
break;
}
// 判断选项/正确答案是否符合规则
if ("1".equals(classification) || "2".equals(classification) || "3".equals(classification)) {
// 判断选项是否符合规则
isRule = isOperationRule(operation);
if (!isRule) {
ar.setFailMsg("导入失败,第" + (rownum + 1) + "行,选项不符合规则!");
result = 1;
break;
}
// 判断正确答案是否符合规则
isRule = isAnswerRule(answer, classification);
if (!isRule) {
ar.setFailMsg("导入失败,第" + (rownum + 1) + "行,正确答案不符合规则!");
result = 1;
break;
}
}
}
}
if (result == 0) {
// 从第三行开始
for (int rownum = 2; rownum <= hssfSheet.getLastRowNum(); rownum++) {
HSSFRow sheetRow = hssfSheet.getRow(rownum);
if (sheetRow != null && !isRowEmpty(sheetRow)) {
addSaveData(sheetRow);
ar.setSucceedMsg(GlobalConst.IMP_SUCCEED);
}
}
}
}
} catch (Exception e) {
logger.error(e.toString(), e);
ar.setFailMsg("第" + errorNum + "行导入失败");
}
return ar;
}
/**
* 判断正确答案是否符合规则
*
* @param answer
* @return
*/
private boolean isAnswerRule(String answer, String classification) {
boolean tf = true;
try {
if ("1".equals(classification) || "2".equals(classification)) {
Pattern pattern = Pattern.compile("[A-Z]*");
Matcher matcher = pattern.matcher(answer);
if (!matcher.matches()) {
System.out.println(answer + "不全是大写字母");
tf = false;
}
} else {
if (!("正确".equals(answer) || "错误".equals(answer))) {
tf = false;
}
}
} catch (Exception e) {
logger.equals(e.toString());
tf = false;
}
return tf;
}
/**
* 判断难易程度是否符合规则
*
* @param questionLevel
* @return
*/
private boolean isQuestionLevelTypeRule(String questionLevel) {
try {
if ("1".equals(questionLevel) || "2".equals(questionLevel) || "3".equals(questionLevel)) {
return true;
}
} catch (Exception e) {
logger.error(e.toString());
}
return false;
}
/**
* 判断题目分类(题库id)是否符合规则
*
* @param questionType
* @return
*/
private boolean isQuestionTypeRule(String questionType) {
boolean tf = true;
try {
int orgId = Integer.parseInt(questionType);
UserBean bean = userService.findOrgId(orgId);
if (bean == null) {
tf = false;
}
} catch (Exception e) {
logger.error(e.toString());
tf = false;
}
return tf;
}
/**
* 判断题目类型是否符合规则
*
* @param classification
* @return
*/
private boolean isClassificationRule(String classification) {
try {
if ("1".equals(classification) || "2".equals(classification) || "3".equals(classification)
|| "4".equals(classification) || "5".equals(classification) || "6".equals(classification)) {
return true;
}
} catch (Exception e) {
logger.error(e.toString());
}
return false;
}
/**
* 判断选项是否符合规则
*
* @param operation
* @return
*/
private boolean isOperationRule(String operation) {
try {
String[] op = operation.split(";");
for (int j = 0; j < op.length; j++) {
try {
Integer.parseInt(op[j].charAt(0) + "");
} catch (NumberFormatException e) {
System.err.println("isOperationRule:" + operation);
return false;
}
}
} catch (Exception e) {
logger.error(e.toString());
}
return true;
}
// 判断该行是否为空
public static boolean isRowEmpty(Row row) {
int count = 0;
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
count++;
}
}
if (count > 3) { // 表示是有效数据行
return false;
}
return true;
}
private void addSaveData(HSSFRow sheetRow) throws Exception {
QuestionBean bean = new QuestionBean();
String content = getValue(sheetRow.getCell(1));
String operation = getValue(sheetRow.getCell(2));
String answer = getValue(sheetRow.getCell(3));
String keyword = getValue(sheetRow.getCell(4));
String classification = change(getValue(sheetRow.getCell(5)));
String questionType = change(getValue(sheetRow.getCell(6)));
String questionLevel = change(getValue(sheetRow.getCell(7)));
String questionGrade = "";
if (classification.equals("1")) { // 单选
questionGrade = "1";
} else if (classification.equals("2")) { // 多选
questionGrade = "2";
String temp = "";
for (int i = 0; i < answer.length(); i++) {
temp += answer.charAt(i) + ",";
}
answer = temp.substring(0, temp.length() - 1);
} else if (classification.equals("3")) { // 判断
questionGrade = "1";
operation = "1正确;2错误";
if (answer.equals("正确")) {
answer = "A";
} else {
answer = "B";
}
} else if (classification.equals("4")) { // 填空
questionGrade = "2";
String temp = answer.replace('', ';');
answer = temp;
operation = "无";
} else if (classification.equals("5")) { // 简答
questionGrade = "5";
String temp = answer.replace('', ';');
answer = temp;
if (answer.charAt(answer.length() - 1) != ';') { // 如果answer不以分号结尾
answer += ";";
}
operation = "无";
// 处理关键字
temp = keyword.replace('', ';');
keyword = temp;
if (keyword.charAt(keyword.length() - 1) != ';') { // 如果keyword不以分号结尾
keyword += ";";
}
// 关键字与标准答案互换
temp = keyword;
keyword = answer;
answer = temp;
} else if (classification.equals("6")) { // 案例
questionGrade = "10";
String temp = answer.replace('', ';');
answer = temp;
if (answer.charAt(answer.length() - 1) != ';') { // 如果answer不以分号结尾
answer += ";";
}
operation = "无";
// 处理关键字
temp = keyword.replace('', ';');
keyword = temp;
if (keyword.charAt(keyword.length() - 1) != ';') { // 如果keyword不以分号结尾
keyword += ";";
}
// 关键字与标准答案互换
temp = keyword;
keyword = answer;
answer = temp;
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
String uploadTime = df.format(new Date());
if (operation != null && operation != "") {
operation = trimBlank(operation); // 去空格
operation = operation.replace(" ", "");
answer = answer.replace(" ", "");
}
bean.setContent(content);
bean.setOperation(operation);
bean.setAnswer(answer);
bean.setClassification(classification);
bean.setQuestionType(questionType);
bean.setQuestionLevel(questionLevel);
bean.setQuestionGrade(questionGrade);
bean.setUploadTime(uploadTime);
if (keyword != null) { // 只针对案例、简答题
bean.setKeyword(keyword);
}
service.addQuestion(bean);
}
// 去除选项的不规范空格
private static String trimBlank(String operation) {
String str = operation.replace('', ';');
String[] s = str.split(";");
String result = "";
for (int i = 0; i < s.length; i++) {
char start = s[i].charAt(0);
String temp = s[i].substring(1, s[i].length()).trim();
temp = start + temp + ";";
result += temp;
}
return result.substring(0, result.length() - 1);
}
private static String getValue(HSSFCell hssfCell) {
// hssfCell.getCellType() 获取当前列的类型
if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
return String.valueOf(hssfCell.getNumericCellValue());
} else {
return String.valueOf(hssfCell.getStringCellValue());
}
}
// 将double类型字符串转化为整型
private static String change(String str) {
if (str.indexOf('.') != -1) {
return str.substring(0, str.indexOf('.'));
} else {
return str;
}
}
}