Search in sources :

Example 6 with JSONArray

use of cn.hutool.json.JSONArray in project hutool by dromara.

the class JSONXMLSerializer method toXml.

/**
 * 转换JSONObject为XML
 *
 * @param object      JSON对象或数组
 * @param tagName     可选标签名称,名称为空时忽略标签
 * @param contentKeys 标识为内容的key,遇到此key直接解析内容而不增加对应名称标签
 * @return A string.
 * @throws JSONException JSON解析异常
 */
public static String toXml(Object object, String tagName, String... contentKeys) throws JSONException {
    if (null == object) {
        return null;
    }
    final StringBuilder sb = new StringBuilder();
    if (object instanceof JSONObject) {
        // Emit <tagName>
        appendTag(sb, tagName, false);
        // Loop thru the keys.
        ((JSONObject) object).forEach((key, value) -> {
            if (ArrayUtil.isArray(value)) {
                value = new JSONArray(value);
            }
            // Emit content in body
            if (ArrayUtil.contains(contentKeys, key)) {
                if (value instanceof JSONArray) {
                    int i = 0;
                    for (Object val : (JSONArray) value) {
                        if (i > 0) {
                            sb.append(CharUtil.LF);
                        }
                        sb.append(EscapeUtil.escapeXml(val.toString()));
                        i++;
                    }
                } else {
                    sb.append(EscapeUtil.escapeXml(value.toString()));
                }
            // Emit an array of similar keys
            } else if (StrUtil.isEmptyIfStr(value)) {
                sb.append(wrapWithTag(null, key));
            } else if (value instanceof JSONArray) {
                for (Object val : (JSONArray) value) {
                    if (val instanceof JSONArray) {
                        sb.append(wrapWithTag(toXml(val), key));
                    } else {
                        sb.append(toXml(val, key));
                    }
                }
            } else {
                sb.append(toXml(value, key));
            }
        });
        // Emit the </tagname> close tag
        appendTag(sb, tagName, true);
        return sb.toString();
    }
    if (ArrayUtil.isArray(object)) {
        object = new JSONArray(object);
    }
    if (object instanceof JSONArray) {
        for (Object val : (JSONArray) object) {
            // XML does not have good support for arrays. If an array
            // appears in a place where XML is lacking, synthesize an
            // <array> element.
            sb.append(toXml(val, tagName == null ? "array" : tagName));
        }
        return sb.toString();
    }
    return wrapWithTag(EscapeUtil.escapeXml(object.toString()), tagName);
}
Also used : JSONObject(cn.hutool.json.JSONObject) JSONArray(cn.hutool.json.JSONArray) JSONObject(cn.hutool.json.JSONObject)

Example 7 with JSONArray

use of cn.hutool.json.JSONArray in project HOJ by HimitZH.

the class CodeForcesJudge method result.

