【修改】增加后台api接口注释,优化mysql判分,知识点改为存储id,试题已使用,学生除待考其它状态不可删除。。。

【新增】试卷任务参数,在已有的试卷里抽卷。。。
This commit is contained in:
YOHO\20373
2025-06-09 10:51:13 +08:00
parent d34b189598
commit a100427181
45 changed files with 1027 additions and 203 deletions

View File

@@ -1,5 +1,7 @@
package pc.exam.pp.module.judgement.controller.admin.getpoints;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pc.exam.pp.framework.common.pojo.CommonResult;
@@ -11,7 +13,7 @@ import pc.exam.pp.module.judgement.controller.service.getpoints.ExamGetPointsSer
import java.io.IOException;
import java.util.List;
@Tag(name = "管理后台 - 考点操作")
@RestController
@RequestMapping("/exam/getPoints")
public class GetPointsController {
@@ -23,6 +25,7 @@ public class GetPointsController {
* 得出文件操作考点
* @return 得分
*/
@Operation(summary = "得出文件操作考点")
@PostMapping("/get_filePoint")
@TenantIgnore
public CommonResult get_file_point(@RequestBody PointsVo pointsVo) throws IOException {
@@ -32,6 +35,7 @@ public class GetPointsController {
* 文件得出MYSQL操作考点
* @return 得分
*/
@Operation(summary = "文件得出MYSQL操作考点")
@PostMapping("/get_mysql_point")
@TenantIgnore
public CommonResult get_mysql_point(@RequestBody PointsVo pointsVo) throws IOException {
@@ -49,24 +53,26 @@ public class GetPointsController {
* 新增/更新MYSQL操作考点
* @return 得分
*/
@Operation(summary = "新增/更新MYSQL操作考点")
@PostMapping("/update_mysql_point")
@TenantIgnore
public CommonResult update_mysql_point(@RequestBody Points points) {
return CommonResult.success(examGetPointsService.update_mysql_point(points));
}
@Operation(summary = "获取考点详情")
@GetMapping("/get_Point_id/{quId}")
@TenantIgnore
public CommonResult getPointById(@PathVariable("quId") String quId) {
return CommonResult.success(examGetPointsService.getPointById(quId));
}
/**
* 新增修改浏览器操作考点
* 新增/修改浏览器操作考点
* @return 得分
*/
@Operation(summary = "新增/修改浏览器操作考点")
@PostMapping("/set_browser_point")
@TenantIgnore
//todo 老师自己设置,不读文件
//老师自己设置,不读文件
public CommonResult get_browser_point(@RequestBody Points points) {
return CommonResult.success(examGetPointsService.get_browser_point(points));
}

View File

@@ -0,0 +1,14 @@
package pc.exam.pp.module.judgement.controller.admin.getpoints.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FileNode {
private Long id;
private String name;
private Long parentId;
}

View File

@@ -0,0 +1,16 @@
package pc.exam.pp.module.judgement.controller.admin.getpoints.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestionAnswer;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FilePointsVo {
List<FileNode> nodeList;
List<ExamQuestionAnswer> examQuestionAnswerList;
}

View File

@@ -14,6 +14,8 @@ import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -24,6 +26,8 @@ public class BrowserServericeImpl implements IBrowserServerice {
static String answerLogPath ; // 文件路径
@Resource
private ExamQuestionAnswerMapper examQuestionAnswerMapper;
private static final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//考生试题文件夹
// static final String BASE_DIR = "D:/exam/4/";
//谷歌浏览器
@@ -149,7 +153,9 @@ public class BrowserServericeImpl implements IBrowserServerice {
*/
public static void appendToFile(String filePath, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
writer.write(content);
String timestamp = LocalDateTime.now().format(formatter);
String logLine = String.format("[%s] %s", timestamp, content);
writer.write(logLine);
writer.newLine(); // 可选:添加换行符
} catch (IOException e) {
e.printStackTrace();

View File

@@ -12,6 +12,8 @@ import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@@ -23,6 +25,8 @@ public class FileServericeImpl implements IFileServerice {
static String answerLogPath ; // 文件路径
@Resource
private ExamQuestionAnswerMapper examQuestionAnswerMapper;
private static final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public double run_file_point(double score,File file, ExamQuestion question) throws IOException {
@@ -116,7 +120,9 @@ public class FileServericeImpl implements IFileServerice {
*/
public static void appendToFile(String filePath, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
writer.write(content);
String timestamp = LocalDateTime.now().format(formatter);
String logLine = String.format("[%s] %s", timestamp, content);
writer.write(logLine);
writer.newLine(); // 可选:添加换行符
} catch (IOException e) {
e.printStackTrace();

View File

@@ -1,6 +1,7 @@
package pc.exam.pp.module.judgement.controller.service.getpoints;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestionAnswer;
import pc.exam.pp.module.judgement.controller.admin.getpoints.vo.FilePointsVo;
import pc.exam.pp.module.judgement.controller.admin.getpoints.vo.Points;
import pc.exam.pp.module.judgement.controller.admin.getpoints.vo.PointsVo;
@@ -11,7 +12,7 @@ public interface ExamGetPointsService {
List<ExamQuestionAnswer> get_file_point(PointsVo pointsVo) throws IOException;
FilePointsVo get_file_point(PointsVo pointsVo) throws IOException;
List<String> get_mysql_point(PointsVo pointsVo) throws IOException;

View File

@@ -15,6 +15,8 @@ import pc.exam.pp.module.exam.utils.file.GetDifferencesBetweenFolders;
import pc.exam.pp.module.exam.utils.uuid.IdUtils;
import pc.exam.pp.module.infra.dal.dataobject.config.ConfigDO;
import pc.exam.pp.module.infra.service.config.ConfigService;
import pc.exam.pp.module.judgement.controller.admin.getpoints.vo.FileNode;
import pc.exam.pp.module.judgement.controller.admin.getpoints.vo.FilePointsVo;
import pc.exam.pp.module.judgement.controller.admin.getpoints.vo.Points;
import pc.exam.pp.module.judgement.controller.admin.getpoints.vo.PointsVo;
import pc.exam.pp.module.judgement.controller.utils.zip.ZipUtil;
@@ -27,6 +29,7 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
@Service
@@ -34,6 +37,7 @@ import java.util.stream.Collectors;
public class ExamGetPointsServiceImpl implements ExamGetPointsService{
@Resource
ConfigService configService;
private static final AtomicLong ID_GENERATOR = new AtomicLong(1); // 自增 ID
@Resource
MysqlKeywordMapper mysqlKeywordMapper;
@@ -42,7 +46,7 @@ public class ExamGetPointsServiceImpl implements ExamGetPointsService{
@Override
public List<ExamQuestionAnswer> get_file_point(PointsVo pointsVo) throws IOException {
public FilePointsVo get_file_point(PointsVo pointsVo) throws IOException {
// 获取平台文件参数
ConfigDO config = configService.getConfigByKey("file_down_path");
@@ -59,10 +63,10 @@ public class ExamGetPointsServiceImpl implements ExamGetPointsService{
//解压之后得文件获取文件夹和文件
File folderStu = new File(stuFilePath);
File folderAnswer = new File(stuFilePath);
File folderAnswer = new File(answerFilePath);
List<FileNode> nodeList = ExamGetPointsServiceImpl.buildFileNodeTree(folderAnswer);
System.out.println(nodeList);
List<ExamQuestionAnswer> answerList = new ArrayList<>();
AtomicInteger sortCounter = new AtomicInteger(1); // 计数器
@@ -96,13 +100,56 @@ public class ExamGetPointsServiceImpl implements ExamGetPointsService{
zip_file_answer.delete();
deleteFolder(folderStu);
deleteFolder(folderAnswer);
return answerList;
FilePointsVo filePointsVo=new FilePointsVo();
filePointsVo.setNodeList(nodeList);
filePointsVo.setExamQuestionAnswerList(answerList);
return filePointsVo;
}
public static List<FileNode> buildFileNodeTree(File root) {
List<FileNode> result = new ArrayList<>();
if (root != null && root.exists() && root.isDirectory()) {
File[] children = root.listFiles();
if (children != null) {
for (File child : children) {
buildRecursive(child, null, result); // 从子文件夹开始构建,跳过 root
}
}
}
return result;
}
private static void buildRecursive(File file, Long parentId, List<FileNode> list) {
Long currentId = ID_GENERATOR.getAndIncrement();
FileNode node = new FileNode();
node.setId(currentId);
node.setName(file.getName());
node.setParentId(parentId);
list.add(node);
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
buildRecursive(child, currentId, list);
}
}
}
}
@Override
public List<String> get_mysql_point(PointsVo pointsVo) throws IOException {
String answerPath = pointsVo.getAnswerPath();
// 获取平台文件参数
ConfigDO config = configService.getConfigByKey("file_down_path");

View File

@@ -20,12 +20,16 @@ import pc.exam.pp.module.judgement.utils.EndStuMonitorUtils;
import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -41,15 +45,16 @@ public class MysqlServericeImpl implements IMysqlServerice {
static String databaseName;
static String databaseNameStu;
static String answerLogPath; // 文件路径
private static final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Resource
private ExamMysqlKeywordMapper examMysqlKeywordMapper;
@Resource
private ExamQuestionAnswerMapper examQuestionAnswerMapper;
private ExamQuestionAnswerMapper examQuestionAnswerMapper;
@Override
public double Judgement(double score,File filepath, ExamQuestion examQuestion) throws IOException, SQLException {
double scoreTotal =0.0;
String fileUrl= examQuestionAnswerMapper.selectAnswerFile(examQuestion.getQuId());
String path = ZipUtil.downloadStudentFile(fileUrl, "data");
// 4、获取到得是zip文件需要解压
@@ -61,18 +66,20 @@ public class MysqlServericeImpl implements IMysqlServerice {
// 5.2、查询试题ID
List<ExamQuestionAnswer> examQuestionAnswers = examQuestionAnswerMapper.selectExamQuestionAnswerByQuId(examQuestion.getQuId());
String totalKeyScore ="0";
if (examQuestionAnswers!=null&&examQuestionAnswers.size()>0){
List<String> answerIdList = examQuestionAnswers.stream()
.map(ExamQuestionAnswer::getAnswerId) // 提取每个对象的 answerId
.collect(Collectors.toList());
//得到总计得分点
System.out.println(answerIdList);
totalKeyScore=examMysqlKeywordMapper.selectByAnswerIds(answerIdList);
//得出 这个题总共的权值点
totalKeyScore=examQuestionAnswerMapper.selectCountPointByQuId(examQuestion.getQuId());
}
// if (examQuestionAnswers!=null&&examQuestionAnswers.size()>0){
// List<String> answerIdList = examQuestionAnswers.stream()
// .map(ExamQuestionAnswer::getAnswerId) // 提取每个对象的 answerId
// .collect(Collectors.toList());
// //得到总计得分点
// System.out.println(answerIdList);
// totalKeyScore=examMysqlKeywordMapper.selectByAnswerIds(answerIdList);
//
// }
answerLogPath = filepath.getParent() + File.separator + "log.txt";
AtomicInteger total = new AtomicInteger();
@@ -223,12 +230,13 @@ public class MysqlServericeImpl implements IMysqlServerice {
if (entry.getValue().trim().toUpperCase().startsWith("CREATE TABLE")) {
List<ExamMysqlKeyword> examMysqlKeywordList =new ArrayList<>();
appendToFile(answerLogPath, "==================建表语句==================");
String answerId = null;
for (ExamQuestionAnswer examQuestionAnswer : examQuestionAnswers) {
if (normalize(examQuestionAnswer.getContent()).equals(normalize(entry.getValue()))) {
// 匹配成功
String answerId = examQuestionAnswer.getAnswerId();
answerId = examQuestionAnswer.getAnswerId();
examMysqlKeywordList= examMysqlKeywordMapper.selectListByAnswerId(answerId);
break;
}
}
@@ -242,35 +250,57 @@ public class MysqlServericeImpl implements IMysqlServerice {
// 查询建表语句
String showCreateTableSql = "SHOW CREATE TABLE " + tableName;
String sql = "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, EXTRA " +
"FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = '" + tableName + "' AND TABLE_SCHEMA = '" + databaseName + "'";
String sql2 = "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, EXTRA " +
"FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = '" + tableName + "' AND TABLE_SCHEMA = '" + databaseNameStu + "'";
try (ResultSet rs = stmt.executeQuery(showCreateTableSql)) {
if (rs.next()) {
String createTableSql = rs.getString("Create Table");
// 替换 result 中的值
entry.setValue(createTableSql);
String sql1 = result.get(entry.getKey());
String sql2 = resultStu.get(entry.getKey());
String normalizedSql1 = simplifyCreateTableSql(sql1);
String normalizedSql2 = simplifyCreateTableSql(sql2);
if (normalizedSql1.equals(normalizedSql2)) {
//
accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score);
} else {
int scoreAnswerNotAllTrue =calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score);
total.addAndGet(scoreAnswerNotAllTrue);
}
// 获取主库字段信息
Set<Map<String, String>> table1Columns = new HashSet<>();
try (ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
Map<String, String> column = new HashMap<>();
column.put("COLUMN_NAME", rs.getString("COLUMN_NAME"));
column.put("COLUMN_TYPE", rs.getString("COLUMN_TYPE"));
column.put("IS_NULLABLE", rs.getString("IS_NULLABLE"));
column.put("COLUMN_KEY", rs.getString("COLUMN_KEY"));
column.put("EXTRA", rs.getString("EXTRA"));
table1Columns.add(column);
}
}catch (SQLException e) {
appendToFile(answerLogPath, "执行验证 SQL 出错!");
e.printStackTrace();
appendToFile(answerLogPath, "标准答案建表键值对:"+table1Columns);
}
// 获取学生库字段信息
Set<Map<String, String>> table2Columns = new HashSet<>();
try (Connection connstu = DriverManager.getConnection(stuDbUrl, user, password);
Statement stmtstu = connstu.createStatement()) {
try (ResultSet rsstu = stmtstu.executeQuery(sql2)) {
while (rsstu.next()) {
Map<String, String> column = new HashMap<>();
column.put("COLUMN_NAME", rsstu.getString("COLUMN_NAME"));
column.put("COLUMN_TYPE", rsstu.getString("COLUMN_TYPE"));
column.put("IS_NULLABLE", rsstu.getString("IS_NULLABLE"));
column.put("COLUMN_KEY", rsstu.getString("COLUMN_KEY"));
column.put("EXTRA", rsstu.getString("EXTRA"));
table2Columns.add(column);
}
appendToFile(answerLogPath, "学生答案建表键值对:"+table2Columns);
}
}
String sql3 = resultStu.get(entry.getKey());
if (table1Columns.equals(table2Columns)) {
//
double sr= accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql3,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sr;
} else {
double sw= calculateTotalScoreRate(sql3, examMysqlKeywordList,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sw;
}
}
}
@@ -284,12 +314,13 @@ public class MysqlServericeImpl implements IMysqlServerice {
if (matcher.find()) {
String tableName = matcher.group(1).replace("`", ""); // 获取表名
String answerId=null;
for (ExamQuestionAnswer examQuestionAnswer : examQuestionAnswers) {
if (normalize(examQuestionAnswer.getContent()).equals(normalize(entry.getValue()))) {
// 匹配成功
String answerId = examQuestionAnswer.getAnswerId();
answerId = examQuestionAnswer.getAnswerId();
examMysqlKeywordList= examMysqlKeywordMapper.selectListByAnswerId(answerId);
break;
}
}
@@ -302,12 +333,11 @@ public class MysqlServericeImpl implements IMysqlServerice {
boolean equals = sql1.equals(sql2);
if (equals) {
accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score);
double sr=accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sr;
} else {
int scoreAnswerNotAllTrue =calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score);
total.addAndGet(scoreAnswerNotAllTrue);
double sw= calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sw;
}
@@ -321,7 +351,7 @@ public class MysqlServericeImpl implements IMysqlServerice {
List<ExamMysqlKeyword> examMysqlKeywordList =new ArrayList<>();
String delStatement = entry.getValue();
delStatement = delStatement.trim().replaceAll(";+\\s*$", "");
String answerId =null;
String sql2 = resultStu.get(entry.getKey());
// 正则提取表名和 WHERE 条件
Pattern pattern = Pattern.compile("DELETE\\s+FROM\\s+(\\w+)\\s+WHERE\\s+(.+)", Pattern.CASE_INSENSITIVE);
@@ -329,9 +359,9 @@ public class MysqlServericeImpl implements IMysqlServerice {
for (ExamQuestionAnswer examQuestionAnswer : examQuestionAnswers) {
if (normalize(examQuestionAnswer.getContent()).equals(normalize(entry.getValue()))) {
// 匹配成功
String answerId = examQuestionAnswer.getAnswerId();
answerId = examQuestionAnswer.getAnswerId();
examMysqlKeywordList= examMysqlKeywordMapper.selectListByAnswerId(answerId);
break;
}
}
@@ -360,13 +390,11 @@ public class MysqlServericeImpl implements IMysqlServerice {
//累加删除语句的所有权值 examQuestionKeywords累加scorerate
appendToFile(answerLogPath, "验证通过:符合 DELETE 条件的记录已删除。");
accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score);
double sr= accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sr;
} else {
int scoreAnswerNotAllTrue =calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score);
total.addAndGet(scoreAnswerNotAllTrue);
double sw= calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sw;
}
}
}catch (SQLException e) {
@@ -394,12 +422,13 @@ public class MysqlServericeImpl implements IMysqlServerice {
appendToFile(answerLogPath, "==================更新语句==================");
List<ExamMysqlKeyword> examMysqlKeywordList =new ArrayList<>();
String sql1 = entry.getValue();
String answerId=null;
for (ExamQuestionAnswer examQuestionAnswer : examQuestionAnswers) {
if (normalize(examQuestionAnswer.getContent()).equals(normalize(entry.getValue()))) {
// 匹配成功
String answerId = examQuestionAnswer.getAnswerId();
answerId = examQuestionAnswer.getAnswerId();
examMysqlKeywordList= examMysqlKeywordMapper.selectListByAnswerId(answerId);
break;
}
}
@@ -413,11 +442,11 @@ public class MysqlServericeImpl implements IMysqlServerice {
//
if (b) {
accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score);
double sr= accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sr;
} else {
int scoreAnswerNotAllTrue =calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score);
total.addAndGet(scoreAnswerNotAllTrue);
// appendToFile(answerLogPath,"语句"+sql2+"不正确,关键得分:"+scoreAnswerNotAllTrue+ "❌");
double sw= calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sw;
}
@@ -426,12 +455,13 @@ public class MysqlServericeImpl implements IMysqlServerice {
if (entry.getValue().trim().toUpperCase().startsWith("SELECT")) {
appendToFile(answerLogPath, "==================查找语句==================");
List<ExamMysqlKeyword> examMysqlKeywordList =new ArrayList<>();
String answerId =null;
for (ExamQuestionAnswer examQuestionAnswer : examQuestionAnswers) {
if (normalize(examQuestionAnswer.getContent()).equals(normalize(entry.getValue()))) {
// 匹配成功
String answerId = examQuestionAnswer.getAnswerId();
answerId = examQuestionAnswer.getAnswerId();
examMysqlKeywordList= examMysqlKeywordMapper.selectListByAnswerId(answerId);
break;
}
}
@@ -446,6 +476,7 @@ public class MysqlServericeImpl implements IMysqlServerice {
Statement stmtan = connanswer.createStatement()) {
try (ResultSet answer = stmtan.executeQuery(sql1)) {
answerList = getAnswerList(answer);
appendToFile(answerLogPath, "查找语句标准答案");
printResult(answerList);
}catch (SQLException e) {
appendToFile(answerLogPath, "执行验证语句"+sql1+"时发生错误: " + e.getMessage());
@@ -456,9 +487,10 @@ public class MysqlServericeImpl implements IMysqlServerice {
Statement stmtstu = connstu.createStatement()) {
try (ResultSet answer = stmtstu.executeQuery(sql2)) {
answerListStu = getAnswerList(answer);
appendToFile(answerLogPath, "学生语句答案");
printResult(answerListStu);
} catch (SQLException e) {
appendToFile(answerLogPath, "执行学生库语句"+sql2+"时发生错误: " + e.getMessage()+"得分0 ❌");
appendToFile(answerLogPath, "执行学生库语句"+sql2+"时发生错误: " + e.getMessage());
}
@@ -471,13 +503,12 @@ public class MysqlServericeImpl implements IMysqlServerice {
if (isEquivalent) {
//todo 得分
accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score);
double sr= accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sr;
} else {
int scoreAnswerNotAllTrue =calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score);
total.addAndGet(scoreAnswerNotAllTrue);
// appendToFile(answerLogPath,"语句"+sql2+"不正确,关键得分:"+scoreAnswerNotAllTrue+ "❌");
double sw= calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sw;
}
@@ -488,12 +519,13 @@ public class MysqlServericeImpl implements IMysqlServerice {
if (entry.getValue().trim().replaceAll("\\s+", " ").matches("(?i)^CREATE( OR REPLACE)?( ALGORITHM\\s*=\\s*\\w+)?( DEFINER\\s*=\\s*[`\"'\\w@%\\.]+)?( SQL SECURITY \\w+)? VIEW\\b.*")) {
appendToFile(answerLogPath, "==================视图语句==================");
List<ExamMysqlKeyword> examMysqlKeywordList =new ArrayList<>();
String answerId=null;
for (ExamQuestionAnswer examQuestionAnswer : examQuestionAnswers) {
if (normalize(examQuestionAnswer.getContent()).equals(normalize(entry.getValue()))) {
// 匹配成功
String answerId = examQuestionAnswer.getAnswerId();
answerId = examQuestionAnswer.getAnswerId();
examMysqlKeywordList= examMysqlKeywordMapper.selectListByAnswerId(answerId);
break;
}
}
@@ -526,12 +558,13 @@ public class MysqlServericeImpl implements IMysqlServerice {
// 执行 CREATE VIEW 语句,创建视图
stmt.execute(createView1);
boolean hasError = false; // 添加标志变量
try {
stmt.execute(createView2);
} catch (SQLException e) {
appendToFile(answerLogPath, "执行学生库语句"+createView2+"时发生错误: " + e.getMessage()+"得分0 ❌");
appendToFile(answerLogPath, "执行学生库语句"+createView2+"时发生错误: " + e.getMessage());
hasError = true; // 发生异常,设为 true
}
// 执行查询获取视图1的结果
@@ -546,7 +579,7 @@ public class MysqlServericeImpl implements IMysqlServerice {
printResult(result2);
// 比较两个视图的结果
boolean isEquivalent = compareResults(result1, result2);
boolean isEquivalent = !hasError &&compareResults(result1, result2);
appendToFile(answerLogPath, "\n是否结果等价: " + isEquivalent);
// 删除视图
@@ -554,12 +587,11 @@ public class MysqlServericeImpl implements IMysqlServerice {
stmt.execute("DROP VIEW IF EXISTS " + viewName1);
stmt.execute("DROP VIEW IF EXISTS " + viewName2);
if (isEquivalent) {
accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score);
double sr= accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sr;
} else {
int scoreAnswerNotAllTrue =calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score);
total.addAndGet(scoreAnswerNotAllTrue);
double sw= calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sw;
}
// }
@@ -569,13 +601,14 @@ public class MysqlServericeImpl implements IMysqlServerice {
//存储过程
if (entry.getValue().trim().toUpperCase().toUpperCase().contains("PROCEDURE")) {
String answerId=null;
List<ExamMysqlKeyword> examMysqlKeywordList =new ArrayList<>();
for (ExamQuestionAnswer examQuestionAnswer : examQuestionAnswers) {
if (normalize(examQuestionAnswer.getContent()).equals(normalize(entry.getValue()))) {
// 匹配成功
String answerId = examQuestionAnswer.getAnswerId();
answerId = examQuestionAnswer.getAnswerId();
examMysqlKeywordList= examMysqlKeywordMapper.selectListByAnswerId(answerId);
break;
}
}
@@ -603,7 +636,7 @@ public class MysqlServericeImpl implements IMysqlServerice {
} catch (SQLException e) {
appendToFile(answerLogPath, "执行标准库 SQL CALL 语句时发生错误: " + e.getMessage());
}
boolean hasError = false; // 添加标志变量
try (Connection connstu = DriverManager.getConnection(stuDbUrl, user, password);
Statement stmtstu = connstu.createStatement()) {
@@ -616,26 +649,31 @@ public class MysqlServericeImpl implements IMysqlServerice {
stuResults.addAll(extractResults(oldResult));
} catch (SQLException e) {
appendToFile(answerLogPath, "执行学生库 SQL CALL 语句时发生错误: " + e.getMessage());
hasError = true; // 发生异常,设为 true
}
// 比较结果
boolean flag = compareExtractResults(anwerResults, stuResults);
if (flag) {
//todo 得分
accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score);
} else {
//得分
int scoreAnswerNotAllTrue =calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score);
total.addAndGet(scoreAnswerNotAllTrue);
}
} catch (SQLException e) {
appendToFile(answerLogPath, "执行学生库语句"+sql2+"时发生错误: " + e.getMessage()+"得分0 ❌");
appendToFile(answerLogPath, "执行学生库语句"+sql2+"时发生错误: " + e.getMessage());
hasError = true; // 发生异常,设为 true
}
// 比较结果(如果发生异常,可以认为比较失败)
boolean flag = !hasError && compareExtractResults(anwerResults, stuResults);
if (flag) {
//todo 得分
double sr= accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score,answerId,scoreTotal);
scoreTotal+=sr;
} else {
//得分
double sw = calculateTotalScoreRate(sql2, examMysqlKeywordList, totalKeyScore, score, answerId, scoreTotal);
scoreTotal+=sw;
}
}
@@ -646,12 +684,13 @@ public class MysqlServericeImpl implements IMysqlServerice {
if (entry.getValue().trim().toUpperCase().toUpperCase().contains("TRIGGER")) {
appendToFile(answerLogPath, "==================触发器==================");
List<ExamMysqlKeyword> examMysqlKeywordList =new ArrayList<>();
String answerId=null;
for (ExamQuestionAnswer examQuestionAnswer : examQuestionAnswers) {
if (normalize(examQuestionAnswer.getContent()).equals(normalize(entry.getValue()))) {
// 匹配成功
String answerId = examQuestionAnswer.getAnswerId();
answerId = examQuestionAnswer.getAnswerId();
examMysqlKeywordList= examMysqlKeywordMapper.selectListByAnswerId(answerId);
break;
}
}
@@ -675,10 +714,12 @@ public class MysqlServericeImpl implements IMysqlServerice {
boolean equals = normalizedTriggerSql1.equals(normalizedTriggerSql2);
if (equals) {
//todo 得分
accumulateScoreAndLog(examMysqlKeywordList,total,answerLogPath,sql2,totalKeyScore,score);
double sr= accumulateScoreAndLog(examMysqlKeywordList, total, answerLogPath, sql2, totalKeyScore, score, answerId, scoreTotal);
scoreTotal+=sr;
} else {
int scoreAnswerNotAllTrue =calculateTotalScoreRate(sql2, examMysqlKeywordList,totalKeyScore,score);
total.addAndGet(scoreAnswerNotAllTrue);
double sw = calculateTotalScoreRate(sql2, examMysqlKeywordList, totalKeyScore, score, answerId, scoreTotal);
scoreTotal+=sw;
}
@@ -698,25 +739,11 @@ public class MysqlServericeImpl implements IMysqlServerice {
}
}
double roundedResult =0.0;
try {
int totalKeyScoreInt = Integer.parseInt(totalKeyScore.trim());
if (totalKeyScoreInt != 0) {
double result = (total.get() * 1.0 / totalKeyScoreInt) * score;
// 保留两位小数
// 保留两位小数的 double四舍五入
roundedResult = Math.round(result * 100.0) / 100.0;
System.out.println("最终结果是:" + roundedResult);
} else {
System.out.println("除数不能为 0");
}
} catch (NumberFormatException e) {
System.out.println("无效的 totalKeyScore 值:" + totalKeyScore);
}
appendToFile(answerLogPath, "共得分:"+roundedResult);
appendToFile(answerLogPath, "共得分:"+scoreTotal);
folderzip.delete();
deleteFolder(folder);
return roundedResult;
return scoreTotal;
}
@@ -731,34 +758,66 @@ public class MysqlServericeImpl implements IMysqlServerice {
}
folder.delete(); // 删除空文件夹或文件
}
//如果这个小题对了,直接累加对应的权值分
private double accumulateScoreAndLog(List<ExamMysqlKeyword> examMysqlKeywordList, AtomicInteger total, String answerLogPath, String sql2, String totalKeyScore, double score,String answerId,double scoreTotal) {
//用answerid查对应答案的权值 。除以总权值
String scoreRateStr= examQuestionAnswerMapper.selectExamQuestionAnswerScoreByAnswerId(answerId);
private static void accumulateScoreAndLog(List<ExamMysqlKeyword> examMysqlKeywordList, AtomicInteger total, String answerLogPath, String sql2, String totalKeyScore, double score) {
AtomicInteger singleTotal = new AtomicInteger(); // 单独累加 scoreRateStr 的总和
for (ExamMysqlKeyword examMysqlKeyword : examMysqlKeywordList) {
String scoreRateStr = examMysqlKeyword.getScoreRate();
if (scoreRateStr != null && !scoreRateStr.trim().isEmpty()) {
try {
int scoreAnswerAllTrue = Integer.parseInt(scoreRateStr.trim());
total.addAndGet(scoreAnswerAllTrue);
singleTotal.addAndGet(scoreAnswerAllTrue); // 单独累加
} catch (NumberFormatException e) {
System.err.println("无效的scoreRate值" + scoreRateStr);
}
}
}
// 解析权值
double scoreRate = 0.0;
double totalKey = 0.0;
double singleScore = 0.0;
try {
int totalKeyScoreInt = Integer.parseInt(totalKeyScore.trim());
double finalScore = ((double) singleTotal.get() / totalKeyScoreInt) * score;
String formattedScore = String.format("%.1f", finalScore);
appendToFile(answerLogPath, "✅语句" + sql2 + "正确,关键得分权值:" + singleTotal.get() + ",得分" + formattedScore);
scoreRate = Double.parseDouble(scoreRateStr);
totalKey = Double.parseDouble(totalKeyScore);
// 计算该答案对应的得分
if (totalKey > 0) {
singleScore = (scoreRate / totalKey) * score;
singleScore = Math.round(singleScore * 100.0) / 100.0;
System.out.println(scoreTotal);
System.out.println(singleScore);
System.out.println(scoreTotal);
}
appendToFile(answerLogPath, "✅语句" + sql2 + "正确,语句得分权值:" + scoreRateStr + ",得分" + singleScore);
} catch (NumberFormatException e) {
System.err.println("无效的totalKeyScore值" + totalKeyScore);
}
return singleScore;
}
public static int calculateTotalScoreRate(String sql, List<ExamMysqlKeyword> examQuestionKeywords, String totalKeyScore, double score) {
public double calculateTotalScoreRate(String sql, List<ExamMysqlKeyword> examQuestionKeywords, String totalKeyScore, double score,String answerId,double scoreTotal) {
//用answerid查对应答案的权值 。除以总权值
String scoreRateStr= examQuestionAnswerMapper.selectExamQuestionAnswerScoreByAnswerId(answerId);
// 解析权值
double scoreRate = 0.0;
double totalKey = 0.0;
// 计算该答案对应的得分
double singleScore = 0.0;
try {
scoreRate = Double.parseDouble(scoreRateStr);
totalKey = Double.parseDouble(totalKeyScore);
if (totalKey > 0) {
singleScore = (scoreRate / totalKey) * score;
singleScore = Math.round(singleScore * 100.0) / 100.0;
}
} catch (NumberFormatException e) {
System.err.println("无效的totalKeyScore值" + totalKeyScore);
}
int totalScoreRate = 0;
Set<String> matchedKeywords = new HashSet<>();
for (ExamMysqlKeyword keyword : examQuestionKeywords) {
@@ -777,11 +836,20 @@ public class MysqlServericeImpl implements IMysqlServerice {
}
}
}
int totalKeyScoreInt = Integer.parseInt(totalKeyScore.trim());
double finalScore = ((double) totalScoreRate / totalKeyScoreInt) * score;
String formattedScore = String.format("%.1f", finalScore);
appendToFile(answerLogPath,"❌语句"+sql+"不正确,答对得分点为:"+matchedKeywords+"关键得分权值"+ totalScoreRate+ ",得分" + formattedScore);
return totalScoreRate;
//累加答案关键字的所有权值
int totalKeyScoreInt = examQuestionKeywords.stream()
.map(ExamMysqlKeyword::getScoreRate)
.filter(s -> s != null && !s.isEmpty())
.mapToInt(Integer::parseInt)
.sum();
//乘以 对了多少个 关键字 权值
double finalRoundedScore = new BigDecimal(
((double) totalScoreRate / totalKeyScoreInt) * singleScore
).setScale(2, RoundingMode.HALF_UP).doubleValue();
appendToFile(answerLogPath,"❌语句"+sql+"不正确,语句权值:"+scoreRateStr+",关键权值:"+totalKeyScoreInt+",答对得分点为:"+matchedKeywords+",答对关键得分权值"+ totalScoreRate+ ",得分" + finalRoundedScore);
return finalRoundedScore;
}
// 预处理函数:去除空格和换行并转为大写
@@ -1033,21 +1101,26 @@ public class MysqlServericeImpl implements IMysqlServerice {
*/
private static void printResult(List<List<String>> result) {
if (result.isEmpty()) {
appendToFile(answerLogPath,"查询结果为空");
appendToFile(answerLogPath, "查询结果为空");
} else {
// 打印每一行数据
for (int i = 0; i < result.size(); i++) {
List<String> row = result.get(i);
if (i == 0) { // 打印列名
appendToFile(answerLogPath,"列名:");
StringBuilder sb = new StringBuilder();
if (i == 0) {
sb.append("列名:");
}
for (String value : row) {
appendToFile(answerLogPath,value + "\t");
sb.append(value).append("\t");
}
System.out.println();
// 输出整行
appendToFile(answerLogPath, sb.toString());
}
}
}
/**
* 使用提供的正则表达式模式从给定的 SQL 语句中提取视图名称。
*/
@@ -1250,7 +1323,9 @@ public class MysqlServericeImpl implements IMysqlServerice {
*/
public static void appendToFile(String filePath, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
writer.write(content);
String timestamp = LocalDateTime.now().format(formatter);
String logLine = String.format("[%s] %s", timestamp, content);
writer.write(logLine);
writer.newLine(); // 可选:添加换行符
} catch (IOException e) {
e.printStackTrace();