Merge branch refs/heads/master into refs/heads/hyc

This commit is contained in:
华允传
2025-04-25 16:00:15 +08:00
26 changed files with 928 additions and 17 deletions

View File

@@ -0,0 +1,15 @@
package pc.exam.pp.module.exam.controller.admin.specialty.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
@Schema(description = "管理后台 - 专业列表 Request VO")
@Data
public class SpecialtListByUserReqVo {
@Schema(description = "用户类型", example = "xxxx")
private String userType;
}

View File

@@ -11,6 +11,7 @@ import pc.exam.pp.framework.mybatis.core.query.LambdaQueryWrapperX;
import pc.exam.pp.module.exam.controller.admin.paper.vo.PaperTaskPageVo;
import pc.exam.pp.module.exam.dal.dataobject.ExamPaperKnowledgePoints;
import pc.exam.pp.module.exam.dal.dataobject.EducationPaperTask;
import pc.exam.pp.module.exam.dal.dataobject.ExamPaperKnowledgePoints;
/**
* 试卷任务Mapper接口

View File

@@ -1,11 +1,13 @@
package pc.exam.pp.module.exam.dal.mysql.specialty;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import pc.exam.pp.framework.mybatis.core.mapper.BaseMapperX;
import pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtListReqVo;
import pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtyQueryVo;
import pc.exam.pp.module.exam.dal.dataobject.specialty.ExamSpecialty;
import java.util.List;
import java.util.Set;
/**
* 客户端Mapper接口
@@ -40,6 +42,20 @@ public interface ExamSpecialtyMapper extends BaseMapperX<ExamSpecialty>
*/
public List<SpecialtyQueryVo> selectExamSpecialtyListVo(SpecialtListReqVo reqVo);
/**
* 查询所有数据信息
*
* @return 数据集合
*/
public List<SpecialtyQueryVo> selectExamSpecialtyAll();
/**
* 通过ID查询数据数据信息
*
* @return 数据集合
*/
public List<SpecialtyQueryVo> selectExamSpecialtyByids(@Param("ids") Set<Long> ids);
/**
* 查询部分数据信息
*

View File

@@ -7,6 +7,7 @@ import pc.exam.pp.module.exam.controller.admin.paper.dto.TempDto;
import pc.exam.pp.module.exam.controller.admin.paper.vo.PaperTaskPageVo;
import pc.exam.pp.module.exam.dal.dataobject.ExamPaperKnowledgePoints;
import pc.exam.pp.module.exam.dal.dataobject.EducationPaperTask;
import pc.exam.pp.module.exam.dal.dataobject.ExamPaperKnowledgePoints;
import java.util.List;

View File

@@ -25,6 +25,8 @@
<result property="spName" column="sp_name" />
<result property="orderNum" column="order_num" />
<result property="status" column="status" />
<result property="unite" column="unite" />
<result property="treeNum" column="tree_num" />
</resultMap>

View File

@@ -28,6 +28,19 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</where>
</select>
<select id="selectExamSpecialtyAll" resultType="pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtyQueryVo">
select sp_id as id, sp_name as name, parent_id, status, create_time from exam_specialty where deleted = 0 and status = 0
</select>
<select id="selectExamSpecialtyByids" resultType="pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtyQueryVo">
SELECT sp_id AS id, sp_name AS name, parent_id, status, create_time from exam_specialty
WHERE sp_id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
AND deleted = 0 and status = 0
</select>
<select id="selectExamSpecialtyPart" resultType="pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtyQueryVo">
select sp_id as id, sp_name as name, parent_id, status, create_time
FROM exam_specialty

View File

@@ -0,0 +1,4 @@
package pc.exam.pp.module.judgement.controller.admin.Gcc;
public class GccController {
}

View File

@@ -1,4 +0,0 @@
package pc.exam.pp.module.judgement.controller.admin;
public class GccController {
}

View File

@@ -0,0 +1,4 @@
package pc.exam.pp.module.judgement.controller.admin.autoTools;
public class AutoToolsController {
}

View File

@@ -0,0 +1,19 @@
package pc.exam.pp.module.judgement.controller.admin.autoTools.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
public class StudentUploadFileZipReqVo {
@Schema(description = "学号")
private Long studentId;
@Schema(description = "试卷号")
private String paperId;
@Schema(description = "上传文件路径")
private String filePath;
}

View File

@@ -0,0 +1,26 @@
package pc.exam.pp.module.judgement.service.auto_tools;
public interface AutoToolsService {
// 文件自动上传
// Boolean autoFileTools(Long studentId, String paperId);
/**
* 文件下载
* @param fileUrl 文件url
* @param filePath 要下载的文件路径
* @return 下载后的文件path
*/
String downloadStudentFile(String fileUrl, String filePath);
//
/**
* 解压文件
* @param zipFilePath zip文件路径
* @return 解压后的目录
*/
String unzipToNamedFolder(String zipFilePath);
}

