Search in sources :

Example 1 with QDOJProblemDto

use of top.hcode.hoj.pojo.dto.QDOJProblemDto in project HOJ by HimitZH.

the class ImportQDUOJController method QDOJProblemToProblemVo.

private QDOJProblemDto QDOJProblemToProblemVo(JSONObject problemJson) {
    QDOJProblemDto qdojProblemDto = new QDOJProblemDto();
    List<String> tags = (List<String>) problemJson.get("tags");
    qdojProblemDto.setTags(tags.stream().map(UnicodeUtil::toString).collect(Collectors.toList()));
    qdojProblemDto.setLanguages(Arrays.asList("C", "C With O2", "C++", "C++ With O2", "Java", "Python3", "Python2", "Golang", "C#"));
    Object spj = problemJson.getObj("spj");
    boolean isSpj = !JSONUtil.isNull(spj);
    qdojProblemDto.setIsSpj(isSpj);
    Problem problem = new Problem();
    if (isSpj) {
        JSONObject spjJson = JSONUtil.parseObj(spj);
        problem.setSpjCode(spjJson.getStr("code")).setSpjLanguage(spjJson.getStr("language"));
    }
    problem.setAuth(1).setIsUploadCase(true).setSource(problemJson.getStr("source", null)).setDifficulty(1).setProblemId(problemJson.getStr("display_id")).setIsRemoveEndBlank(true).setOpenCaseResult(true).setCodeShare(false).setType(problemJson.getStr("rule_type").equals("ACM") ? 0 : 1).setTitle(problemJson.getStr("title")).setDescription(UnicodeUtil.toString(problemJson.getJSONObject("description").getStr("value"))).setInput(UnicodeUtil.toString(problemJson.getJSONObject("input_description").getStr("value"))).setOutput(UnicodeUtil.toString(problemJson.getJSONObject("output_description").getStr("value"))).setHint(UnicodeUtil.toString(problemJson.getJSONObject("hint").getStr("value"))).setTimeLimit(problemJson.getInt("time_limit")).setMemoryLimit(problemJson.getInt("memory_limit"));
    JSONArray samples = problemJson.getJSONArray("samples");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < samples.size(); i++) {
        JSONObject sample = (JSONObject) samples.get(i);
        String input = sample.getStr("input");
        String output = sample.getStr("output");
        sb.append("<input>").append(input).append("</input>");
        sb.append("<output>").append(output).append("</output>");
    }
    problem.setExamples(sb.toString());
    int sumScore = 0;
    JSONArray testcaseList = problemJson.getJSONArray("test_case_score");
    List<ProblemCase> problemSamples = new LinkedList<>();
    for (int i = 0; i < testcaseList.size(); i++) {
        JSONObject testcase = (JSONObject) testcaseList.get(i);
        String input = testcase.getStr("input_name");
        String output = testcase.getStr("output_name");
        Integer score = testcase.getInt("score", null);
        problemSamples.add(new ProblemCase().setInput(input).setOutput(output).setScore(score));
        if (score != null) {
            sumScore += score;
        }
    }
    problem.setIsRemote(false);
    problem.setIoScore(sumScore);
    qdojProblemDto.setSamples(problemSamples);
    qdojProblemDto.setProblem(problem);
    return qdojProblemDto;
}
Also used : JSONArray(cn.hutool.json.JSONArray) QDOJProblemDto(top.hcode.hoj.pojo.dto.QDOJProblemDto) ProblemCase(top.hcode.hoj.pojo.entity.problem.ProblemCase) UnicodeUtil(cn.hutool.core.text.UnicodeUtil) LinkedList(java.util.LinkedList) JSONObject(cn.hutool.json.JSONObject) LinkedList(java.util.LinkedList) List(java.util.List) JSONObject(cn.hutool.json.JSONObject) Problem(top.hcode.hoj.pojo.entity.problem.Problem)

Example 2 with QDOJProblemDto

use of top.hcode.hoj.pojo.dto.QDOJProblemDto in project HOJ by HimitZH.

the class ImportQDUOJController method importQDOJProblem.

/**
 * @param file
 * @MethodName importQDOJProblem
 * @Description zip文件导入题目 仅超级管理员可操作
 * @Return
 * @Since 2021/5/27
 */
