Search in sources :

Example 11 with Judge

use of top.hcode.hoj.pojo.entity.judge.Judge in project HOJ by HimitZH.

the class JudgeServiceImpl method judge.

@Override
public void judge(Judge judge) {
    // 标志该判题过程进入编译阶段
    judge.setStatus(Constants.Judge.STATUS_COMPILING.getStatus());
    // 写入当前判题服务的名字
    judge.setJudger(name);
    judgeEntityService.updateById(judge);
    // 进行判题操作
    Problem problem = problemEntityService.getById(judge.getPid());
    Judge finalJudge = judgeContext.Judge(problem, judge);
    // 更新该次提交
    judgeEntityService.updateById(finalJudge);
    if (finalJudge.getStatus().intValue() != Constants.Judge.STATUS_SUBMITTED_FAILED.getStatus()) {
        // 更新其它表
        judgeContext.updateOtherTable(finalJudge.getSubmitId(), finalJudge.getStatus(), finalJudge.getCid(), finalJudge.getUid(), finalJudge.getPid(), finalJudge.getGid(), finalJudge.getScore(), finalJudge.getTime());
    }
}
Also used : Problem(top.hcode.hoj.pojo.entity.problem.Problem) Judge(top.hcode.hoj.pojo.entity.judge.Judge)

Example 12 with Judge

use of top.hcode.hoj.pojo.entity.judge.Judge in project HOJ by HimitZH.

the class AccountManager method getUserCalendarHeatmap.

/**
 * @param uid
 * @param username
 * @return
 * @Description 获取用户最近一年的提交热力图数据
 */
public UserCalendarHeatmapVo getUserCalendarHeatmap(String uid, String username) throws StatusFailException {
    org.apache.shiro.session.Session session = SecurityUtils.getSubject().getSession();
    UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
    if (StringUtils.isEmpty(uid) && StringUtils.isEmpty(username)) {
        if (userRolesVo != null) {
            uid = userRolesVo.getUid();
        } else {
            throw new StatusFailException("请求参数错误:uid和username不能都为空!");
        }
    }
    UserCalendarHeatmapVo userCalendarHeatmapVo = new UserCalendarHeatmapVo();
    userCalendarHeatmapVo.setEndDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
    List<Judge> lastYearUserJudgeList = userRecordEntityService.getLastYearUserJudgeList(uid, username);
    if (CollectionUtils.isEmpty(lastYearUserJudgeList)) {
        userCalendarHeatmapVo.setDataList(new ArrayList<>());
        return userCalendarHeatmapVo;
    }
    HashMap<String, Integer> tmpRecordMap = new HashMap<>();
    for (Judge judge : lastYearUserJudgeList) {
        Date submitTime = judge.getSubmitTime();
        String dateStr = DateUtil.format(submitTime, "yyyy-MM-dd");
        tmpRecordMap.merge(dateStr, 1, Integer::sum);
    }
    List<HashMap<String, Object>> dataList = new ArrayList<>();
    for (Map.Entry<String, Integer> record : tmpRecordMap.entrySet()) {
        HashMap<String, Object> tmp = new HashMap<>(2);
        tmp.put("date", record.getKey());
        tmp.put("count", record.getValue());
        dataList.add(tmp);
    }
    userCalendarHeatmapVo.setDataList(dataList);
    return userCalendarHeatmapVo;
}
Also used : StatusFailException(top.hcode.hoj.common.exception.StatusFailException) Judge(top.hcode.hoj.pojo.entity.judge.Judge)

Example 13 with Judge

use of top.hcode.hoj.pojo.entity.judge.Judge in project HOJ by HimitZH.

the class GroupContestProblemManager method deleteContestProblem.