View File

@@ -0,0 +1,97 @@
package pc.exam.pp.module.judgement.service.auto_tools;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@Service
public class AutoToolsServiceImpl implements AutoToolsService{
@Override
public String downloadStudentFile(String fileUrl, String filePath) {
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
String fileName = new File(url.getPath()).getName();
File dir = new File(filePath);
if (!dir.exists()) dir.mkdirs();
File saveFile = new File(dir, fileName);
try (InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(saveFile)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("✅ 下载成功: " + saveFile.getAbsolutePath());
return saveFile.getAbsolutePath();
}
} catch (IOException e) {
System.err.println("❌ 下载失败: " + e.getMessage());
return null;
}
}
@Override
public String unzipToNamedFolder(String zipFilePath) {
File zipFile = new File(zipFilePath);
if (!zipFile.exists() || !zipFile.getName().toLowerCase().endsWith(".zip")) {
System.err.println("❌ 无效 zip 文件: " + zipFilePath);
return null;
}
// 提取 zip 文件名(无扩展)
String fileNameNoExt = zipFile.getName().replaceAll("(?i)\\.zip$", "");
// 自动拼接系统适配路径
File extractDir = new File(zipFile.getParentFile(), fileNameNoExt);
if (!extractDir.exists()) {
extractDir.mkdirs();
}
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File outFile = new File(extractDir, entry.getName());
// 防止 Zip 路径穿越攻击
if (!outFile.getCanonicalPath().startsWith(extractDir.getCanonicalPath())) {
throw new IOException("非法路径: " + entry.getName());
}
if (entry.isDirectory()) {
outFile.mkdirs();
} else {
File parent = outFile.getParentFile();
if (!parent.exists()) parent.mkdirs();
try (FileOutputStream fos = new FileOutputStream(outFile)) {
byte[] buffer = new byte[4096];
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
zis.closeEntry();
}
System.out.println("✅ 解压完成,目录:" + extractDir.getAbsolutePath());
return extractDir.getAbsolutePath();
} catch (IOException e) {
System.err.println("❌ 解压出错: " + e.getMessage());
return null;
}
}
}

View File

@@ -0,0 +1,29 @@
package pc.exam.pp.module.judgement.service.c_programming;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestion;
/**
* 判分逻辑集合
*
* @author rwb
*/
public interface JudgementService {
/**
* 程序设计判分
* @param examQuestion 程序设计题内容
* @param path 文件路径
* @param score 分数
* @return 返回判分
*/
public double ProgrammingC(double score, String path, ExamQuestion examQuestion);
/**
* 出题时测试运行C语言代码
* @param code 源码
* @return 运行结果
*/
public String run_test_result(String code);
}

View File

