Search in sources :

Example 76 with UpdateWrapper

use of com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper in project HOJ by HimitZH.

the class RemoteJudgeGetResult method process.

public void process(RemoteJudgeStrategy remoteJudgeStrategy) {
    RemoteJudgeDTO remoteJudgeDTO = remoteJudgeStrategy.getRemoteJudgeDTO();
    String key = UUID.randomUUID().toString() + remoteJudgeDTO.getSubmitId();
    AtomicInteger count = new AtomicInteger(0);
    Runnable getResultTask = new Runnable() {

        @Override
        public void run() {
            if (count.get() >= 60) {
                // 超过60次失败则判为提交失败
                // 更新此次提交状态为提交失败!
                UpdateWrapper<Judge> judgeUpdateWrapper = new UpdateWrapper<>();
                judgeUpdateWrapper.set("status", Constants.Judge.STATUS_SUBMITTED_FAILED.getStatus()).set("error_message", "Waiting for remote judge result exceeds the maximum number of times, please try submitting again!").eq("submit_id", remoteJudgeDTO.getJudgeId());
                judgeEntityService.update(judgeUpdateWrapper);
                log.error("[{}] Get Result Failed!", remoteJudgeDTO.getOj());
                changeRemoteJudgeLock(remoteJudgeDTO.getOj(), remoteJudgeDTO.getUsername(), remoteJudgeDTO.getServerIp(), remoteJudgeDTO.getServerPort(), remoteJudgeDTO.getSubmitId());
                Future future = futureTaskMap.get(key);
                if (future != null) {
                    boolean isCanceled = future.cancel(true);
                    if (isCanceled) {
                        futureTaskMap.remove(key);
                    }
                }
                return;
            }
            count.getAndIncrement();
            RemoteJudgeRes remoteJudgeRes;
            try {
                remoteJudgeRes = remoteJudgeStrategy.result();
            } catch (Exception e) {
                if (count.get() == 60) {
                    log.error("The Error of getting the `remote judge` result:", e);
                }
                return;
            }
            // 保留各个测试点的结果数据
            if (!CollectionUtils.isEmpty(remoteJudgeRes.getJudgeCaseList())) {
                judgeCaseEntityService.saveBatch(remoteJudgeRes.getJudgeCaseList());
            }
            Integer status = remoteJudgeRes.getStatus();
            if (status.intValue() != Constants.Judge.STATUS_PENDING.getStatus() && status.intValue() != Constants.Judge.STATUS_JUDGING.getStatus() && status.intValue() != Constants.Judge.STATUS_COMPILING.getStatus()) {
                log.info("[{}] Get Result Successfully! Status:[{}]", remoteJudgeDTO.getOj(), status);
                changeRemoteJudgeLock(remoteJudgeDTO.getOj(), remoteJudgeDTO.getUsername(), remoteJudgeDTO.getServerIp(), remoteJudgeDTO.getServerPort(), remoteJudgeDTO.getSubmitId());
                Integer time = remoteJudgeRes.getTime();
                Integer memory = remoteJudgeRes.getMemory();
                String errorInfo = remoteJudgeRes.getErrorInfo();
                Judge judge = new Judge();
                judge.setSubmitId(remoteJudgeDTO.getJudgeId()).setStatus(status).setTime(time).setMemory(memory).setJudger(name);
                if (status.intValue() == Constants.Judge.STATUS_COMPILE_ERROR.getStatus()) {
                    judge.setErrorMessage(errorInfo);
                } else if (status.intValue() == Constants.Judge.STATUS_SYSTEM_ERROR.getStatus()) {
                    judge.setErrorMessage("There is something wrong with the " + remoteJudgeDTO.getOj() + ", please try again later");
                }
                // 如果是比赛题目,需要特别适配OI比赛的得分 除AC给100 其它结果给0分
                if (remoteJudgeDTO.getCid() != 0) {
                    int score = 0;
                    if (judge.getStatus().intValue() == Constants.Judge.STATUS_ACCEPTED.getStatus()) {
                        score = 100;
                    }
                    judge.setScore(score);
                    // 写回数据库
                    judgeEntityService.updateById(judge);
                    // 同步其它表
                    judgeContext.updateOtherTable(remoteJudgeDTO.getJudgeId(), status, remoteJudgeDTO.getCid(), remoteJudgeDTO.getUid(), remoteJudgeDTO.getPid(), remoteJudgeDTO.getGid(), score, judge.getTime());
                } else {
                    judgeEntityService.updateById(judge);
                    // 同步其它表
                    judgeContext.updateOtherTable(remoteJudgeDTO.getJudgeId(), status, remoteJudgeDTO.getCid(), remoteJudgeDTO.getUid(), remoteJudgeDTO.getPid(), remoteJudgeDTO.getGid(), null, null);
                }
                Future future = futureTaskMap.get(key);
                if (future != null) {
                    future.cancel(true);
                    futureTaskMap.remove(key);
                }
            } else {
                Judge judge = new Judge();
                judge.setSubmitId(remoteJudgeDTO.getJudgeId()).setStatus(status).setJudger(name);
                // 写回数据库
                judgeEntityService.updateById(judge);
            }
        }
    };
    ScheduledFuture<?> beeperHandle = scheduler.scheduleWithFixedDelay(getResultTask, 0, 2500, TimeUnit.MILLISECONDS);
    futureTaskMap.put(key, beeperHandle);
}
Also used : UpdateWrapper(com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper) RemoteJudgeRes(top.hcode.hoj.remoteJudge.entity.RemoteJudgeRes) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RemoteJudgeDTO(top.hcode.hoj.remoteJudge.entity.RemoteJudgeDTO) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Judge(top.hcode.hoj.pojo.entity.judge.Judge)