@RequiresRoles("root")
@RequiresAuthentication
@ResponseBody
@Transactional(rollbackFor = Exception.class)
@PostMapping("/import-qdoj-problem")
public CommonResult importQDOJProblem(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
    if (!"zip".toUpperCase().contains(suffix.toUpperCase())) {
        return CommonResult.errorResponse("请上传zip格式的题目文件压缩包!");
    }
    String fileDirId = IdUtil.simpleUUID();
    String fileDir = Constants.File.TESTCASE_TMP_FOLDER.getPath() + File.separator + fileDirId;
    String filePath = fileDir + File.separator + file.getOriginalFilename();
    // 文件夹不存在就新建
    FileUtil.mkdir(fileDir);
    try {
        file.transferTo(new File(filePath));
    } catch (IOException e) {
        FileUtil.del(fileDir);
        return CommonResult.errorResponse("服务器异常:qduoj题目上传失败!");
    }
    // 将压缩包压缩到指定文件夹
    ZipUtil.unzip(filePath, fileDir);
    // 删除zip文件
    FileUtil.del(filePath);
    // 检查文件是否存在
    File testCaseFileList = new File(fileDir);
    File[] files = testCaseFileList.listFiles();
    if (files == null || files.length == 0) {
        FileUtil.del(fileDir);
        return CommonResult.errorResponse("评测数据压缩包里文件不能为空!");
    }
    HashMap<String, File> problemInfo = new HashMap<>();
    for (File tmp : files) {
        if (tmp.isDirectory()) {
            File[] problemAndTestcase = tmp.listFiles();
            if (problemAndTestcase == null || problemAndTestcase.length == 0) {
                FileUtil.del(fileDir);
                return CommonResult.errorResponse("编号为:" + tmp.getName() + "的文件夹为空!");
            }
            for (File problemFile : problemAndTestcase) {
                if (problemFile.isFile()) {
                    // 检查文件是否时json文件
                    if (!problemFile.getName().endsWith("json")) {
                        FileUtil.del(fileDir);
                        return CommonResult.errorResponse("编号为:" + tmp.getName() + "的文件夹里面的题目数据格式错误,请使用json文件!");
                    }
                    problemInfo.put(tmp.getName(), problemFile);
                }
            }
        }
    }
    // 读取json文件生成对象
    HashMap<String, QDOJProblemDto> problemVoMap = new HashMap<>();
    for (String key : problemInfo.keySet()) {
        try {
            FileReader fileReader = new FileReader(problemInfo.get(key));
            JSONObject problemJson = JSONUtil.parseObj(fileReader.readString());
            QDOJProblemDto qdojProblemDto = QDOJProblemToProblemVo(problemJson);
            problemVoMap.put(key, qdojProblemDto);
        } catch (Exception e) {
            FileUtil.del(fileDir);
            return CommonResult.errorResponse("请检查编号为:" + key + "的题目json文件的格式:" + e.getLocalizedMessage());
        }
    }
    QueryWrapper<Language> languageQueryWrapper = new QueryWrapper<>();
    languageQueryWrapper.eq("oj", "ME");
    List<Language> languageList = languageService.list(languageQueryWrapper);
    HashMap<String, Long> languageMap = new HashMap<>();
    for (Language language : languageList) {
        languageMap.put(language.getName(), language.getId());
    }
    // 获取当前登录的用户
    HttpSession session = request.getSession();
    UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
    List<Tag> tagList = tagService.list(new QueryWrapper<Tag>().eq("oj", "ME"));
    HashMap<String, Tag> tagMap = new HashMap<>();
    for (Tag tag : tagList) {
        tagMap.put(tag.getName().toUpperCase(), tag);
    }
    List<ProblemDto> problemDtos = new LinkedList<>();
    for (String key : problemInfo.keySet()) {
        QDOJProblemDto qdojProblemDto = problemVoMap.get(key);
        // 格式化题目语言
        List<Language> languages = new LinkedList<>();
        for (String lang : qdojProblemDto.getLanguages()) {
            Long lid = languageMap.getOrDefault(lang, null);
            languages.add(new Language().setId(lid).setName(lang));
        }
        // 格式化标签
        List<Tag> tags = new LinkedList<>();
        for (String tagStr : qdojProblemDto.getTags()) {
            Tag tag = tagMap.getOrDefault(tagStr.toUpperCase(), null);
            if (tag == null) {
                tags.add(new Tag().setName(tagStr).setOj("ME"));
            } else {
                tags.add(tag);
            }
        }
        Problem problem = qdojProblemDto.getProblem();
        if (problem.getAuthor() == null) {
            problem.setAuthor(userRolesVo.getUsername());
        }
        ProblemDto problemDto = new ProblemDto();
        String mode = Constants.JudgeMode.DEFAULT.getMode();
        if (qdojProblemDto.getIsSpj()) {
            mode = Constants.JudgeMode.SPJ.getMode();
        }
        problemDto.setJudgeMode(mode).setProblem(problem).setCodeTemplates(qdojProblemDto.getCodeTemplates()).setTags(tags).setLanguages(languages).setUploadTestcaseDir(fileDir + File.separator + key + File.separator + "testcase").setIsUploadTestCase(true).setSamples(qdojProblemDto.getSamples());
        problemDtos.add(problemDto);
    }
    for (ProblemDto problemDto : problemDtos) {
        problemService.adminAddProblem(problemDto);
    }
    return CommonResult.successResponse(null, "导入题目成功");
}
Also used : HashMap(java.util.HashMap) Language(top.hcode.hoj.pojo.entity.problem.Language) UserRolesVo(top.hcode.hoj.pojo.vo.UserRolesVo) FileReader(cn.hutool.core.io.file.FileReader) QDOJProblemDto(top.hcode.hoj.pojo.dto.QDOJProblemDto) ProblemDto(top.hcode.hoj.pojo.dto.ProblemDto) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) HttpSession(javax.servlet.http.HttpSession) QDOJProblemDto(top.hcode.hoj.pojo.dto.QDOJProblemDto) IOException(java.io.IOException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) JSONObject(cn.hutool.json.JSONObject) Problem(top.hcode.hoj.pojo.entity.problem.Problem) Tag(top.hcode.hoj.pojo.entity.problem.Tag) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) PostMapping(org.springframework.web.bind.annotation.PostMapping) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) RequiresRoles(org.apache.shiro.authz.annotation.RequiresRoles) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with QDOJProblemDto

