Search in sources :

Example 1 with FileReader

use of cn.hutool.core.io.file.FileReader in project View-Elasticsearch by shencangsheng.

the class QueryTest method main.

public static void main(String[] args) throws Exception {
    FileReader templateJson = new FileReader("template.json");
    String queryJson = templateJson.readString();
    ObjectMapper objectMapper = new ObjectMapper();
    List<QueryInstance> queryInstances = objectMapper.readValue(queryJson, new TypeReference<>() {
    });
    BoolQueryBuilder boolQueryBuilder = BoolQueryBuilderFactory.boolQueryBuilderFactory(queryInstances, new TemplateModuleInstance());
    System.out.println(boolQueryBuilder);
}
Also used : QueryInstance(com.shencangsheng.view.query.model.QueryInstance) TemplateModuleInstance(com.shencangsheng.view.module.TemplateModuleInstance) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) FileReader(cn.hutool.core.io.file.FileReader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 2 with FileReader

use of cn.hutool.core.io.file.FileReader in project HOJ by HimitZH.

the class ContestFileController method downloadContestPrintText.

@GetMapping("/download-contest-print-text")
@RequiresAuthentication
@RequiresRoles(value = { "root", "admin", "problem_admin" }, logical = Logical.OR)
public void downloadContestPrintText(@RequestParam("id") Long id, HttpServletResponse response) {
    ContestPrint contestPrint = contestPrintService.getById(id);
    String filename = contestPrint.getUsername() + "_Contest_Print.txt";
    String filePath = Constants.File.CONTEST_TEXT_PRINT_FOLDER.getPath() + File.separator + id + File.separator + filename;
    if (!FileUtil.exist(filePath)) {
        FileWriter fileWriter = new FileWriter(filePath);
        fileWriter.write(contestPrint.getContent());
    }
    FileReader zipFileReader = new FileReader(filePath);
    // 放到缓冲流里面
    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(filename, "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("下载比赛打印文本文件异常------------>", e);
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Map<String, Object> map = new HashMap<>();
        map.put("status", CommonResult.STATUS_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();
        }
    }
}
Also used : ContestPrint(top.hcode.hoj.pojo.entity.contest.ContestPrint) FileWriter(cn.hutool.core.io.file.FileWriter) FileReader(cn.hutool.core.io.file.FileReader) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ContestPrint(top.hcode.hoj.pojo.entity.contest.ContestPrint) GetMapping(org.springframework.web.bind.annotation.GetMapping) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) RequiresRoles(org.apache.shiro.authz.annotation.RequiresRoles)

Example 3 with FileReader

use of cn.hutool.core.io.file.FileReader in project HOJ by HimitZH.

the class TestCaseController method downloadTestcase.

@GetMapping("/download-testcase")
@RequiresAuthentication
@RequiresRoles(value = { "root", "problem_admin" }, logical = Logical.OR)
public void downloadTestcase(@RequestParam("pid") Long pid, HttpServletResponse response) {
    String workDir = Constants.File.TESTCASE_BASE_FOLDER.getPath() + File.separator + "problem_" + pid;
    File file = new File(workDir);
    if (!file.exists()) {
        // 本地为空 尝试去数据库查找
        QueryWrapper<ProblemCase> problemCaseQueryWrapper = new QueryWrapper<>();
        problemCaseQueryWrapper.eq("pid", pid);
        List<ProblemCase> problemCaseList = problemCaseService.list(problemCaseQueryWrapper);
        Assert.notEmpty(problemCaseList, "对不起,该题目的评测数据为空!");
        boolean hasTestCase = true;
        if (problemCaseList.get(0).getInput().endsWith(".in") && (problemCaseList.get(0).getOutput().endsWith(".out") || problemCaseList.get(0).getOutput().endsWith(".ans"))) {
            hasTestCase = false;
        }
        Assert.isTrue(hasTestCase, "对不起,该题目的评测数据为空!");
        FileUtil.mkdir(workDir);
        // 写入本地
        for (int i = 0; i < problemCaseList.size(); i++) {
            String filePreName = workDir + File.separator + (i + 1);
            String inputName = filePreName + ".in";
            String outputName = filePreName + ".out";
            FileWriter infileWriter = new FileWriter(inputName);
            infileWriter.write(problemCaseList.get(i).getInput());
            FileWriter outfileWriter = new FileWriter(outputName);
            outfileWriter.write(problemCaseList.get(i).getOutput());
        }
    }
    String fileName = "problem_" + pid + "_testcase_" + System.currentTimeMillis() + ".zip";
    // 将对应文件夹的文件压缩成zip
    ZipUtil.zip(workDir, Constants.File.FILE_DOWNLOAD_TMP_FOLDER.getPath() + File.separator + fileName);
    // 将zip变成io流返回给前端
    FileReader fileReader = new FileReader(Constants.File.FILE_DOWNLOAD_TMP_FOLDER.getPath() + File.separator + fileName);
    // 放到缓冲流里面
    BufferedInputStream bins = new BufferedInputStream(fileReader.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(fileName, "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("下载题目测试数据的压缩文件异常------------>{}", e.getMessage());
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Map<String, Object> map = new HashMap<>();
        map.put("status", CommonResult.STATUS_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(Constants.File.FILE_DOWNLOAD_TMP_FOLDER.getPath() + File.separator + fileName);
    }
}
Also used : QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) FileWriter(cn.hutool.core.io.file.FileWriter) ProblemCase(top.hcode.hoj.pojo.entity.problem.ProblemCase) FileReader(cn.hutool.core.io.file.FileReader) MultipartFile(org.springframework.web.multipart.MultipartFile) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) RequiresRoles(org.apache.shiro.authz.annotation.RequiresRoles)