Example 77 with UpdateWrapper

use of com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper in project HOJ by HimitZH.

the class AdminTrainingManager method updateTraining.

@Transactional(rollbackFor = Exception.class)
public void updateTraining(TrainingDto trainingDto) throws StatusForbiddenException, StatusFailException {
    // 获取当前登录的用户
    Session session = SecurityUtils.getSubject().getSession();
    UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
    // 是否为超级管理员
    boolean isRoot = SecurityUtils.getSubject().hasRole("root");
    // 只有超级管理员和训练拥有者才能操作
    if (!isRoot && !userRolesVo.getUsername().equals(trainingDto.getTraining().getAuthor())) {
        throw new StatusForbiddenException("对不起,你无权限操作!");
    }
    Training training = trainingDto.getTraining();
    Training oldTraining = trainingEntityService.getById(training.getId());
    trainingEntityService.updateById(training);
    // 私有训练 修改密码 需要清空之前注册训练的记录
    if (training.getAuth().equals(Constants.Training.AUTH_PRIVATE.getValue())) {
        if (!Objects.equals(training.getPrivatePwd(), oldTraining.getPrivatePwd())) {
            UpdateWrapper<TrainingRegister> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("tid", training.getId());
            trainingRegisterEntityService.remove(updateWrapper);
        }
    }
    TrainingCategory trainingCategory = trainingDto.getTrainingCategory();
    if (trainingCategory.getId() == null) {
        try {
            trainingCategoryEntityService.save(trainingCategory);
        } catch (Exception ignored) {
            QueryWrapper<TrainingCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", trainingCategory.getName());
            trainingCategory = trainingCategoryEntityService.getOne(queryWrapper, false);
        }
    }
    MappingTrainingCategory mappingTrainingCategory = mappingTrainingCategoryEntityService.getOne(new QueryWrapper<MappingTrainingCategory>().eq("tid", training.getId()), false);
    if (mappingTrainingCategory == null) {
        mappingTrainingCategoryEntityService.save(new MappingTrainingCategory().setTid(training.getId()).setCid(trainingCategory.getId()));
        adminTrainingRecordManager.checkSyncRecord(trainingDto.getTraining());
    } else {
        if (!mappingTrainingCategory.getCid().equals(trainingCategory.getId())) {
            UpdateWrapper<MappingTrainingCategory> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("tid", training.getId()).set("cid", trainingCategory.getId());
            boolean isOk = mappingTrainingCategoryEntityService.update(null, updateWrapper);
            if (isOk) {
                adminTrainingRecordManager.checkSyncRecord(trainingDto.getTraining());
            } else {
                throw new StatusFailException("修改失败");
            }
        }
    }
}
Also used : StatusForbiddenException(top.hcode.hoj.common.exception.StatusForbiddenException) UpdateWrapper(com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) StatusForbiddenException(top.hcode.hoj.common.exception.StatusForbiddenException) MappingTrainingCategory(top.hcode.hoj.pojo.entity.training.MappingTrainingCategory) Training(top.hcode.hoj.pojo.entity.training.Training) TrainingRegister(top.hcode.hoj.pojo.entity.training.TrainingRegister) UserRolesVo(top.hcode.hoj.pojo.vo.UserRolesVo) TrainingCategory(top.hcode.hoj.pojo.entity.training.TrainingCategory) MappingTrainingCategory(top.hcode.hoj.pojo.entity.training.MappingTrainingCategory) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) Session(org.apache.shiro.session.Session) Transactional(org.springframework.transaction.annotation.Transactional)

Example 78 with UpdateWrapper

use of com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper in project HOJ by HimitZH.

the class AdminTrainingProblemManager method addProblemFromPublic.