use of top.hcode.hoj.pojo.dto.QDOJProblemDto in project HOJ by HimitZH.

the class ImportQDUOJProblemManager method QDOJProblemToProblemVo.

private QDOJProblemDto QDOJProblemToProblemVo(JSONObject problemJson) {
    QDOJProblemDto qdojProblemDto = new QDOJProblemDto();
    List<String> tags = (List<String>) problemJson.get("tags");
    qdojProblemDto.setTags(tags.stream().map(UnicodeUtil::toString).collect(Collectors.toList()));
    qdojProblemDto.setLanguages(Arrays.asList("C", "C With O2", "C++", "C++ With O2", "Java", "Python3", "Python2", "Golang", "C#"));
    Object spj = problemJson.getObj("spj");
    boolean isSpj = !JSONUtil.isNull(spj);
    qdojProblemDto.setIsSpj(isSpj);
    Problem problem = new Problem();
    if (isSpj) {
        JSONObject spjJson = JSONUtil.parseObj(spj);
        problem.setSpjCode(spjJson.getStr("code")).setSpjLanguage(spjJson.getStr("language"));
    }
    problem.setAuth(1).setIsGroup(false).setIsUploadCase(true).setSource(problemJson.getStr("source", null)).setDifficulty(1).setProblemId(problemJson.getStr("display_id")).setIsRemoveEndBlank(true).setOpenCaseResult(true).setCodeShare(false).setType(problemJson.getStr("rule_type").equals("ACM") ? 0 : 1).setTitle(problemJson.getStr("title")).setDescription(UnicodeUtil.toString(problemJson.getJSONObject("description").getStr("value"))).setInput(UnicodeUtil.toString(problemJson.getJSONObject("input_description").getStr("value"))).setOutput(UnicodeUtil.toString(problemJson.getJSONObject("output_description").getStr("value"))).setHint(UnicodeUtil.toString(problemJson.getJSONObject("hint").getStr("value"))).setTimeLimit(problemJson.getInt("time_limit")).setMemoryLimit(problemJson.getInt("memory_limit"));
    JSONArray samples = problemJson.getJSONArray("samples");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < samples.size(); i++) {
        JSONObject sample = (JSONObject) samples.get(i);
        String input = sample.getStr("input");
        String output = sample.getStr("output");
        sb.append("<input>").append(input).append("</input>");
        sb.append("<output>").append(output).append("</output>");
    }
    problem.setExamples(sb.toString());
    int sumScore = 0;
    JSONArray testcaseList = problemJson.getJSONArray("test_case_score");
    List<ProblemCase> problemSamples = new LinkedList<>();
    for (int i = 0; i < testcaseList.size(); i++) {
        JSONObject testcase = (JSONObject) testcaseList.get(i);
        String input = testcase.getStr("input_name");
        String output = testcase.getStr("output_name");
        Integer score = testcase.getInt("score", null);
        problemSamples.add(new ProblemCase().setInput(input).setOutput(output).setScore(score));
        if (score != null) {
            sumScore += score;
        }
    }
    problem.setIsRemote(false);
    problem.setIoScore(sumScore);
    qdojProblemDto.setSamples(problemSamples);
    qdojProblemDto.setProblem(problem);
    return qdojProblemDto;
}
Also used : JSONArray(cn.hutool.json.JSONArray) QDOJProblemDto(top.hcode.hoj.pojo.dto.QDOJProblemDto) ProblemCase(top.hcode.hoj.pojo.entity.problem.ProblemCase) UnicodeUtil(cn.hutool.core.text.UnicodeUtil) LinkedList(java.util.LinkedList) JSONObject(cn.hutool.json.JSONObject) LinkedList(java.util.LinkedList) List(java.util.List) JSONObject(cn.hutool.json.JSONObject) Problem(top.hcode.hoj.pojo.entity.problem.Problem)