@@ -0,0 +1,207 @@
package pc.exam.pp.module.judgement.service.c_programming;
import org.springframework.stereotype.Service;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestion;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestionAnswer;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestionKeyword;
import pc.exam.pp.module.exam.utils.file.LogFileUtils;
import pc.exam.pp.module.judgement.utils.JudgementCUtils;
import java.util.*;
/**
* 判分逻辑集合
*
* @author rwb
*/
@Service
public class JudgementServiceImpl implements JudgementService
{
/**
* 程序设计判分
* @param examQuestion 程序设计题内容
* @param path 文件路径
* @param score 分数
* @return 返回判分
*/
public double ProgrammingC(double score, String path, ExamQuestion examQuestion) {
// 关键字比对,超过权重-测试用例/运行(测试用例全对,直接满分-不全对)-结果,不超过权重只给关键字几个的分
// 获取该题有多少分
// TODO 测试分数15该程序设计题为15分
// double score = 15;
// 总分
double totalScore = 0;
// 测试用例结果分数
double compile_score = 0;
// 关键字分数
double key_score = 0;
// 关键字分数
double result_score = 0;
// 先获取题的组成部分
// 是否需要程序编译 (0:true;1:false)
boolean is_pass = Objects.equals(examQuestion.getQuestionScores().getIsPass(), "0");
// 是否需要程序结果 (0:true;1:false)
boolean is_result = Objects.equals(examQuestion.getQuestionScores().getIsResult(), "0");
// 是否需要关键字 (0:true;1:false)
boolean is_keyword = Objects.equals(examQuestion.getQuestionScores().getIsKeyword(), "0");
// 是否需要测试用例 (0:true;1:false)
boolean is_compile = Objects.equals(examQuestion.getQuestionScores().getIsCompile(), "0");
// 占比百分比
double is_pass_score = Integer.parseInt(examQuestion.getQuestionScores().getIsPassScore()) / 100.0;
double is_result_score = Integer.parseInt(examQuestion.getQuestionScores().getIsResultScore()) / 100.0;
double is_keyword_score = Integer.parseInt(examQuestion.getQuestionScores().getIsKeywordScore()) / 100.0;
double is_compile_score = Integer.parseInt(examQuestion.getQuestionScores().getIsCompileScore()) / 100.0;
// 关键字分数占比
double keyword_score = score * is_keyword_score;
// 编译分数分数占比
double pass_score = score * is_pass_score;
// 试卷其中有C语言的试题
String path_c = path + "/" + examQuestion.getQuBankName();
// 创建log文件txt用于记录
LogFileUtils.createFile(path_c + "/log.txt");
String code = JudgementCUtils.readFile(path_c, examQuestion.getQuId()+".txt");
LogFileUtils.writeLine("✅ 系统开始读取文件:" + code);
if (code == null) {
// 如果没有读到源码
LogFileUtils.writeLine("❌ 系统没有读取到文件。");
LogFileUtils.close();
// 该题不得分直接算成0分
return 0;
}
int true_number = 0;
// 关键字分数
if (is_keyword) {
// 总权重值
int weight = 0;
List<Map<String, Object>> key_list = new ArrayList<>();
// 进行关键字权重比对进行判断
for (ExamQuestionKeyword examQuestionKeyword : examQuestion.getQuestionKeywords()) {
boolean keyword_run = code.contains(examQuestionKeyword.getKeyword());
// 计算权值
Map<String, Object> item = new HashMap<>();
item.put("success", keyword_run);
item.put("score_rate", examQuestionKeyword.getScoreRate());
LogFileUtils.writeLine("✅ 关键字比对:" + examQuestionKeyword.getKeyword() + "--" + keyword_run);
weight += Integer.parseInt(examQuestionKeyword.getScoreRate());
key_list.add(item);
}
// 所有的关键字比对完成之后进行盘端关键字的分数
// 先获取关键字应该分数占比
double one_keyword_score = keyword_score / weight;
// 根据权重进行给分
for (Map<String, Object> item : key_list) {
// 判断首先等于true 的情况下
if ((boolean)item.get("success")) {
// 每个选项分值 = 总分 / 总权重
true_number += 1;
key_score += one_keyword_score * Integer.parseInt((String) item.get("score_rate"));
LogFileUtils.writeLine("✅ 关键字得分:" + key_score);
}
}
}
// 程序需要在运行测试用例,及满足关键字的情况下进行给出运行得分
// 关键字临界得分值
int todo_key_percentage = Integer.parseInt(examQuestion.getQuestionScores().getKeywordCutoff());
if (key_score > keyword_score * ((double) todo_key_percentage / 100) ) {
// 编译代码运行
if (is_pass) {
// 如果使用程序编译,进行程序编译
LogFileUtils.writeLine("✅ 正在使用-std=c99进行编译...");
// 使用C99 运行并得出结果
String code_return = JudgementCUtils.run_code(code,null,"-std=c99", "编译通过运行");
if (!code_return.contains("error")) {
// 编译没有报错,加上编译分数
totalScore += pass_score;
LogFileUtils.writeLine("✅ 编译通过得分:" + pass_score);
} else {
LogFileUtils.writeLine("❌ 编译未通过。");
}
}
// 进行判断测试用例
// 测试用例
// 判断是否要程序结果 ,需要程序结果的,就需要测试用例
if (is_compile) {
// 先运行程序,再将测试用例进行比对
// 运行完成后在判断是否需要进行关键字比对
boolean run_code = false;
List<Boolean> runList = new ArrayList<>();
LogFileUtils.writeLine("✅ 使用测试用例进行判分...");
for (ExamQuestionAnswer examQuestionAnswer : examQuestion.getAnswerList()) {
// 使用C99 运行并得出结果
String code_return = JudgementCUtils.run_code(code, examQuestionAnswer.getContentIn(),"-std=c99",null);
String actual = code_return.trim();
String expected = examQuestionAnswer.getContent().trim();
if (actual.equals(expected)) {
// 判断测试用例结果是否正确
runList.add(true);
// 获取测试用例临界值,并进行判断
// if (runList.size() >= Integer.parseInt(examQuestion.getQuestionScores().getCompileCutoff()) && !runList.contains(false)) {
// // 测试用例得分
// compile_score += (double) (score * is_compile_score);
// // 结果得分
// result_score += (double) (score * is_result_score);
// LogFileUtils.writeLine("✅ 测试用例得分:" + compile_score);
// break;
// }
}
}
// 记录存在多少个测试用例,并且同时记录正确测试用例个数
int test_case_number = examQuestion.getAnswerList().size();
int true_test_case_number = runList.size();
// 判断正确关系
// 1、如果完全相等说明完全正确直接给满分
if (test_case_number == true_test_case_number) {
// 满分,该题多少分就是多少分
LogFileUtils.writeLine("✅ 测试用例全部正确:"+ score);
LogFileUtils.close();
return score;
} else if (test_case_number > true_test_case_number) {
// 2、测试用例没有完全正确对多少个就是多少分
// 公式:测试用例总分数 / 测试用例数量 * 正确测试用例数量
compile_score += (double) ((score * is_compile_score) / test_case_number) * true_test_case_number;
LogFileUtils.writeLine("✅ 测试用例数量:"+ test_case_number + ",正确数量:" + true_test_case_number + ",得分:" + compile_score);
}
}
// 总分 = 总分 + 测试用例得分
totalScore += compile_score;
if (compile_score > 0) {
// 如果测试用例正确有得分的
// 结果
if (is_result) {
// 总分 = 总分 + 结果得分
totalScore += result_score;
LogFileUtils.writeLine("✅ 结果得分:" + result_score);
}
}
totalScore += key_score;
LogFileUtils.close();
return totalScore;
} else {
// 关键字对几个给几分,没有达到临界值的情况下
totalScore += key_score;
LogFileUtils.writeLine("❌ 关键字没有达到临界值,正确数量:"+ true_number);
LogFileUtils.close();
return totalScore;
}
}
/**
*
* @param code 源码
* @return 运行结果
*/
@Override
public String run_test_result(String code){
// 使用C99 运行并得出结果
return JudgementCUtils.run_test_code(code,"-std=c99");
}
}