public void addProblemFromPublic(TrainingProblemDto trainingProblemDto) throws StatusFailException {
    Long pid = trainingProblemDto.getPid();
    Long tid = trainingProblemDto.getTid();
    String displayId = trainingProblemDto.getDisplayId();
    QueryWrapper<TrainingProblem> trainingProblemQueryWrapper = new QueryWrapper<>();
    trainingProblemQueryWrapper.eq("tid", tid).and(wrapper -> wrapper.eq("pid", pid).or().eq("display_id", displayId));
    TrainingProblem trainingProblem = trainingProblemEntityService.getOne(trainingProblemQueryWrapper, false);
    if (trainingProblem != null) {
        throw new StatusFailException("添加失败,该题目已添加或者题目的训练展示ID已存在!");
    }
    TrainingProblem newTProblem = new TrainingProblem();
    boolean isOk = trainingProblemEntityService.saveOrUpdate(newTProblem.setTid(tid).setPid(pid).setDisplayId(displayId));
    if (isOk) {
        // 添加成功
        // 更新训练最近更新时间
        UpdateWrapper<Training> trainingUpdateWrapper = new UpdateWrapper<>();
        trainingUpdateWrapper.set("gmt_modified", new Date()).eq("id", tid);
        trainingEntityService.update(trainingUpdateWrapper);
        // 异步地同步用户对该题目的提交数据
        adminTrainingRecordManager.syncAlreadyRegisterUserRecord(tid, pid, newTProblem.getId());
    } else {
        throw new StatusFailException("添加失败!");
    }
}
Also used : Training(top.hcode.hoj.pojo.entity.training.Training) UpdateWrapper(com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) TrainingProblem(top.hcode.hoj.pojo.entity.training.TrainingProblem) StatusFailException(top.hcode.hoj.common.exception.StatusFailException)

Example 79 with UpdateWrapper

use of com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper in project HOJ by HimitZH.

the class AdminUserManager method editUser.

public void editUser(AdminEditUserDto adminEditUserDto) throws StatusFailException {
    String username = adminEditUserDto.getUsername();
    String uid = adminEditUserDto.getUid();
    String realname = adminEditUserDto.getRealname();
    String email = adminEditUserDto.getEmail();
    String password = adminEditUserDto.getPassword();
    int type = adminEditUserDto.getType();
    int status = adminEditUserDto.getStatus();
    boolean setNewPwd = adminEditUserDto.getSetNewPwd();
    String titleName = adminEditUserDto.getTitleName();
    String titleColor = adminEditUserDto.getTitleColor();
    if (!StringUtils.isEmpty(realname) && realname.length() > 50) {
        throw new StatusFailException("真实姓名的长度不能超过50位");
    }
    if (!StringUtils.isEmpty(titleName) && titleName.length() > 20) {
        throw new StatusFailException("头衔的长度建议不要超过20位");
    }
    if (!StringUtils.isEmpty(password) && (password.length() < 6 || password.length() > 20)) {
        throw new StatusFailException("密码长度建议为6~20位!");
    }
    if (username.length() > 20) {
        throw new StatusFailException("用户名长度建议不能超过20位!");
    }
    UpdateWrapper<UserInfo> userInfoUpdateWrapper = new UpdateWrapper<>();
    userInfoUpdateWrapper.eq("uuid", uid).set("username", username).set("realname", realname).set("email", email).set(setNewPwd, "password", SecureUtil.md5(password)).set("title_name", titleName).set("title_color", titleColor).set("status", status);
    boolean updateUserInfo = userInfoEntityService.update(userInfoUpdateWrapper);
    QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
    userRoleQueryWrapper.eq("uid", uid);
    UserRole userRole = userRoleEntityService.getOne(userRoleQueryWrapper, false);
    boolean changeUserRole = false;
    int oldType = userRole.getRoleId().intValue();
    if (userRole.getRoleId().intValue() != type) {
        userRole.setRoleId((long) type);
        changeUserRole = userRoleEntityService.updateById(userRole);
        if (type == 1000 || oldType == 1000) {
            // 新增或者去除超级管理员需要删除缓存
            String cacheKey = Constants.Account.SUPER_ADMIN_UID_LIST_CACHE.getCode();
            redisUtils.del(cacheKey);
        }
    }
    if (updateUserInfo && setNewPwd) {
        // 需要重新登录
        userRoleEntityService.deleteCache(uid, true);
    } else if (changeUserRole) {
        // 需要重新授权
        userRoleEntityService.deleteCache(uid, false);
    }
    if (changeUserRole) {
        // 获取当前登录的用户
        Session session = SecurityUtils.getSubject().getSession();
        UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
        String title = "权限变更通知(Authority Change Notice)";
        String content = userRoleEntityService.getAuthChangeContent(oldType, type);
        adminNoticeManager.addSingleNoticeToUser(userRolesVo.getUid(), uid, title, content, "Sys");
    }
}
Also used : UpdateWrapper(com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) UserRole(top.hcode.hoj.pojo.entity.user.UserRole) UserRolesVo(top.hcode.hoj.pojo.vo.UserRolesVo) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) UserInfo(top.hcode.hoj.pojo.entity.user.UserInfo) Session(org.apache.shiro.session.Session)

