jiangping
2023-10-09 e0f652dbea279b49b4b2d7acc328cca3d52c43c9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package com.doumee.core.utils;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Hex;
//import org.apache.commons.httpclient.HttpClient;
//import org.apache.commons.httpclient.NameValuePair;
//import org.apache.commons.httpclient.methods.PostMethod;
//import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;
 
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
 
public class HttpUtil {
    public static final String UTF8 = "UTF-8";
 
    /**
     * @param urlpath
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static String postRequestConn(String urlpath) throws UnsupportedEncodingException, IOException {
        String sendString = "";
 
        // 创建url对象
        URL url = new URL(urlpath);
 
        // 打开url连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        // 设置url请求方式 ‘get’ 或者 ‘post’
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(true);
        connection.setConnectTimeout(3000);
        connection.setReadTimeout(10000);
        connection.setRequestProperty("Charset", "UTF-8");
        int responseCode = connection.getResponseCode();
        if (HttpURLConnection.HTTP_OK == responseCode) {
            String readLine;
            BufferedReader responseReader;
            StringBuffer sb = new StringBuffer();
            responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            while ((readLine = responseReader.readLine()) != null) {
                sb.append(readLine).append("\n");
            }
            responseReader.close();
            sendString = sb.toString();
            // httpConn.disconnect();
        } else {
            System.out.println("error");
        }
 
        return sendString;
    }
 
    /**
     * @param urlPath
     * @param json
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static String postRequestConn(String urlPath, String json,String tokenStr) throws UnsupportedEncodingException, IOException {
        String sendString = "";
        // try {
        URL url;
        url = new URL(urlPath);
        HttpURLConnection httpConn;
        httpConn = (HttpURLConnection) url.openConnection();
        // httpConn.connect();
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setUseCaches(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestProperty("Content-Type", "application/json");
        httpConn.setRequestProperty("accept", "application/json");
        httpConn.setRequestProperty("X-Judge-Server-Token",getSHA256Str(tokenStr));
        httpConn.setConnectTimeout(10000);
        httpConn.setReadTimeout(10000);
        httpConn.connect();
        OutputStream out = httpConn.getOutputStream();
        byte[] data = (json.toString()).getBytes("UTF-8");
        out.write(data, 0, data.length);
        out.flush();
        out.close();
        int responseCode = httpConn.getResponseCode();
        if (HttpURLConnection.HTTP_OK == responseCode) {
            String readLine;
            BufferedReader responseReader;
            StringBuffer sb = new StringBuffer();
            responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
            while ((readLine = responseReader.readLine()) != null) {
                sb.append(readLine);
            }
            responseReader.close();
            sendString = sb.toString();
            // httpConn.disconnect();
        } else {
            System.out.println("error");
        }
        return sendString;
    }
 
    public static String doPost(String url,JSONObject json,String token) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        String response = null;
        try {
            post.addHeader("Content-Type", "application/json; charset=utf-8");
            post.addHeader("X-Judge-Server-Token",getSHA256Str(token));
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                response = EntityUtils.toString(entity);// 返回json格式:
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // System.out.print(response);
        return response;
    }
 
    //java对象转map
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }
//    public static String doFormPost(String url,JSONObject json) throws Exception{
//        String response = null;
//        HttpClient client = new HttpClient();
//        PostMethod postMethod = new PostMethod(url);
//        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
//        Map<String, Object>  params =objectToMap(json);
//        if(params !=null && params.get("map") !=null ){
//            HashMap<String,String> map = (HashMap<String, String>) params.get("map");
//            if(map !=null   && !map.isEmpty()){
//            NameValuePair[] data = new NameValuePair[map.size()];
//            int i =0;
//            for(Map.Entry<String,String> entry : map.entrySet()){
//                data[i] = new NameValuePair(entry.getKey(),entry.getValue());
//                i++;
//            }
//            postMethod.setRequestBody(data);
//            }
//        }
//        try {
//            client.executeMethod(postMethod);
//            if(postMethod.getStatusCode() == HttpStatus.SC_OK){
//                response = postMethod.getResponseBodyAsString();
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return response;
//    }
 
 
    public static void main(String[] args) throws IOException {
//        "language_config": sub_config["config"],
//                "src": code,
//                "max_cpu_time": self.problem.time_limit,
//                "max_memory": 1024 * 1024 * self.problem.memory_limit,
//                "test_case_id": self.problem.test_case_id,
//                "output": False,
//                "spj_version": self.problem.spj_version,
//                "spj_config": spj_config.get("config"),
//                "spj_compile_config": spj_config.get("compile"),
//                "spj_src": self.problem.spj_code,
//                "io_mode": self.problem.io_mode
/*
        {
            "template": "" ,
 
             "compile": {
            "src_name": "main.cpp",
                    "exe_name": "main",
                    "max_cpu_time": 10000,
                    "max_real_time": 20000,
                    "max_memory": 1024 * 1024 * 1024,
                    "compile_command": "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++14 {src_path} -lm -o {exe_path}",
        },
            "run": {
            "command": "{exe_path}",
                    "seccomp_rule": {ProblemIOMode.standard: "c_cpp", ProblemIOMode.file: "c_cpp_file_io"},
            "env": default_env
        }
 
        {"config": _cpp_lang_config, "spj": {"compile": _cpp_lang_spj_compile, "config": _cpp_lang_spj_config},
            "name": "C++", "description": "G++ 5.4", "content_type": "text/x-c++src"},*/
        JSONObject json =new JSONObject();
        JSONObject j = new JSONObject();
        JSONObject spj = new JSONObject();
        JSONObject sc = new JSONObject();
        sc.put("src_name","spj-{spj_version}.cpp");
        sc.put("exe_name","spj-{spj_version}");
        sc.put("max_cpu_time",10000);
        sc.put("max_real_time",20000);
        sc.put("max_memory",1024 * 1024 * 1024);
        sc.put("compile_command","/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++14 {src_path} -lm -o {exe_path}");
        spj.put("compile",sc);
        JSONObject scc = new JSONObject();
        scc.put("exe_name","spj-{spj_version}");
        scc.put("command","{exe_path} {in_file_path} {user_out_file_path}");
        scc.put("seccomp_rule","c_cpp");
        spj.put("config",scc);
        JSONObject compile = new JSONObject();
        compile.put("src_name", "main.cpp");
        compile.put("exe_name", "main");
        compile.put("max_cpu_time", 10000);
        compile.put("max_real_time", 20000);
        compile.put("max_memory",1024 * 1024 * 1024);
        compile.put("compile_command", "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++14 {src_path} -lm -o {exe_path}");
        JSONObject run = new JSONObject();
        JSONObject sr = new JSONObject();
        sr.put("Standard IO","c_cpp");
        sr.put("File IO","c_cpp_file_io");
        run.put("command", "{exe_path}");
        run.put("seccomp_rule", sr);
        run.put("env",new  String[]{"LANG=en_US.UTF-8", "LANGUAGE=en_US:en", "LC_ALL=en_US.UTF-8"});
        JSONObject config = new JSONObject();
        config.put("template","//PREPEND BEGIN\n" +
                "#include <iostream>\n" +
                "//PREPEND END\n" +
                "\n" +
                "//TEMPLATE BEGIN\n" +
                "int add(int a, int b) {\n" +
                "  // Please fill this blank\n" +
                "  return ___________;\n" +
                "}\n" +
                "//TEMPLATE END\n" +
                "\n" +
                "//APPEND BEGIN\n" +
                "int main() {\n" +
                "  std::cout << add(1, 2);\n" +
                "  return 0;\n" +
                "}\n" +
                "//APPEND END");
        config.put("run",run);
        config.put("compile",compile);
 