public void deleteContestProblem(Long pid, Long cid) throws StatusNotFoundException, StatusForbiddenException, StatusFailException {
    Session session = SecurityUtils.getSubject().getSession();
    UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
    boolean isRoot = SecurityUtils.getSubject().hasRole("root");
    Contest contest = contestEntityService.getById(cid);
    if (contest == null) {
        throw new StatusNotFoundException("该比赛不存在!");
    }
    Long gid = contest.getGid();
    Group group = groupEntityService.getById(gid);
    if (group == null || group.getStatus() == 1 && !isRoot) {
        throw new StatusNotFoundException("该团队不存在或已被封禁!");
    }
    if (!userRolesVo.getUid().equals(contest.getUid()) && !isRoot && !groupValidator.isGroupRoot(userRolesVo.getUid(), gid)) {
        throw new StatusForbiddenException("对不起,您无权限操作!");
    }
    QueryWrapper<ContestProblem> contestProblemQueryWrapper = new QueryWrapper<>();
    contestProblemQueryWrapper.eq("cid", cid).eq("pid", pid);
    boolean isOk = contestProblemEntityService.remove(contestProblemQueryWrapper);
    if (isOk) {
        UpdateWrapper<Judge> judgeUpdateWrapper = new UpdateWrapper<>();
        judgeUpdateWrapper.eq("cid", cid).eq("pid", pid);
        judgeEntityService.remove(judgeUpdateWrapper);
    } else {
        throw new StatusFailException("删除失败!");
    }
}
Also used : Group(top.hcode.hoj.pojo.entity.group.Group) StatusForbiddenException(top.hcode.hoj.common.exception.StatusForbiddenException) UpdateWrapper(com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) StatusNotFoundException(top.hcode.hoj.common.exception.StatusNotFoundException) UserRolesVo(top.hcode.hoj.pojo.vo.UserRolesVo) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) Contest(top.hcode.hoj.pojo.entity.contest.Contest) ContestProblem(top.hcode.hoj.pojo.entity.contest.ContestProblem) Judge(top.hcode.hoj.pojo.entity.judge.Judge) Session(org.apache.shiro.session.Session)

Example 14 with Judge

use of top.hcode.hoj.pojo.entity.judge.Judge in project HOJ by HimitZH.

the class AdminTrainingRecordManager method syncAllUserProblemRecord.

private void syncAllUserProblemRecord(Long tid) {
    QueryWrapper<TrainingProblem> trainingProblemQueryWrapper = new QueryWrapper<>();
    trainingProblemQueryWrapper.eq("tid", tid);
    List<TrainingProblem> trainingProblemList = trainingProblemEntityService.list(trainingProblemQueryWrapper);
    if (trainingProblemList.size() == 0) {
        return;
    }
    List<Long> pidList = new ArrayList<>();
    HashMap<Long, Long> pidMapTPid = new HashMap<>();
    for (TrainingProblem trainingProblem : trainingProblemList) {
        pidList.add(trainingProblem.getPid());
        pidMapTPid.put(trainingProblem.getPid(), trainingProblem.getId());
    }
    List<String> uidList = trainingRegisterEntityService.getAlreadyRegisterUidList(tid);
    if (uidList.size() == 0) {
        return;
    }
    QueryWrapper<Judge> judgeQueryWrapper = new QueryWrapper<>();
    judgeQueryWrapper.in("pid", pidList).eq("cid", 0).eq("status", // 只同步ac的提交
    Constants.Judge.STATUS_ACCEPTED.getStatus()).in("uid", uidList);
    List<Judge> judgeList = judgeEntityService.list(judgeQueryWrapper);
    saveBatchNewRecordByJudgeList(judgeList, tid, null, pidMapTPid);
}
Also used : QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TrainingProblem(top.hcode.hoj.pojo.entity.training.TrainingProblem) Judge(top.hcode.hoj.pojo.entity.judge.Judge)

Example 15 with Judge

use of top.hcode.hoj.pojo.entity.judge.Judge in project HOJ by HimitZH.

the class ContestFileManager method downloadContestACSubmission.