Example 80 with UpdateWrapper

use of com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper in project HOJ by HimitZH.

the class ImageManager method uploadGroupAvatar.

@Transactional(rollbackFor = Exception.class)
public Group uploadGroupAvatar(MultipartFile image, Long gid) throws StatusFailException, StatusSystemErrorException, StatusForbiddenException {
    Session session = SecurityUtils.getSubject().getSession();
    UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
    boolean isRoot = SecurityUtils.getSubject().hasRole("root");
    if (!isRoot && !groupValidator.isGroupRoot(userRolesVo.getUid(), gid)) {
        throw new StatusForbiddenException("对不起,您无权限操作!");
    }
    if (image == null) {
        throw new StatusFailException("上传的头像图片文件不能为空!");
    }
    if (image.getSize() > 1024 * 1024 * 2) {
        throw new StatusFailException("上传的头像图片文件大小不能大于2M!");
    }
    String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf(".") + 1);
    if (!"jpg,jpeg,gif,png,webp".toUpperCase().contains(suffix.toUpperCase())) {
        throw new StatusFailException("请选择jpg,jpeg,gif,png,webp格式的头像图片!");
    }
    FileUtil.mkdir(Constants.File.GROUP_AVATAR_FOLDER.getPath());
    String filename = IdUtil.simpleUUID() + "." + suffix;
    try {
        image.transferTo(FileUtil.file(Constants.File.GROUP_AVATAR_FOLDER.getPath() + File.separator + filename));
    } catch (Exception e) {
        log.error("头像文件上传异常-------------->", e);
        throw new StatusSystemErrorException("服务器异常:头像上传失败!");
    }
    fileEntityService.updateFileToDeleteByGidAndType(gid, "avatar");
    UpdateWrapper<Group> GroupUpdateWrapper = new UpdateWrapper<>();
    GroupUpdateWrapper.set("avatar", Constants.File.IMG_API.getPath() + filename).eq("id", gid);
    groupEntityService.update(GroupUpdateWrapper);
    top.hcode.hoj.pojo.entity.common.File imgFile = new top.hcode.hoj.pojo.entity.common.File();
    imgFile.setName(filename).setFolderPath(Constants.File.GROUP_AVATAR_FOLDER.getPath()).setFilePath(Constants.File.GROUP_AVATAR_FOLDER.getPath() + File.separator + filename).setSuffix(suffix).setType("avatar").setGid(gid);
    fileEntityService.saveOrUpdate(imgFile);
    Group group = groupEntityService.getById(gid);
    return group;
}
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) StatusSystemErrorException(top.hcode.hoj.common.exception.StatusSystemErrorException) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) StatusForbiddenException(top.hcode.hoj.common.exception.StatusForbiddenException) UserRolesVo(top.hcode.hoj.pojo.vo.UserRolesVo) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) StatusSystemErrorException(top.hcode.hoj.common.exception.StatusSystemErrorException) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) Session(org.apache.shiro.session.Session) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

UpdateWrapper (com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper)97 Transactional (org.springframework.transaction.annotation.Transactional)41 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)40 UserRolesVo (top.hcode.hoj.pojo.vo.UserRolesVo)34 StatusFailException (top.hcode.hoj.common.exception.StatusFailException)28 Session (org.apache.shiro.session.Session)24 StatusForbiddenException (top.hcode.hoj.common.exception.StatusForbiddenException)21 Judge (top.hcode.hoj.pojo.entity.judge.Judge)17 LambdaUpdateWrapper (com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper)16 HttpSession (javax.servlet.http.HttpSession)14 Problem (top.hcode.hoj.pojo.entity.problem.Problem)14 RequiresAuthentication (org.apache.shiro.authz.annotation.RequiresAuthentication)13 StatusNotFoundException (top.hcode.hoj.common.exception.StatusNotFoundException)11 Group (top.hcode.hoj.pojo.entity.group.Group)11 Date (java.util.Date)10 Discussion (top.hcode.hoj.pojo.entity.discussion.Discussion)10 Contest (top.hcode.hoj.pojo.entity.contest.Contest)8 User (com.baomidou.mybatisplus.samples.wrapper.entity.User)5 Result (org.jeecg.common.api.vo.Result)5 LoginUser (org.jeecg.common.system.vo.LoginUser)5