View File

@@ -0,0 +1,22 @@
package pc.exam.pp.module.judgement.service.choice;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestion;
/**
* 判分逻辑集合(选择题)
*
* @author rwb
*/
public interface JudgementChoiceService {
/**
*
* @param score 题分
* @param examQuestion 选择题内容(学生答题)
* @param originalExamQuestion 原始题(判断答案)
* @return 得分
*/
public double ProgrammingChoice(double score, ExamQuestion examQuestion, ExamQuestion originalExamQuestion);
}

View File

@@ -0,0 +1,54 @@
package pc.exam.pp.module.judgement.service.choice;
import org.springframework.stereotype.Service;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestion;
import pc.exam.pp.module.exam.dal.dataobject.ExamQuestionAnswer;
/**
* 判分逻辑集合
*
* @author rwb
*/
@Service
public class JudgementChoiceServiceImpl implements JudgementChoiceService
{
/**
* 选择题判分
* @param examQuestion 选择题内容(学生答题)
* @param originalExamQuestion 原始题(判断答案)
* @param score 分数
* @return 返回判分
*/
public double ProgrammingChoice(double score, ExamQuestion examQuestion, ExamQuestion originalExamQuestion) {
// 总分重置
double totalScore = 0;
String right_id = null;
String stu_right_id = null;
// 获取选择题的标准答案
// 找到对应正确题的答案ID
for (ExamQuestionAnswer examQuestionAnswer : originalExamQuestion.getAnswerList()) {
// 判断正确答案
if ("0".equals(examQuestionAnswer.getIsRight())) {
// 正确答案
right_id = examQuestionAnswer.getAnswerId();
break;
}
}
// 获取学生的做题答案,进行判断是否一致
for (ExamQuestionAnswer examQuestionAnswer : examQuestion.getAnswerList()) {
// 判断正确答案
if ("0".equals(examQuestionAnswer.getIsRight())) {
// 正确答案
stu_right_id = examQuestionAnswer.getAnswerId();
break;
}
}
// 判断
if (stu_right_id.equals(right_id)) {
totalScore += score;
}
// 该题得分返回
return totalScore;
}
}

View File