public void downloadContestACSubmission(Long cid, Boolean excludeAdmin, String splitType, HttpServletResponse response) throws StatusForbiddenException, StatusFailException {
    Contest contest = contestEntityService.getById(cid);
    if (contest == null) {
        throw new StatusFailException("错误:该比赛不存在!");
    }
    // 获取当前登录的用户
    Session session = SecurityUtils.getSubject().getSession();
    UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
    boolean isRoot = SecurityUtils.getSubject().hasRole("root");
    // 除非是root 其它管理员只能下载自己的比赛ac记录
    Long gid = contest.getGid();
    if (!isRoot && !contest.getUid().equals(userRolesVo.getUid()) && !(contest.getIsGroup() && groupValidator.isGroupRoot(userRolesVo.getUid(), gid))) {
        throw new StatusForbiddenException("错误:您并非该比赛的管理员,无权下载AC记录!");
    }
    boolean isACM = contest.getType().intValue() == Constants.Contest.TYPE_ACM.getCode();
    QueryWrapper<ContestProblem> contestProblemQueryWrapper = new QueryWrapper<>();
    contestProblemQueryWrapper.eq("cid", contest.getId());
    List<ContestProblem> contestProblemList = contestProblemEntityService.list(contestProblemQueryWrapper);
    List<String> superAdminUidList = userInfoEntityService.getSuperAdminUidList();
    QueryWrapper<Judge> judgeQueryWrapper = new QueryWrapper<>();
    judgeQueryWrapper.eq("cid", cid).eq(isACM, "status", Constants.Judge.STATUS_ACCEPTED.getStatus()).isNotNull(!isACM, // OI模式取得分不为null的
    "score").between("submit_time", contest.getStartTime(), contest.getEndTime()).ne(excludeAdmin, "uid", // 排除比赛创建者和root
    contest.getUid()).notIn(excludeAdmin && superAdminUidList.size() > 0, "uid", superAdminUidList).orderByDesc("submit_time");
    List<Judge> judgeList = judgeEntityService.list(judgeQueryWrapper);
    // 打包文件的临时路径 -> username为文件夹名字
    String tmpFilesDir = Constants.File.CONTEST_AC_SUBMISSION_TMP_FOLDER.getPath() + File.separator + IdUtil.fastSimpleUUID();
    FileUtil.mkdir(tmpFilesDir);
    HashMap<String, Boolean> recordMap = new HashMap<>();
    if ("user".equals(splitType)) {
        /**
         * 以用户来分割提交的代码
         */
        List<String> usernameList = judgeList.stream().filter(// 根据用户名过滤唯一
        distinctByKey(Judge::getUsername)).map(Judge::getUsername).collect(// 映射出用户名列表
        Collectors.toList());
        HashMap<Long, String> cpIdMap = new HashMap<>();
        for (ContestProblem contestProblem : contestProblemList) {
            cpIdMap.put(contestProblem.getId(), contestProblem.getDisplayId());
        }
        for (String username : usernameList) {
            // 对于每个用户生成对应的文件夹
            String userDir = tmpFilesDir + File.separator + username;
            FileUtil.mkdir(userDir);
            // 如果是ACM模式,则所有提交代码都要生成,如果同一题多次提交AC,加上提交时间秒后缀 ---> A_(666666).c
            // 如果是OI模式就生成最近一次提交即可,且带上分数 ---> A_(666666)_100.c
            List<Judge> userSubmissionList = judgeList.stream().filter(// 过滤出对应用户的提交
            judge -> judge.getUsername().equals(username)).sorted(// 根据提交时间进行降序
            Comparator.comparing(Judge::getSubmitTime).reversed()).collect(Collectors.toList());
            for (Judge judge : userSubmissionList) {
                String filePath = userDir + File.separator + cpIdMap.getOrDefault(judge.getCpid(), "null");
                // OI模式只取最后一次提交
                if (!isACM) {
                    String key = judge.getUsername() + "_" + judge.getPid();
                    if (!recordMap.containsKey(key)) {
                        filePath += "_" + judge.getScore() + "_(" + threadLocalTime.get().format(judge.getSubmitTime()) + ")." + languageToFileSuffix(judge.getLanguage().toLowerCase());
                        FileWriter fileWriter = new FileWriter(filePath);
                        fileWriter.write(judge.getCode());
                        recordMap.put(key, true);
                    }
                } else {
                    filePath += "_(" + threadLocalTime.get().format(judge.getSubmitTime()) + ")." + languageToFileSuffix(judge.getLanguage().toLowerCase());
                    FileWriter fileWriter = new FileWriter(filePath);
                    fileWriter.write(judge.getCode());
                }
            }
        }
    } else if ("problem".equals(splitType)) {
        for (ContestProblem contestProblem : contestProblemList) {
            // 对于每题目生成对应的文件夹
            String problemDir = tmpFilesDir + File.separator + contestProblem.getDisplayId();
            FileUtil.mkdir(problemDir);
            // 如果是ACM模式,则所有提交代码都要生成,如果同一题多次提交AC,加上提交时间秒后缀 ---> username_(666666).c
            // 如果是OI模式就生成最近一次提交即可,且带上分数 ---> username_(666666)_100.c
            List<Judge> problemSubmissionList = judgeList.stream().filter(// 过滤出对应题目的提交
            judge -> judge.getPid().equals(contestProblem.getPid())).sorted(// 根据提交时间进行降序
            Comparator.comparing(Judge::getSubmitTime).reversed()).collect(Collectors.toList());
            for (Judge judge : problemSubmissionList) {
                String filePath = problemDir + File.separator + judge.getUsername();
                if (!isACM) {
                    String key = judge.getUsername() + "_" + contestProblem.getDisplayId();
                    // OI模式只取最后一次提交
                    if (!recordMap.containsKey(key)) {
                        filePath += "_" + judge.getScore() + "_(" + threadLocalTime.get().format(judge.getSubmitTime()) + ")." + languageToFileSuffix(judge.getLanguage().toLowerCase());
                        FileWriter fileWriter = new FileWriter(filePath);
                        fileWriter.write(judge.getCode());
                        recordMap.put(key, true);
                    }
                } else {
                    filePath += "_(" + threadLocalTime.get().format(judge.getSubmitTime()) + ")." + languageToFileSuffix(judge.getLanguage().toLowerCase());
                    FileWriter fileWriter = new FileWriter(filePath);
                    fileWriter.write(judge.getCode());
                }
            }
        }
    }
    String zipFileName = "contest_" + contest.getId() + "_" + System.currentTimeMillis() + ".zip";
    String zipPath = Constants.File.CONTEST_AC_SUBMISSION_TMP_FOLDER.getPath() + File.separator + zipFileName;
    ZipUtil.zip(tmpFilesDir, zipPath);
    // 将zip变成io流返回给前端
    FileReader zipFileReader = new FileReader(zipPath);
    // 放到缓冲流里面
    BufferedInputStream bins = new BufferedInputStream(zipFileReader.getInputStream());
    // 获取文件输出IO流
    OutputStream outs = null;
    BufferedOutputStream bouts = null;
    try {
        outs = response.getOutputStream();
        bouts = new BufferedOutputStream(outs);
        response.setContentType("application/x-download");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
        int bytesRead = 0;
        byte[] buffer = new byte[1024 * 10];
        // 开始向网络传输文件流
        while ((bytesRead = bins.read(buffer, 0, 1024 * 10)) != -1) {
            bouts.write(buffer, 0, bytesRead);
        }
        // 刷新缓存
        bouts.flush();
    } catch (IOException e) {
        log.error("下载比赛AC提交代码的压缩文件异常------------>", e);
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Map<String, Object> map = new HashMap<>();
        map.put("status", ResultStatus.SYSTEM_ERROR);
        map.put("msg", "下载文件失败,请重新尝试!");
        map.put("data", null);
        try {
            response.getWriter().println(JSONUtil.toJsonStr(map));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    } finally {
        try {
            bins.close();
            if (outs != null) {
                outs.close();
            }
            if (bouts != null) {
                bouts.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    FileUtil.del(tmpFilesDir);
    FileUtil.del(zipPath);
}
Also used : java.util(java.util) ACMContestRankVo(top.hcode.hoj.pojo.vo.ACMContestRankVo) UserRolesVo(top.hcode.hoj.pojo.vo.UserRolesVo) IdUtil(cn.hutool.core.util.IdUtil) Autowired(org.springframework.beans.factory.annotation.Autowired) SimpleDateFormat(java.text.SimpleDateFormat) EasyExcel(com.alibaba.excel.EasyExcel) ZipUtil(cn.hutool.core.util.ZipUtil) Session(org.apache.shiro.session.Session) Function(java.util.function.Function) ContestValidator(top.hcode.hoj.validator.ContestValidator) JSONUtil(cn.hutool.json.JSONUtil) Judge(top.hcode.hoj.pojo.entity.judge.Judge) GroupValidator(top.hcode.hoj.validator.GroupValidator) ContestEntityService(top.hcode.hoj.dao.contest.ContestEntityService) ContestCalculateRankManager(top.hcode.hoj.manager.oj.ContestCalculateRankManager) ContestProblemEntityService(top.hcode.hoj.dao.contest.ContestProblemEntityService) ContestPrint(top.hcode.hoj.pojo.entity.contest.ContestPrint) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) JudgeEntityService(top.hcode.hoj.dao.judge.JudgeEntityService) FileReader(cn.hutool.core.io.file.FileReader) Predicate(java.util.function.Predicate) Contest(top.hcode.hoj.pojo.entity.contest.Contest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) FileEntityService(top.hcode.hoj.dao.common.FileEntityService) Collectors(java.util.stream.Collectors) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) ResultStatus(top.hcode.hoj.common.result.ResultStatus) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) URLEncoder(java.net.URLEncoder) UserInfoEntityService(top.hcode.hoj.dao.user.UserInfoEntityService) java.io(java.io) StatusForbiddenException(top.hcode.hoj.common.exception.StatusForbiddenException) ContestProblem(top.hcode.hoj.pojo.entity.contest.ContestProblem) OIContestRankVo(top.hcode.hoj.pojo.vo.OIContestRankVo) ContestPrintEntityService(top.hcode.hoj.dao.contest.ContestPrintEntityService) FileWriter(cn.hutool.core.io.file.FileWriter) FileUtil(cn.hutool.core.io.FileUtil) Constants(top.hcode.hoj.utils.Constants) SecurityUtils(org.apache.shiro.SecurityUtils) StatusForbiddenException(top.hcode.hoj.common.exception.StatusForbiddenException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) FileWriter(cn.hutool.core.io.file.FileWriter) UserRolesVo(top.hcode.hoj.pojo.vo.UserRolesVo) FileReader(cn.hutool.core.io.file.FileReader) Contest(top.hcode.hoj.pojo.entity.contest.Contest) ContestProblem(top.hcode.hoj.pojo.entity.contest.ContestProblem) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) ContestPrint(top.hcode.hoj.pojo.entity.contest.ContestPrint) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Judge(top.hcode.hoj.pojo.entity.judge.Judge) Session(org.apache.shiro.session.Session)

Aggregations

Judge (top.hcode.hoj.pojo.entity.judge.Judge)50 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)29 UpdateWrapper (com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper)21 Transactional (org.springframework.transaction.annotation.Transactional)18 Problem (top.hcode.hoj.pojo.entity.problem.Problem)18 UserRolesVo (top.hcode.hoj.pojo.vo.UserRolesVo)14 Contest (top.hcode.hoj.pojo.entity.contest.Contest)13 Session (org.apache.shiro.session.Session)11 HttpSession (javax.servlet.http.HttpSession)10 ContestRecord (top.hcode.hoj.pojo.entity.contest.ContestRecord)10 JudgeCase (top.hcode.hoj.pojo.entity.judge.JudgeCase)10 RequiresAuthentication (org.apache.shiro.authz.annotation.RequiresAuthentication)8 UserAcproblem (top.hcode.hoj.pojo.entity.user.UserAcproblem)8 StatusFailException (top.hcode.hoj.common.exception.StatusFailException)7 java.util (java.util)6 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 SecurityUtils (org.apache.shiro.SecurityUtils)6 Autowired (org.springframework.beans.factory.annotation.Autowired)6 Constants (top.hcode.hoj.utils.Constants)6 JSONObject (cn.hutool.json.JSONObject)4