@Override
public RemoteJudgeRes result() {
    String resJson = getSubmissionResult(getRemoteJudgeDTO().getUsername(), 1000).body();
    JSONObject jsonObject = JSONUtil.parseObj(resJson);
    RemoteJudgeRes remoteJudgeRes = RemoteJudgeRes.builder().status(Constants.Judge.STATUS_JUDGING.getStatus()).build();
    JSONArray results = (JSONArray) jsonObject.get("result");
    for (Object tmp : results) {
        JSONObject result = (JSONObject) tmp;
        long runId = Long.parseLong(result.get("id").toString());
        if (runId == getRemoteJudgeDTO().getSubmitId()) {
            String verdict = (String) result.get("verdict");
            Constants.Judge resultStatus = statusMap.get(verdict);
            if (resultStatus == Constants.Judge.STATUS_JUDGING) {
                return RemoteJudgeRes.builder().status(resultStatus.getStatus()).build();
            } else if (resultStatus == null) {
                return RemoteJudgeRes.builder().status(Constants.Judge.STATUS_PENDING.getStatus()).build();
            }
            remoteJudgeRes.setTime((Integer) result.get("timeConsumedMillis"));
            remoteJudgeRes.setMemory((int) result.get("memoryConsumedBytes") / 1024);
            if (resultStatus == Constants.Judge.STATUS_COMPILE_ERROR) {
                String csrfToken = getCsrfToken(HOST);
                HttpRequest httpRequest = HttpUtil.createPost(HOST + CE_INFO_URL).timeout(30000);
                httpRequest.form(MapUtil.builder(new HashMap<String, Object>()).put("csrf_token", csrfToken).put("submissionId", getRemoteJudgeDTO().getSubmitId().toString()).map());
                HttpResponse response = httpRequest.execute();
                if (response.getStatus() == 200) {
                    JSONObject CEInfoJson = JSONUtil.parseObj(response.body());
                    String CEInfo = CEInfoJson.getStr("checkerStdoutAndStderr#1");
                    remoteJudgeRes.setErrorInfo(CEInfo);
                } else {
                    // 非200则说明cf没有提供编译失败的详情
                    remoteJudgeRes.setErrorInfo("Oops! Because Codeforces does not provide compilation details, it is unable to provide the reason for compilation failure!");
                }
            }
            remoteJudgeRes.setStatus(resultStatus.getStatus());
            return remoteJudgeRes;
        }
    }
    return remoteJudgeRes;
}
Also used : RemoteJudgeRes(top.hcode.hoj.remoteJudge.entity.RemoteJudgeRes) HttpRequest(cn.hutool.http.HttpRequest) JSONObject(cn.hutool.json.JSONObject) JSONArray(cn.hutool.json.JSONArray) Constants(top.hcode.hoj.util.Constants) HttpResponse(cn.hutool.http.HttpResponse) JSONObject(cn.hutool.json.JSONObject)

Example 8 with JSONArray

use of cn.hutool.json.JSONArray in project HOJ by HimitZH.

the class SandboxRun method interactTestCase.

/**
 * @param args                   cmd的命令参数 评测运行的命令
 * @param envs                   测评的环境变量
 * @param userExeName            用户程序的名字
 * @param userFileId             用户程序在编译后返回的id,主要是对应内存中已编译后的文件
 * @param userFileSrc            用户程序文件的绝对路径,如果userFileId存在则为null
 * @param userMaxTime            用户程序的最大测评时间 ms
 * @param userMaxStack           用户程序的最大测评栈空间 mb
 * @param testCaseInputPath      题目数据的输入文件路径
 * @param testCaseInputFileName  题目数据的输入文件名字
 * @param testCaseOutputFilePath 题目数据的输出文件路径
 * @param testCaseOutputFileName 题目数据的输出文件名字
 * @param userOutputFileName     用户程序的输出文件名字
 * @param interactArgs           交互程序运行的cmd命令参数
 * @param interactEnvs           交互程序运行的环境变量
 * @param interactExeSrc         交互程序的exe文件路径
 * @param interactExeName        交互程序的exe文件名字
 * @MethodName interactTestCase
 * @Description 交互评测
 * @Return JSONArray
 * @Since 2022/1/3
 */