Example 4 with FileReader

use of cn.hutool.core.io.file.FileReader 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 5 with FileReader

use of cn.hutool.core.io.file.FileReader in project coding-more by itwanger.

the class Convert method main.

public static void main(String[] args) throws IOException {
    FileReader fileReader = FileReader.create(new File(docPath + fileName), Charset.forName("utf-8"));
    List<String> list = fileReader.readLines();
    FileWriter writer = new FileWriter(docPath + fileName);
    int num = 1;
    for (String line : list) {
        Matcher m = pattern.matcher(line);
        if (m.matches()) {
            // 处理图片
            // png 还是 gif 还是 jpg
            String imgSuffixTemp = pngSuffix;
            int index = line.indexOf(pngSuffix);
            if (index == -1) {
                index = line.indexOf(gifSuffix);
                imgSuffixTemp = gifSuffix;
                if (index == -1) {
                    index = line.indexOf(jpgSuffix);
                    imgSuffixTemp = jpgSuffix;
                    if (index == -1) {
                        index = line.indexOf(jpegSuffix);
                        imgSuffixTemp = jpegSuffix;
                    }
                }
            }
            if (index == -1) {
                writer.append(line + "\n");
            } else {
                System.out.println("处理图片" + line);
                String originImgUrl = line.substring("![](".length(), index) + imgSuffixTemp;
                String destinationImgPath = imgPath + key + "-" + num + imgSuffixTemp;
                // 1、下载到本地
                new Thread(new MyRunnable(originImgUrl, destinationImgPath)).start();
                // 2、修改 MD 文档
                writer.append("![](" + imgCdnPre + num + imgSuffixTemp + ")\n");
                num++;
            }
        } else {
            writer.append(line + "\n");
        }
    }
    writer.flush();
}
Also used : Matcher(java.util.regex.Matcher) FileReader(cn.hutool.core.io.file.FileReader)

Aggregations

FileReader (cn.hutool.core.io.file.FileReader)26 FileWriter (cn.hutool.core.io.file.FileWriter)14 File (java.io.File)11 JSONObject (cn.hutool.json.JSONObject)10 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)10 MultipartFile (org.springframework.web.multipart.MultipartFile)8 UserRolesVo (top.hcode.hoj.pojo.vo.UserRolesVo)8 RequiresAuthentication (org.apache.shiro.authz.annotation.RequiresAuthentication)6 RequiresRoles (org.apache.shiro.authz.annotation.RequiresRoles)6 JSONArray (cn.hutool.json.JSONArray)5 Session (org.apache.shiro.session.Session)5 HashMap (java.util.HashMap)4 Matcher (java.util.regex.Matcher)4 IOException (java.io.IOException)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 Pattern (java.util.regex.Pattern)3 Test (org.junit.Test)3 Transactional (org.springframework.transaction.annotation.Transactional)3 StatusFailException (top.hcode.hoj.common.exception.StatusFailException)3 ProblemDto (top.hcode.hoj.pojo.dto.ProblemDto)3