-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathGetRequestCall.java
More file actions
79 lines (64 loc) · 2.59 KB
/
GetRequestCall.java
File metadata and controls
79 lines (64 loc) · 2.59 KB
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
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import javax.script.*;
import java.net.*;
class Result {
/*
* Complete the 'getNumDraws' function below
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER year as parameter.
*/
public static int getNumDraws(int year) throws IOException{
final String endPoint = "https://jsonmock.hackerrank.com/api/football_matches?year="+year;
final int maxScore = 10;
int totalNumDraws = 0;
for(int score=0; score<= maxScore; score++){
totalNumDraws+=getTotalNumDraws(String.format(endPoint + "&team1goals=%d&team2goals=%d", score, score));
}
return totalNumDraws;
}
private static int getTotalNumDraws(String request) throws IOException{
URL url = new URL(request);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
httpURLConnection.addRequestProperty("Content-Type", "application/json");
int status = httpURLConnection.getResponseCode();
InputStream in = (status < 200 || status > 299) ? httpURLConnection.getErrorStream() : httpURLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String responseLine;
StringBuffer responseContent = new StringBuffer();
while((responseLine = br.readLine()) != null){
responseContent.append(responseLine);
}
br.close();
httpURLConnection.disconnect();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
String script = "var obj = JSON.parse('" + responseContent.toString() + "');";
script+="var total = obj.total;";
try{
engine.eval(script);
}catch(ScriptException ex){
ex.printStackTrace();
}
if(null == engine.get("total")){
throw new RuntimeException("Can't retrieve data !!!");
}
return (int) engine.get("total");
}
}
public class Solution {
// Some trivial code here
}