public static JSONArray interactTestCase(List<String> args, List<String> envs, String userExeName, String userFileId, String userFileSrc, Long userMaxTime, Long userMaxMemory, Integer userMaxStack, String testCaseInputPath, String testCaseInputFileName, String testCaseOutputFilePath, String testCaseOutputFileName, String userOutputFileName, List<String> interactArgs, List<String> interactEnvs, String interactExeSrc, String interactExeName) throws SystemError {
    /**
     *  注意:用户源代码需要先编译,若是通过编译需要先将文件存入内存,再利用管道判题,同时特殊判题程序必须已编译且存在(否则判题失败,系统错误)!
     */
    JSONObject pipeInputCmd = new JSONObject();
    pipeInputCmd.set("args", args);
    pipeInputCmd.set("env", envs);
    JSONArray files = new JSONArray();
    JSONObject stderr = new JSONObject();
    stderr.set("name", "stderr");
    stderr.set("max", 1024 * 1024 * STDIO_SIZE_MB);
    files.put(new JSONObject());
    files.put(new JSONObject());
    files.put(stderr);
    String inTmp = files.toString().replace("{}", "null");
    pipeInputCmd.set("files", JSONUtil.parseArray(inTmp, false));
    // ms-->ns
    pipeInputCmd.set("cpuLimit", userMaxTime * 1000 * 1000L);
    pipeInputCmd.set("clockLimit", userMaxTime * 1000 * 1000L * 3);
    // byte
    pipeInputCmd.set("memoryLimit", (userMaxMemory + 100) * 1024 * 1024L);
    pipeInputCmd.set("procLimit", maxProcessNumber);
    pipeInputCmd.set("stackLimit", userMaxStack * 1024 * 1024L);
    JSONObject exeFile = new JSONObject();
    if (!StringUtils.isEmpty(userFileId)) {
        exeFile.set("fileId", userFileId);
    } else {
        exeFile.set("src", userFileSrc);
    }
    JSONObject copyIn = new JSONObject();
    copyIn.set(userExeName, exeFile);
    pipeInputCmd.set("copyIn", copyIn);
    pipeInputCmd.set("copyOut", new JSONArray());
    // 管道输出,用户程序输出数据经过特殊判题程序后,得到的最终输出结果。
    JSONObject pipeOutputCmd = new JSONObject();
    pipeOutputCmd.set("args", interactArgs);
    pipeOutputCmd.set("env", interactEnvs);
    JSONArray outFiles = new JSONArray();
    JSONObject outStderr = new JSONObject();
    outStderr.set("name", "stderr");
    outStderr.set("max", 1024 * 1024 * STDIO_SIZE_MB);
    outFiles.put(new JSONObject());
    outFiles.put(new JSONObject());
    outFiles.put(outStderr);
    String outTmp = outFiles.toString().replace("{}", "null");
    pipeOutputCmd.set("files", JSONUtil.parseArray(outTmp, false));
    // ms-->ns
    pipeOutputCmd.set("cpuLimit", userMaxTime * 1000 * 1000L * 2);
    pipeOutputCmd.set("clockLimit", userMaxTime * 1000 * 1000L * 3 * 2);
    // byte
    pipeOutputCmd.set("memoryLimit", (userMaxMemory + 100) * 1024 * 1024L * 2);
    pipeOutputCmd.set("procLimit", maxProcessNumber);
    pipeOutputCmd.set("stackLimit", STACK_LIMIT_MB * 1024 * 1024L);
    JSONObject spjExeFile = new JSONObject();
    spjExeFile.set("src", interactExeSrc);
    JSONObject stdInputFileSrc = new JSONObject();
    stdInputFileSrc.set("src", testCaseInputPath);
    JSONObject stdOutFileSrc = new JSONObject();
    stdOutFileSrc.set("src", testCaseOutputFilePath);
    JSONObject interactiveCopyIn = new JSONObject();
    interactiveCopyIn.set(interactExeName, spjExeFile);
    interactiveCopyIn.set(testCaseInputFileName, stdInputFileSrc);
    interactiveCopyIn.set(testCaseOutputFileName, stdOutFileSrc);
    pipeOutputCmd.set("copyIn", interactiveCopyIn);
    pipeOutputCmd.set("copyOut", new JSONArray().put(userOutputFileName));
    JSONArray cmdList = new JSONArray();
    cmdList.put(pipeInputCmd);
    cmdList.put(pipeOutputCmd);
    JSONObject param = new JSONObject();
    // 添加cmd指令
    param.set("cmd", cmdList);
    // 添加管道映射
    JSONArray pipeMapping = new JSONArray();
    // 用户程序
    JSONObject user = new JSONObject();
    JSONObject userIn = new JSONObject();
    userIn.set("index", 0);
    userIn.set("fd", 1);
    JSONObject userOut = new JSONObject();
    userOut.set("index", 1);
    userOut.set("fd", 0);
    user.set("in", userIn);
    user.set("out", userOut);
    user.set("max", STDIO_SIZE_MB * 1024 * 1024);
    user.set("proxy", true);
    user.set("name", "stdout");
    // 评测程序
    JSONObject judge = new JSONObject();
    JSONObject judgeIn = new JSONObject();
    judgeIn.set("index", 1);
    judgeIn.set("fd", 1);
    JSONObject judgeOut = new JSONObject();
    judgeOut.set("index", 0);
    judgeOut.set("fd", 0);
    judge.set("in", judgeIn);
    judge.set("out", judgeOut);
    judge.set("max", STDIO_SIZE_MB * 1024 * 1024);
    judge.set("proxy", true);
    judge.set("name", "stdout");
    // 添加到管道映射列表
    pipeMapping.add(user);
    pipeMapping.add(judge);
    param.set("pipeMapping", pipeMapping);
    // 调用判题安全沙箱
    JSONArray result = instance.run("/run", param);
    JSONObject userRes = (JSONObject) result.get(0);
    JSONObject interactiveRes = (JSONObject) result.get(1);
    userRes.set("status", RESULT_MAP_STATUS.get(userRes.getStr("status")));
    interactiveRes.set("status", RESULT_MAP_STATUS.get(interactiveRes.getStr("status")));
    return result;
}
Also used : JSONObject(cn.hutool.json.JSONObject) JSONArray(cn.hutool.json.JSONArray)