Example 4 with QDOJProblemDto

use of top.hcode.hoj.pojo.dto.QDOJProblemDto in project HOJ by HimitZH.

the class ImportQDUOJProblemManager method importQDOJProblem.

/**
 * @param file
 * @MethodName importQDOJProblem
 * @Description zip文件导入题目 仅超级管理员可操作
 * @Return
 * @Since 2021/5/27
 */
@Transactional(rollbackFor = Exception.class)
public void importQDOJProblem(MultipartFile file) throws StatusFailException, StatusSystemErrorException {
    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
    if (!"zip".toUpperCase().contains(suffix.toUpperCase())) {
        throw new StatusFailException("请上传zip格式的题目文件压缩包!");
    }
    String fileDirId = IdUtil.simpleUUID();
    String fileDir = Constants.File.TESTCASE_TMP_FOLDER.getPath() + File.separator + fileDirId;
    String filePath = fileDir + File.separator + file.getOriginalFilename();
    // 文件夹不存在就新建
    FileUtil.mkdir(fileDir);
    try {
        file.transferTo(new File(filePath));
    } catch (IOException e) {
        FileUtil.del(fileDir);
        throw new StatusSystemErrorException("服务器异常:qduoj题目上传失败!");
    }
    // 将压缩包压缩到指定文件夹
    ZipUtil.unzip(filePath, fileDir);
    // 删除zip文件
    FileUtil.del(filePath);
    // 检查文件是否存在
    File testCaseFileList = new File(fileDir);
    File[] files = testCaseFileList.listFiles();
    if (files == null || files.length == 0) {
        FileUtil.del(fileDir);
        throw new StatusFailException("评测数据压缩包里文件不能为空!");
    }
    HashMap<String, File> problemInfo = new HashMap<>();
    for (File tmp : files) {
        if (tmp.isDirectory()) {
            File[] problemAndTestcase = tmp.listFiles();
            if (problemAndTestcase == null || problemAndTestcase.length == 0) {
                FileUtil.del(fileDir);
                throw new StatusFailException("编号为:" + tmp.getName() + "的文件夹为空!");
            }
            for (File problemFile : problemAndTestcase) {
                if (problemFile.isFile()) {
                    // 检查文件是否时json文件
                    if (!problemFile.getName().endsWith("json")) {
                        FileUtil.del(fileDir);
                        throw new StatusFailException("编号为:" + tmp.getName() + "的文件夹里面的题目数据格式错误,请使用json文件!");
                    }
                    problemInfo.put(tmp.getName(), problemFile);
                }
            }
        }
    }
    // 读取json文件生成对象
    HashMap<String, QDOJProblemDto> problemVoMap = new HashMap<>();
    for (String key : problemInfo.keySet()) {
        try {
            FileReader fileReader = new FileReader(problemInfo.get(key));
            JSONObject problemJson = JSONUtil.parseObj(fileReader.readString());
            QDOJProblemDto qdojProblemDto = QDOJProblemToProblemVo(problemJson);
            problemVoMap.put(key, qdojProblemDto);
        } catch (Exception e) {
            FileUtil.del(fileDir);
            throw new StatusFailException("请检查编号为:" + key + "的题目json文件的格式:" + e.getLocalizedMessage());
        }
    }
    QueryWrapper<Language> languageQueryWrapper = new QueryWrapper<>();
    languageQueryWrapper.eq("oj", "ME");
    List<Language> languageList = languageEntityService.list(languageQueryWrapper);
    HashMap<String, Long> languageMap = new HashMap<>();
    for (Language language : languageList) {
        languageMap.put(language.getName(), language.getId());
    }
    // 获取当前登录的用户
    Session session = SecurityUtils.getSubject().getSession();
    UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
    List<Tag> tagList = tagEntityService.list(new QueryWrapper<Tag>().eq("oj", "ME"));
    HashMap<String, Tag> tagMap = new HashMap<>();
    for (Tag tag : tagList) {
        tagMap.put(tag.getName().toUpperCase(), tag);
    }
    List<ProblemDto> problemDtos = new LinkedList<>();
    for (String key : problemInfo.keySet()) {
        QDOJProblemDto qdojProblemDto = problemVoMap.get(key);
        // 格式化题目语言
        List<Language> languages = new LinkedList<>();
        for (String lang : qdojProblemDto.getLanguages()) {
            Long lid = languageMap.getOrDefault(lang, null);
            languages.add(new Language().setId(lid).setName(lang));
        }
        // 格式化标签
        List<Tag> tags = new LinkedList<>();
        for (String tagStr : qdojProblemDto.getTags()) {
            Tag tag = tagMap.getOrDefault(tagStr.toUpperCase(), null);
            if (tag == null) {
                tags.add(new Tag().setName(tagStr).setOj("ME"));
            } else {
                tags.add(tag);
            }
        }
        Problem problem = qdojProblemDto.getProblem();
        if (problem.getAuthor() == null) {
            problem.setAuthor(userRolesVo.getUsername());
        }
        ProblemDto problemDto = new ProblemDto();
        String mode = Constants.JudgeMode.DEFAULT.getMode();
        if (qdojProblemDto.getIsSpj()) {
            mode = Constants.JudgeMode.SPJ.getMode();
        }
        problemDto.setJudgeMode(mode).setProblem(problem).setCodeTemplates(qdojProblemDto.getCodeTemplates()).setTags(tags).setLanguages(languages).setUploadTestcaseDir(fileDir + File.separator + key + File.separator + "testcase").setIsUploadTestCase(true).setSamples(qdojProblemDto.getSamples());
        problemDtos.add(problemDto);
    }
    if (problemDtos.size() == 0) {
        throw new StatusFailException("警告:未成功导入一道以上的题目,请检查文件格式是否正确!");
    } else {
        for (ProblemDto problemDto : problemDtos) {
            problemEntityService.adminAddProblem(problemDto);
        }
    }
}
Also used : HashMap(java.util.HashMap) Language(top.hcode.hoj.pojo.entity.problem.Language) UserRolesVo(top.hcode.hoj.pojo.vo.UserRolesVo) FileReader(cn.hutool.core.io.file.FileReader) QDOJProblemDto(top.hcode.hoj.pojo.dto.QDOJProblemDto) ProblemDto(top.hcode.hoj.pojo.dto.ProblemDto) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) QDOJProblemDto(top.hcode.hoj.pojo.dto.QDOJProblemDto) IOException(java.io.IOException) StatusSystemErrorException(top.hcode.hoj.common.exception.StatusSystemErrorException) IOException(java.io.IOException) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) LinkedList(java.util.LinkedList) JSONObject(cn.hutool.json.JSONObject) StatusFailException(top.hcode.hoj.common.exception.StatusFailException) Problem(top.hcode.hoj.pojo.entity.problem.Problem) Tag(top.hcode.hoj.pojo.entity.problem.Tag) 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

JSONObject (cn.hutool.json.JSONObject)4 LinkedList (java.util.LinkedList)4 QDOJProblemDto (top.hcode.hoj.pojo.dto.QDOJProblemDto)4 Problem (top.hcode.hoj.pojo.entity.problem.Problem)4 FileReader (cn.hutool.core.io.file.FileReader)2 UnicodeUtil (cn.hutool.core.text.UnicodeUtil)2 JSONArray (cn.hutool.json.JSONArray)2 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)2 File (java.io.File)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Transactional (org.springframework.transaction.annotation.Transactional)2 MultipartFile (org.springframework.web.multipart.MultipartFile)2 ProblemDto (top.hcode.hoj.pojo.dto.ProblemDto)2 Language (top.hcode.hoj.pojo.entity.problem.Language)2 ProblemCase (top.hcode.hoj.pojo.entity.problem.ProblemCase)2 Tag (top.hcode.hoj.pojo.entity.problem.Tag)2 UserRolesVo (top.hcode.hoj.pojo.vo.UserRolesVo)2 HttpSession (javax.servlet.http.HttpSession)1