@@ -0,0 +1,262 @@
package pc.exam.pp.module.judgement.utils;
import javax.swing.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Stream;
/**
* C语言 相关工具类
*
* @author pengchen
*/
public class JudgementCUtils
{
/**
* 判断程序是否安装GCC 编译环境
* @return true or false
*/
public static boolean isGCCInstalled() {
try {
ProcessBuilder builder = new ProcessBuilder("gcc", "--version");
Process process = builder.start();
process.waitFor();
return process.exitValue() == 0;
} catch (Exception e) {
return false;
}
}
/**
* 安装GCC编译环境
* @param os 操作系统
* @return 安装话术
*/
public static String installGCC(String os) {
try {
ProcessBuilder builder;
if (os.equals("windows")) {
builder = new ProcessBuilder("cmd.exe", "/c", "choco install mingw");
} else {
builder = new ProcessBuilder("bash", "-c", "sudo apt-get install gcc -y");
}
builder.redirectErrorStream(true);
Process process = builder.start();
process.waitFor();
JOptionPane.showMessageDialog(null, "GCC installation completed for " + os);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Installation failed: " + ex.getMessage());
throw new RuntimeException("Installation failed: " + ex.getMessage());
}
return "GCC installation completed for " + os;
}
/**
* 运行C语言代码
* @param code C语言代码
* @param input 测试用例插入值(如有)
* @param standard 编译版本 C99
* @return 运行结果
*/
public static String run_code(String code, String input, String standard, String text) {
try {
boolean hasInput = code.contains("scanf") || code.contains("fgets") || code.contains("getchar");
// 写入 C 源码到文件
File file = new File("program.c");
try (FileWriter writer = new FileWriter(file)) {
writer.write(code);
}
// 编译代码
ProcessBuilder compileBuilder = new ProcessBuilder("gcc", standard, "program.c", "-o", "program.out");
compileBuilder.redirectErrorStream(true);
Process compileProcess = compileBuilder.start();
StringBuilder compileOutput = new StringBuilder();
try (BufferedReader compileReader = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()))) {
String line;
while ((line = compileReader.readLine()) != null) {
compileOutput.append(line).append("\n");
}
}
int compileResult = compileProcess.waitFor();
String outputLower = compileOutput.toString().toLowerCase();
if (outputLower.contains("error:") || !Files.exists(Paths.get("program.out"))) {
// LogFileUtils.writeLine("❌ 编译失败:");
// LogFileUtils.writeLine(compileOutput.toString());
return "编译失败,输出:\n" + compileOutput.toString();
}
// 运行程序
ProcessBuilder runBuilder = new ProcessBuilder("./program.out");
runBuilder.redirectErrorStream(true);
Process runProcess = runBuilder.start();
// 输入注入(如有)
if (hasInput && input != null) {
try (BufferedWriter inputWriter = new BufferedWriter(new OutputStreamWriter(runProcess.getOutputStream()))) {
inputWriter.write(input);
inputWriter.newLine();
inputWriter.flush();
}
}
// 使用线程池处理带超时的输出读取
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
return output.toString();
});
String output;
try {
output = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
// LogFileUtils.writeLine("⏰ 程序超时,强制终止进程!");
runProcess.destroy();
future.cancel(true);
output = "程序运行超时(超过 5 秒)";
} finally {
executor.shutdownNow();
}
// if (text != null) {
// LogFileUtils.writeLine("✅ 程序运行完成,输出:" + text);
// } else {
// LogFileUtils.writeLine("✅ 程序运行完成,输出:" + output.trim());
// }
return output;
} catch (Exception ex) {
ex.printStackTrace();
// LogFileUtils.writeLine("❌ 运行 C 代码时出错:" + ex.getMessage());
return "运行 C 代码时出错:" + ex.getMessage();
}
}
/**
* 运行C语言代码,出题测试运行
* @param code C语言代码
* @param standard 编译版本 C99
* @return 运行结果
*/
public static String run_test_code(String code, String standard) {
try {
// 写入 C 语言源码到文件
File file = new File("program.c");
try (FileWriter writer = new FileWriter(file)) {
writer.write(code);
}
// 编译 C 代码
ProcessBuilder compileBuilder = new ProcessBuilder("gcc", standard, "program.c", "-o", "program.out");
compileBuilder.redirectErrorStream(true);
Process compileProcess = compileBuilder.start();
StringBuilder compileOutput = new StringBuilder();
try (BufferedReader compileReader = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()))) {
String line;
while ((line = compileReader.readLine()) != null) {
compileOutput.append(line).append("\n");
}
}
int compileResult = compileProcess.waitFor();
// 检查编译是否成功
String outputLower = compileOutput.toString().toLowerCase();
if (outputLower.contains("error:") || !Files.exists(Paths.get("program.out"))) {
return "编译失败,输出:\n" + compileOutput.toString();
}
// 运行程序并添加超时机制
ProcessBuilder runBuilder = new ProcessBuilder("./program.out");
runBuilder.redirectErrorStream(true);
Process runProcess = runBuilder.start();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
return output.toString();
});
String output;
try {
output = future.get(5, TimeUnit.SECONDS); // 设置 5 秒超时
} catch (TimeoutException e) {
runProcess.destroy();
future.cancel(true);
output = "程序运行超时(超过 5 秒)";
} finally {
executor.shutdownNow();
}
return output;
} catch (Exception ex) {
ex.printStackTrace();
return "运行 C 代码时出错:" + ex.getMessage();
}
}
/**
* 读取文件代码
* @param filePath 文件路径
* @return 文件内容
*/
public static String readFile(String filePath, String fileName) {
// 创建一个 Path 对象,指向包含 C 语言文件的文件夹
Path folderPath = Paths.get(filePath);
// 判断路径是否存在
if (!Files.exists(folderPath)) {
// LogFileUtils.writeLine("❗ 文件夹路径不存在: " + folderPath.toString());
return null; // 或者 return null或者 throw new RuntimeException(...),看你的函数定义
}
// 使用 StringBuilder 来累积所有读取到的代码内容
StringBuilder codeBuilder = new StringBuilder();
try (Stream<Path> paths = Files.walk(folderPath)) {
paths.filter(Files::isRegularFile)
.filter(path -> path.toString().toLowerCase().endsWith(fileName))
.forEach(path -> {
// LogFileUtils.writeLine("📄 文件: " + path);
try {
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
codeBuilder.append("\n").append(line);
System.out.println(" " + line);
}
} catch (IOException e) {
// LogFileUtils.writeLine("❗ 无法读取文件: " + path);
}
});
} catch (IOException e) {
return null;
}
return codeBuilder.toString();
}
}