Example 9 with JSONArray

use of cn.hutool.json.JSONArray in project HOJ by HimitZH.

the class SandboxRun method compile.

/**
 * @param maxCpuTime        最大编译的cpu时间 ms
 * @param maxRealTime       最大编译的真实时间 ms
 * @param maxMemory         最大编译的空间 b
 * @param maxStack          最大编译的栈空间 b
 * @param srcName           编译的源文件名字
 * @param exeName           编译生成的exe文件名字
 * @param args              编译的cmd参数
 * @param envs              编译的环境变量
 * @param code              编译的源代码
 * @param extraFiles        编译所需的额外文件 key:文件名,value:文件内容
 * @param needCopyOutCached 是否需要生成编译后的用户程序exe文件
 * @param needCopyOutExe    是否需要生成用户程序的缓存文件,即生成用户程序id
 * @param copyOutDir        生成编译后的用户程序exe文件的指定路径
 * @MethodName compile
 * @Description 编译运行
 * @Return
 * @Since 2022/1/3
 */
public static JSONArray compile(Long maxCpuTime, Long maxRealTime, Long maxMemory, Long maxStack, String srcName, String exeName, List<String> args, List<String> envs, String code, HashMap<String, String> extraFiles, Boolean needCopyOutCached, Boolean needCopyOutExe, String copyOutDir) throws SystemError {
    JSONObject cmd = new JSONObject();
    cmd.set("args", args);
    cmd.set("env", envs);
    cmd.set("files", COMPILE_FILES);
    // ms-->ns
    cmd.set("cpuLimit", maxCpuTime * 1000 * 1000L);
    cmd.set("clockLimit", maxRealTime * 1000 * 1000L);
    // byte
    cmd.set("memoryLimit", maxMemory);
    cmd.set("procLimit", maxProcessNumber);
    cmd.set("stackLimit", maxStack);
    JSONObject fileContent = new JSONObject();
    fileContent.set("content", code);
    JSONObject copyIn = new JSONObject();
    copyIn.set(srcName, fileContent);
    if (extraFiles != null) {
        for (Map.Entry<String, String> entry : extraFiles.entrySet()) {
            if (!StringUtils.isEmpty(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                JSONObject content = new JSONObject();
                content.set("content", entry.getValue());
                copyIn.set(entry.getKey(), content);
            }
        }
    }
    cmd.set("copyIn", copyIn);
    cmd.set("copyOut", new JSONArray().put("stdout").put("stderr"));
    if (needCopyOutCached) {
        cmd.set("copyOutCached", new JSONArray().put(exeName));
    }
    if (needCopyOutExe) {
        cmd.set("copyOutDir", copyOutDir);
    }
    JSONObject param = new JSONObject();
    param.set("cmd", new JSONArray().put(cmd));
    JSONArray result = instance.run("/run", param);
    JSONObject tmp = (JSONObject) result.get(0);
    ((JSONObject) result.get(0)).set("status", RESULT_MAP_STATUS.get(tmp.getStr("status")));
    return result;
}
Also used : JSONObject(cn.hutool.json.JSONObject) JSONArray(cn.hutool.json.JSONArray) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with JSONArray

use of cn.hutool.json.JSONArray in project HOJ by HimitZH.

the class DefaultJudge method checkResult.

@Override
public JSONObject checkResult(SandBoxRes sandBoxRes, JudgeDTO judgeDTO, JudgeGlobalDTO judgeGlobalDTO) {
    JSONObject result = new JSONObject();
    StringBuilder errMsg = new StringBuilder();
    // 如果测试跑题无异常
    if (sandBoxRes.getStatus().equals(Constants.Judge.STATUS_ACCEPTED.getStatus())) {
        // 对结果的时间损耗和空间损耗与题目限制做比较,判断是否mle和tle
        if (sandBoxRes.getTime() > judgeGlobalDTO.getMaxTime()) {
            result.set("status", Constants.Judge.STATUS_TIME_LIMIT_EXCEEDED.getStatus());
        } else if (sandBoxRes.getMemory() > judgeGlobalDTO.getMaxMemory() * 1024) {
            result.set("status", Constants.Judge.STATUS_MEMORY_LIMIT_EXCEEDED.getStatus());
        } else {
            // 与原测试数据输出的md5进行对比 AC或者是WA
            JSONObject testcaseInfo = (JSONObject) ((JSONArray) judgeGlobalDTO.getTestCaseInfo().get("testCases")).get(judgeDTO.getTestCaseId() - 1);
            result.set("status", compareOutput(sandBoxRes.getStdout(), judgeGlobalDTO.getRemoveEOLBlank(), testcaseInfo));
        }
    } else if (sandBoxRes.getStatus().equals(Constants.Judge.STATUS_TIME_LIMIT_EXCEEDED.getStatus())) {
        result.set("status", Constants.Judge.STATUS_TIME_LIMIT_EXCEEDED.getStatus());
    } else if (sandBoxRes.getExitCode() != 0) {
        result.set("status", Constants.Judge.STATUS_RUNTIME_ERROR.getStatus());
        if (sandBoxRes.getExitCode() < 32) {
            errMsg.append(String.format("Your program return ExitCode: %s (%s)\n", sandBoxRes.getExitCode(), SandboxRun.signals.get(sandBoxRes.getExitCode())));
        } else {
            errMsg.append(String.format("Your program return ExitCode: %s\n", sandBoxRes.getExitCode()));
        }
    } else {
        result.set("status", sandBoxRes.getStatus());
    }
    // b
    result.set("memory", sandBoxRes.getMemory());
    // ns->ms
    result.set("time", sandBoxRes.getTime());
    // 记录该测试点的错误信息
    if (!StringUtils.isEmpty(errMsg.toString())) {
        String str = errMsg.toString();
        result.set("errMsg", str.substring(0, Math.min(1024 * 1024, str.length())));
    }
    if (judgeGlobalDTO.getNeedUserOutputFile()) {
        // 如果需要获取用户对于该题目的输出
        result.set("output", sandBoxRes.getStdout());
    }
    return result;
}
Also used : JSONObject(cn.hutool.json.JSONObject) JSONArray(cn.hutool.json.JSONArray)

Aggregations

JSONArray (cn.hutool.json.JSONArray)38 JSONObject (cn.hutool.json.JSONObject)29 FileWriter (cn.hutool.core.io.file.FileWriter)6 SystemError (top.hcode.hoj.common.exception.SystemError)5 Constants (top.hcode.hoj.util.Constants)5 Test (org.junit.Test)4 DateTime (cn.hutool.core.date.DateTime)3 FileReader (cn.hutool.core.io.file.FileReader)3 GuildedException (vip.floatationdevice.guilded4j.exception.GuildedException)3 File (java.io.File)2 Async (org.springframework.scheduling.annotation.Async)2 CompileError (top.hcode.hoj.common.exception.CompileError)2 SubmitError (top.hcode.hoj.common.exception.SubmitError)2 ProblemCase (top.hcode.hoj.pojo.entity.problem.ProblemCase)2 CollUtil (cn.hutool.core.collection.CollUtil)1 DateUtil (cn.hutool.core.date.DateUtil)1 UnicodeUtil (cn.hutool.core.text.UnicodeUtil)1 StrUtil (cn.hutool.core.util.StrUtil)1 HttpRequest (cn.hutool.http.HttpRequest)1 HttpResponse (cn.hutool.http.HttpResponse)1