use of cn.hutool.http.HttpRequest 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;
}
use of cn.hutool.http.HttpRequest in project HOJ by HimitZH.
the class CodeForcesJudge method submitCode.
public void submitCode(RemoteJudgeDTO remoteJudgeDTO) {
String csrfToken = getCsrfToken(getSubmitUrl(remoteJudgeDTO.getContestId()));
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("csrf_token", csrfToken);
paramMap.put("_tta", 140);
paramMap.put("bfaa", "f1b3f18c715565b589b7823cda7448ce");
paramMap.put("ftaa", "");
paramMap.put("action", "submitSolutionFormSubmitted");
paramMap.put("submittedProblemIndex", remoteJudgeDTO.getProblemNum());
paramMap.put("contestId", remoteJudgeDTO.getContestId());
paramMap.put("programTypeId", getLanguage(remoteJudgeDTO.getLanguage()));
paramMap.put("tabsize", 4);
paramMap.put("source", remoteJudgeDTO.getUserCode() + getRandomBlankString());
paramMap.put("sourceCodeConfirmed", true);
paramMap.put("doNotShowWarningAgain", "on");
HttpRequest request = HttpUtil.createPost(getSubmitUrl(remoteJudgeDTO.getContestId()) + "?csrf_token=" + csrfToken);
request.setConnectionTimeout(60000);
request.setReadTimeout(60000);
request.form(paramMap);
request.cookie(remoteJudgeDTO.getCookies());
request.header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36");
HttpResponse response = request.execute();
remoteJudgeDTO.setSubmitStatus(response.getStatus());
if (response.getStatus() != HttpStatus.SC_MOVED_TEMPORARILY) {
if (response.body().contains("error for__programTypeId")) {
String log = String.format("Codeforces[%s] [%s]:Failed to submit code, caused by `Language Rejected`", remoteJudgeDTO.getContestId(), remoteJudgeDTO.getProblemNum());
throw new RuntimeException(log);
}
if (response.body().contains("error for__source")) {
String log = String.format("Codeforces[%s] [%s]:Failed to submit code, caused by `Source Code Error`", remoteJudgeDTO.getContestId(), remoteJudgeDTO.getProblemNum());
throw new RuntimeException(log);
}
}
}
use of cn.hutool.http.HttpRequest in project HOJ by HimitZH.
the class SPOJJudge method login.
@Override
public void login() {
RemoteJudgeDTO remoteJudgeDTO = getRemoteJudgeDTO();
HttpRequest request = HttpUtil.createPost(HOST + LOGIN_URL);
HttpResponse response = request.form(MapUtil.builder(new HashMap<String, Object>()).put("login_user", remoteJudgeDTO.getUsername()).put("autologin", "1").put("submit", "Log In").put("password", remoteJudgeDTO.getPassword()).map()).execute();
remoteJudgeDTO.setLoginStatus(response.getStatus()).setCookies(response.getCookies());
}
use of cn.hutool.http.HttpRequest in project HOJ by HimitZH.
the class SPOJJudge method submit.
@Override
public void submit() {
RemoteJudgeDTO remoteJudgeDTO = getRemoteJudgeDTO();
if (remoteJudgeDTO.getCompleteProblemId() == null || remoteJudgeDTO.getUserCode() == null) {
return;
}
login();
List<HttpCookie> cookies = remoteJudgeDTO.getCookies();
HttpRequest request = HttpUtil.createPost(HOST + SUBMIT_URL).cookie(cookies);
HttpResponse response = request.form(MapUtil.builder(new HashMap<String, Object>()).put("lang", getLanguage(remoteJudgeDTO.getLanguage())).put("problemcode", remoteJudgeDTO.getCompleteProblemId()).put("file", remoteJudgeDTO.getUserCode()).map()).execute();
remoteJudgeDTO.setSubmitStatus(response.getStatus());
if (response.body().contains("submit in this language for this problem")) {
throw new RuntimeException("Language Error");
} else if (response.body().contains("Wrong problem code!")) {
throw new RuntimeException("Wrong problem code!");
} else if (response.body().contains("solution is too long")) {
throw new RuntimeException("Code Length Exceeded");
}
String runId = ReUtil.get("name=\"newSubmissionId\" value=\"(\\d+)\"", response.body(), 1);
if (runId == null) {
remoteJudgeDTO.setSubmitId(-1L);
} else {
remoteJudgeDTO.setSubmitId(Long.parseLong(runId));
}
}
use of cn.hutool.http.HttpRequest in project fast-request by dromara.
the class FastRequestToolWindow method sendRequestEvent.
public void sendRequestEvent(boolean fileMode) {
if (!sendButtonFlag) {
return;
}
sendButtonFlag = false;
try {
FastRequestConfiguration config = FastRequestComponent.getInstance().getState();
assert config != null;
NameGroup defaultNameGroup = new NameGroup(StringUtils.EMPTY, new ArrayList<>());
HostGroup defaultHostGroup = new HostGroup(StringUtils.EMPTY, StringUtils.EMPTY);
String domain = config.getDataList().stream().filter(n -> n.getName().equals(projectComboBox.getSelectedItem())).findFirst().orElse(defaultNameGroup).getHostGroup().stream().filter(h -> h.getEnv().equals(envComboBox.getSelectedItem())).findFirst().orElse(defaultHostGroup).getUrl();
String sendUrl = urlTextField.getText();
if (StringUtils.isBlank(domain) || !UrlUtil.isURL(domain + sendUrl)) {
ApplicationManager.getApplication().invokeLater(() -> {
((MyLanguageTextField) responseTextAreaPanel).setText("Correct url required");
});
tabbedPane.setSelectedIndex(4);
responseTabbedPanel.setSelectedIndex(2);
sendButtonFlag = true;
((MyLanguageTextField) prettyJsonEditorPanel).setText("");
return;
}
String methodType = (String) methodTypeComboBox.getSelectedItem();
HttpRequest request = HttpUtil.createRequest(Method.valueOf(methodType), domain + sendUrl);
request.setMaxRedirectCount(10);
headerParamsKeyValueList = headerParamsKeyValueList == null ? new ArrayList<>() : headerParamsKeyValueList;
List<DataMapping> globalHeaderList = config.getGlobalHeaderList();
globalHeaderList = globalHeaderList == null ? new ArrayList<>() : globalHeaderList;
Map<String, List<String>> globalHeaderMap = globalHeaderList.stream().filter(DataMapping::getEnabled).collect(Collectors.toMap(DataMapping::getType, p -> Lists.newArrayList(p.getValue()), (existing, replacement) -> existing));
Map<String, List<String>> headerMap = headerParamsKeyValueList.stream().filter(DataMapping::getEnabled).collect(Collectors.toMap(DataMapping::getType, p -> Lists.newArrayList(p.getValue()), (existing, replacement) -> existing));
globalHeaderMap.putAll(headerMap);
request.header(globalHeaderMap);
Map<String, Object> multipartFormParam = multipartKeyValueList.stream().filter(ParamKeyValue::getEnabled).collect(HashMap::new, (m, v) -> {
Object value = v.getValue();
String key = v.getKey();
if (TypeUtil.Type.File.name().equals(v.getType())) {
if (value != null && !StringUtils.isBlank(value.toString())) {
m.put(key, new File(value.toString()));
} else {
m.put(key, null);
}
} else {
m.put(key, value);
}
}, HashMap::putAll);
Map<String, Object> urlParam = urlParamsKeyValueList.stream().filter(ParamKeyValue::getEnabled).collect(Collectors.toMap(ParamKeyValue::getKey, ParamKeyValue::getValue, (existing, replacement) -> existing));
String jsonParam = ((LanguageTextField) jsonParamsTextArea).getText();
Map<String, Object> formMap = new HashMap<>();
urlEncodedKeyValueList.stream().filter(ParamKeyValue::getEnabled).forEach(q -> {
formMap.put(q.getKey(), q.getValue());
});
boolean formFlag = true;
// json优先
if (!formMap.isEmpty()) {
request.form(formMap);
formFlag = false;
}
if (StringUtils.isNotEmpty(jsonParam)) {
request.body(JSON.toJSONString(JSON.parse(jsonParam)));
formFlag = false;
}
if (!urlParam.isEmpty()) {
String queryParam = UrlQuery.of(urlParam).build(StandardCharsets.UTF_8);
request.setUrl(request.getUrl() + "?" + queryParam);
}
if (!multipartFormParam.isEmpty() && formFlag) {
request.form(multipartFormParam);
}
FileSaverDialog fd = null;
if (fileMode) {
fd = FileChooserFactory.getInstance().createSaveFileDialog(new FileSaverDescriptor("Save As", ""), myProject);
}
FileSaverDialog finalFd = fd;
requestProgressBar.setVisible(true);
requestProgressBar.setForeground(ColorProgressBar.GREEN);
Future<?> future = ThreadUtil.execAsync(() -> {
try {
long start = System.currentTimeMillis();
HttpResponse response = request.execute();
long end = System.currentTimeMillis();
ApplicationManager.getApplication().invokeLater(() -> {
tabbedPane.setSelectedIndex(4);
String duration = String.valueOf(end - start);
requestProgressBar.setVisible(false);
int status = response.getStatus();
// download file
if (fileMode && status >= 200 && status < 300) {
((MyLanguageTextField) prettyJsonEditorPanel).setText("");
((MyLanguageTextField) responseTextAreaPanel).setText("");
Task.Backgroundable task = new Task.Backgroundable(myProject, "Saving file...") {
@Override
public void run(@NotNull ProgressIndicator indicator) {
ApplicationManager.getApplication().invokeLater(() -> {
sendButtonFlag = false;
try {
File f = new File(myProject.getBasePath());
File finalFile = response.completeFileNameFromHeader(f);
response.writeBody(finalFile);
VirtualFileWrapper fileWrapper = finalFd.save(finalFile.getName());
if (fileWrapper != null) {
File file = fileWrapper.getFile();
FileUtil.move(finalFile, file, true);
NotificationGroupManager.getInstance().getNotificationGroup("toolWindowNotificationGroup").createNotification("Success", MessageType.INFO).addAction(new GotoFile(file)).notify(myProject);
}
finalFile.delete();
} catch (Exception ignored) {
}
sendButtonFlag = true;
});
}
};
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, new BackgroundableProcessIndicator(task));
}
if (!fileMode) {
String body = response.body();
int bodyLength = StrUtil.byteLength(body, StandardCharsets.UTF_8);
if (bodyLength > MAX_DATA_LENGTH) {
((MyLanguageTextField) responseTextAreaPanel).setText(body);
((MyLanguageTextField) prettyJsonEditorPanel).setText(body);
refreshResponseTable("");
} else {
if (JSONUtil.isJson(body)) {
responseTabbedPanel.setSelectedIndex(1);
((MyLanguageTextField) prettyJsonEditorPanel).setText(body.isBlank() ? "" : body);
((MyLanguageTextField) responseTextAreaPanel).setText(body);
refreshResponseTable(body);
} else {
responseTabbedPanel.setSelectedIndex(2);
String subBody = body.substring(0, Math.min(body.length(), 32768));
if (body.length() > 32768) {
subBody += "\n\ntext too large only show 32768 characters\n.............";
}
String finalSubBody = subBody;
((MyLanguageTextField) prettyJsonEditorPanel).setText(finalSubBody);
((MyLanguageTextField) responseTextAreaPanel).setText(subBody);
refreshResponseTable("");
}
}
}
responseInfoParamsKeyValueList = Lists.newArrayList(new ParamKeyValue("Url", request.getUrl(), 2, TypeUtil.Type.String.name()), new ParamKeyValue("Cost", duration + " ms", 2, TypeUtil.Type.String.name()), new ParamKeyValue("Response status", status + " " + Constant.HttpStatusDesc.STATUS_MAP.get(status)), new ParamKeyValue("Date", DateUtil.formatDateTime(new Date())));
// refreshTable(responseInfoTable);
responseInfoTable.setModel(new ListTableModel<>(getColumns(Lists.newArrayList("Name", "Value")), responseInfoParamsKeyValueList));
responseInfoTable.getColumnModel().getColumn(0).setPreferredWidth(150);
responseInfoTable.getColumnModel().getColumn(0).setMaxWidth(150);
responseStatusComboBox.setSelectedItem(status);
responseStatusComboBox.setBackground((status >= 200 && status < 300) ? MyColor.green : MyColor.red);
}, ModalityState.NON_MODAL);
} catch (Exception ee) {
sendButtonFlag = true;
requestProgressBar.setVisible(false);
tabbedPane.setSelectedIndex(4);
responseTabbedPanel.setSelectedIndex(2);
responseStatusComboBox.setSelectedItem(0);
String errorMsg = ee.getMessage();
ApplicationManager.getApplication().invokeLater(() -> {
((MyLanguageTextField) responseTextAreaPanel).setText(errorMsg);
((MyLanguageTextField) prettyJsonEditorPanel).setText("");
});
responseStatusComboBox.setBackground(MyColor.red);
responseInfoParamsKeyValueList = Lists.newArrayList(new ParamKeyValue("Url", request.getUrl(), 2, TypeUtil.Type.String.name()), new ParamKeyValue("Error", errorMsg));
// refreshTable(responseInfoTable);
responseInfoTable.setModel(new ListTableModel<>(getColumns(Lists.newArrayList("Name", "Value")), responseInfoParamsKeyValueList));
responseInfoTable.getColumnModel().getColumn(0).setPreferredWidth(150);
responseInfoTable.getColumnModel().getColumn(0).setMaxWidth(150);
CustomNode root = new CustomNode("Root", "");
((DefaultTreeModel) responseTable.getTableModel()).setRoot(root);
}
sendButtonFlag = true;
});
} catch (Exception exception) {
sendButtonFlag = true;
requestProgressBar.setVisible(false);
String errorMsg = exception.getMessage();
ApplicationManager.getApplication().invokeLater(() -> {
((MyLanguageTextField) responseTextAreaPanel).setText(errorMsg);
((MyLanguageTextField) prettyJsonEditorPanel).setText("");
});
responseStatusComboBox.setSelectedItem(0);
responseStatusComboBox.setBackground(MyColor.red);
responseInfoParamsKeyValueList = Lists.newArrayList(new ParamKeyValue("Error", errorMsg));
// refreshTable(responseInfoTable);
responseInfoTable.setModel(new ListTableModel<>(getColumns(Lists.newArrayList("Name", "Value")), responseInfoParamsKeyValueList));
responseInfoTable.getColumnModel().getColumn(0).setPreferredWidth(150);
responseInfoTable.getColumnModel().getColumn(0).setMaxWidth(150);
CustomNode root = new CustomNode("Root", "");
((DefaultTreeModel) responseTable.getTableModel()).setRoot(root);
tabbedPane.setSelectedIndex(4);
responseTabbedPanel.setSelectedIndex(2);
}
}
Aggregations