View File

@@ -17,6 +17,8 @@ public interface ErrorCodeConstants {
ErrorCode AUTH_MOBILE_NOT_EXISTS = new ErrorCode(1_002_000_007, "手机号不存在");
ErrorCode AUTH_REGISTER_CAPTCHA_CODE_ERROR = new ErrorCode(1_002_000_008, "验证码不正确,原因:{}");
ErrorCode AUTH_LOGIN_NICKNAME_NOT = new ErrorCode(1_002_000_009, "登录失败,账号昵称不正确");
ErrorCode AUTH_LOGIN_BAD_USERNAME_NOT = new ErrorCode(1_002_000_010, "登录失败,账号不正确");
// ========== 菜单模块 1-002-001-000 ==========
ErrorCode MENU_NAME_DUPLICATE = new ErrorCode(1_002_001_000, "已经存在该名字的菜单");
ErrorCode MENU_PARENT_NOT_EXISTS = new ErrorCode(1_002_001_001, "父菜单不存在");

View File

@@ -131,6 +131,12 @@
<version>2.4.2-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>pc.exam.gg</groupId>
<artifactId>exam-module-infra-biz</artifactId>
<version>2.4.2-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>

View File

@@ -7,6 +7,8 @@ import pc.exam.pp.framework.common.enums.UserTypeEnum;
import pc.exam.pp.framework.common.pojo.CommonResult;
import pc.exam.pp.framework.security.config.SecurityProperties;
import pc.exam.pp.framework.security.core.util.SecurityFrameworkUtils;
import pc.exam.pp.module.infra.dal.dataobject.config.ConfigDO;
import pc.exam.pp.module.infra.service.config.ConfigService;
import pc.exam.pp.module.system.controller.admin.auth.vo.*;
import pc.exam.pp.module.system.convert.auth.AuthConvert;
import pc.exam.pp.module.system.dal.dataobject.permission.MenuDO;
@@ -66,6 +68,9 @@ public class AuthController {
@Resource
private SecurityProperties securityProperties;
@Resource
private ConfigService configService;
@PostMapping("/login")
@PermitAll
@Operation(summary = "使用账号密码登录")
@@ -110,7 +115,6 @@ public class AuthController {
if (user == null) {
return success(null);
}
// 1.2 获得角色列表
Set<Long> roleIds = permissionService.getUserRoleIdListByUserId(getLoginUserId());
if (CollUtil.isEmpty(roleIds)) {
@@ -122,8 +126,19 @@ public class AuthController {
// 1.3 获得菜单列表
Set<Long> menuIds = permissionService.getRoleMenuListByRoleId(convertSet(roles, RoleDO::getId));
List<MenuDO> menuList = menuService.getMenuList(menuIds);
// 1.4 判断是否为学生,并且是否为考试模式
if (user.getUserType().equals("2")) {
// 获取考试模式数据
ConfigDO config = configService.getConfigByKey("student_login");
if (config.getValue().equals("0")) {
// 考试模式菜单返回为空
menuList = null;
} else {
menuList = menuService.filterDisableMenus(menuList);
}
} else {
menuList = menuService.filterDisableMenus(menuList);
}
// 2. 拼接结果返回
return success(AuthConvert.INSTANCE.convert(user, roles, menuList));
}

View File

@@ -32,6 +32,12 @@ public class AuthLoginReqVO extends CaptchaVerificationReqVO {
@Length(min = 4, max = 16, message = "密码长度为 4-16 位")
private String password;
@Schema(description = "用户昵称")
private String nickname;
@Schema(description = "用户类型")
private String userType;
// ========== 绑定社交登录时,需要传递如下参数 ==========
@Schema(description = "社交平台的类型,参见 SocialTypeEnum 枚举值", requiredMode = Schema.RequiredMode.REQUIRED, example = "10")
@@ -41,8 +47,7 @@ public class AuthLoginReqVO extends CaptchaVerificationReqVO {
@Schema(description = "授权码", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
private String socialCode;
@Schema(description = "用户类型")
private String userType;
@Schema(description = "state", requiredMode = Schema.RequiredMode.REQUIRED, example = "9b2ffbc1-7425-4155-9894-9d5c08541d62")
private String socialState;

View File

@@ -6,7 +6,10 @@ import pc.exam.pp.framework.common.enums.CommonStatusEnum;
import pc.exam.pp.framework.common.pojo.CommonResult;
import pc.exam.pp.framework.common.pojo.PageParam;
import pc.exam.pp.framework.common.pojo.PageResult;
import pc.exam.pp.framework.common.util.object.BeanUtils;
import pc.exam.pp.framework.excel.core.util.ExcelUtils;
import pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtListByUserReqVo;
import pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtyQueryVo;
import pc.exam.pp.module.exam.dal.dataobject.classs.ClassDO;
import pc.exam.pp.module.exam.service.classs.ClassService;
import pc.exam.pp.module.system.controller.admin.user.vo.user.*;
@@ -232,4 +235,13 @@ public class UserController {
return success(userService.importUserList(list, updateSupport));
}
@GetMapping("/getSpeciatListByUser")
@Operation(summary = "获取专业信息,判断用户类型")
public CommonResult<List<SpecialtyQueryVo>> getListByUser() {
List<SpecialtyQueryVo> list = userService.getListByUser();
return success(BeanUtils.toBean(list, SpecialtyQueryVo.class));
}
}

View File

@@ -23,6 +23,23 @@ public interface AdminAuthService {
*/
AdminUserDO authenticate(String username, String password);
/**
* 验证账号 + 昵称。如果通过,则返回用户
*
* @param username 账号
* @param nickname 昵称
* @return 用户
*/
AdminUserDO authenticateByNickName(String username, String nickname);
/**
* 验证账号。如果通过,则返回用户
*
* @param username 账号
* @return 用户
*/
AdminUserDO authenticateOnlyUsername(String username);
/**
* 账号登录
*

View File

@@ -6,6 +6,8 @@ import pc.exam.pp.framework.common.enums.UserTypeEnum;
import pc.exam.pp.framework.common.util.monitor.TracerUtils;
import pc.exam.pp.framework.common.util.servlet.ServletUtils;
import pc.exam.pp.framework.common.util.validation.ValidationUtils;
import pc.exam.pp.module.infra.dal.dataobject.config.ConfigDO;
import pc.exam.pp.module.infra.service.config.ConfigService;
import pc.exam.pp.module.system.api.logger.dto.LoginLogCreateReqDTO;
import pc.exam.pp.module.system.api.sms.SmsCodeApi;
import pc.exam.pp.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
@@ -67,7 +69,8 @@ public class AdminAuthServiceImpl implements AdminAuthService {
private CaptchaService captchaService;
@Resource
private SmsCodeApi smsCodeApi;
@Resource
private ConfigService configService;
/**
* 验证码的开关,默认为 true
*/
@@ -95,15 +98,62 @@ public class AdminAuthServiceImpl implements AdminAuthService {
}
return user;
}
@Override
public AdminUserDO authenticateOnlyUsername(String username) {
final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
// 校验账号是否存在
AdminUserDO user = userService.getUserByUsername(username);
if (user == null) {
createLoginLog(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
throw exception(AUTH_LOGIN_BAD_USERNAME_NOT);
}
// 校验是否禁用
if (CommonStatusEnum.isDisable(user.getStatus())) {
createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
throw exception(AUTH_LOGIN_USER_DISABLED);
}
return user;
}
@Override
public AdminUserDO authenticateByNickName(String username, String nickname) {
final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
// 校验账号是否存在
AdminUserDO user = userService.getUserByUsername(username);
// 校验昵称是否匹配
if (user.getNickname().equals(nickname)) {
throw exception(AUTH_LOGIN_NICKNAME_NOT);
}
// 校验是否禁用
if (CommonStatusEnum.isDisable(user.getStatus())) {
createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
throw exception(AUTH_LOGIN_USER_DISABLED);
}
return user;
}
@Override
public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
AdminUserDO user = new AdminUserDO();
// 校验验证码
validateCaptcha(reqVO);
// 判断用户类型
if (reqVO.getUserType().equals("2")) {
// 说明是学生用户,在判断学生的登录方式
ConfigDO config = configService.getConfigByKey("student_login");
String type = config.getValue();
if (type.equals("1")) {
// 考生账号+姓名登录
user = authenticateByNickName(reqVO.getUsername(), reqVO.getPassword());
} else if (type.equals("2")) {
// 考生账号+密码登录
user = authenticate(reqVO.getUsername(), reqVO.getPassword());
} else if (type.equals("3")) {
// 考生账号登录
user = authenticateOnlyUsername(reqVO.getUsername());
}
} else {
// 使用账号密码,进行登录
AdminUserDO user = authenticate(reqVO.getUsername(), reqVO.getPassword());
user = authenticate(reqVO.getUsername(), reqVO.getPassword());
}
// 如果 socialType 非空,说明需要绑定社交用户
if (reqVO.getSocialType() != null) {
socialUserService.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),

View File

@@ -3,6 +3,8 @@ package pc.exam.pp.module.system.service.user;
import cn.hutool.core.collection.CollUtil;
import pc.exam.pp.framework.common.pojo.PageResult;
import pc.exam.pp.framework.common.util.collection.CollectionUtils;
import pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtListByUserReqVo;
import pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtyQueryVo;
import pc.exam.pp.module.system.controller.admin.auth.vo.AuthRegisterReqVO;
import pc.exam.pp.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO;
import pc.exam.pp.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO;
@@ -256,5 +258,11 @@ public interface AdminUserService {
* @return 是否匹配
*/
boolean isPasswordMatch(String rawPassword, String encodedPassword);
/**
* 获取专业信息,判断用户类型
*
* @return 全部信息集合
*/
List<SpecialtyQueryVo> getListByUser();
}

View File

@@ -4,7 +4,6 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import org.bouncycastle.jcajce.provider.symmetric.TEA;
import pc.exam.pp.framework.common.enums.CommonStatusEnum;
import pc.exam.pp.framework.common.exception.ServiceException;
import pc.exam.pp.framework.common.pojo.PageResult;
@@ -12,9 +11,13 @@ import pc.exam.pp.framework.common.util.collection.CollectionUtils;
import pc.exam.pp.framework.common.util.object.BeanUtils;
import pc.exam.pp.framework.common.util.validation.ValidationUtils;
import pc.exam.pp.framework.datapermission.core.util.DataPermissionUtils;
import pc.exam.pp.framework.web.core.util.WebFrameworkUtils;
import pc.exam.pp.module.exam.controller.admin.classs.vo.ClassSaveReqVO;
import pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtListByUserReqVo;
import pc.exam.pp.module.exam.controller.admin.specialty.vo.SpecialtyQueryVo;
import pc.exam.pp.module.exam.dal.dataobject.classs.ClassDO;
import pc.exam.pp.module.exam.dal.mysql.classs.ClassMapper;
import pc.exam.pp.module.exam.dal.mysql.specialty.ExamSpecialtyMapper;
import pc.exam.pp.module.exam.service.classs.ClassService;
import pc.exam.pp.module.infra.api.config.ConfigApi;
import pc.exam.pp.module.infra.api.file.FileApi;
@@ -99,6 +102,8 @@ public class AdminUserServiceImpl implements AdminUserService {
private FileApi fileApi;
@Resource
private ConfigApi configApi;
@Resource
private ExamSpecialtyMapper examSpecialtyMapper;
@Override
@Transactional(rollbackFor = Exception.class)
@@ -731,6 +736,29 @@ public class AdminUserServiceImpl implements AdminUserService {
return passwordEncoder.matches(rawPassword, encodedPassword);
}
@Override
public List<SpecialtyQueryVo> getListByUser() {
Long userId = WebFrameworkUtils.getLoginUserId();
AdminUserDO adminUserDO = getUser(userId);
List<SpecialtyQueryVo> specialtyQueryVos = new ArrayList<>();
// 判断用户类型 管理员所有专业
if (adminUserDO.getUserType().equals("0")) {
// 查询所有专业数据
specialtyQueryVos = examSpecialtyMapper.selectExamSpecialtyAll();
} else {
// 判断专业是否为空,为空的话查询所有
if (adminUserDO.getClassIds() != null) {
// 查询所有数据
specialtyQueryVos = examSpecialtyMapper.selectExamSpecialtyAll();
} else {
// 查询部分数据
specialtyQueryVos = examSpecialtyMapper.selectExamSpecialtyByids(adminUserDO.getClassIds());
}
}
return specialtyQueryVos;
}
/**
* 对密码进行加密
*