        j.put("name","C++");
        j.put("description","G++ 5.4");
        j.put("content_type","text/x-c++src");
        j.put("config",config);
        j.put("spj",spj);
 
        json.put("language_config",j.get("config"));
        json.put("src","#include <stdio.h> // puts     \n" +
                "int main(){\n" +
                "  puts(\"Hello,World!\");// 输出\n" +
                "}");
        json.put("max_cpu_time",1000);
        json.put("max_memory",1024*1024*64);
        json.put("test_case_id","2b7e2f6a801b6c00388e717ae11b6f57");
//        json.put("output",Boolean.FALSE);
//        json.put("spj_version","");
//        json.put("spj_config","");
//        json.put("spj_compile_config","");
//        json.put("spj_src","");
//        json.put("io_mode","{\"input\": \"input.in\", \"output\": \"output.out\", \"io_mode\": \"Standard IO\"}");
 
        System.out.println(json.toJSONString());
        System.out.println(postRequestConn("http://47.100.55.21:8080/judge",json.toJSONString(),"3c8e8bd79d66259c46d8a3d057278dc8"));
    }
 
    public static String getSHA256Str(String str) {
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encdeStr;
    }
 
 
 
    /**
     * 下载二维码图片文件,
     * 
     * @param urlString
     * @return 临时文件夹地址
     * @throws Exception
     */
 
    public static String downloadQrcode(String urlString) throws Exception {
        String savePath = System.getProperty("java.io.tmpdir");
        String nfix = ".jpg";// 文件后缀名
        String tempName = UUID.randomUUID().toString() + nfix;// 临时文件名
 
        // ----------------图片下载开始---------------
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 设置请求超时为5s
        con.setConnectTimeout(5 * 1000);
        // 输入流
        InputStream is = con.getInputStream();
 
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf = new File(savePath);
        if (!sf.exists()) {
            sf.mkdirs();
        }
        String tempFilePath = sf.getPath() + "\\" + tempName;
        OutputStream os = new FileOutputStream(tempFilePath);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕,关闭所有链接
        os.close();
        is.close();
        // -------------------图片下载完毕------------------
 
        return tempFilePath;
    }
}