REST 03: Goals

Rest Consumer

import java.io.*;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.net.MalformedURLException;
import java.net.ProtocolException;

//import org.json.JSONObject;

public class TeamGoals {

    private static final String MATCH_URL = "https://jsonmock.hackerrank.com/api/football_matches"; 

    public static int getTotalGoals(String team, int year) {

    	try {
	        String team1Url = String.format(MATCH_URL+"?year=%d&team1=%s", year, URLEncoder.encode(team,"UTF-8"));
	        String team2Url = String.format(MATCH_URL+"?year=%d&team2=%s", year, URLEncoder.encode(team,"UTF-8"));
	        
	        return getTeamGoals(team1Url,"team1", 1,0) + getTeamGoals(team2Url,"team2", 1,0);
    	} catch (Exception e) {
    		
    		
    	}
    	return 0;

    }
    
    private static int getTeamGoals(String endpoint, String teamnum, int page, int totalGoals) throws Exception {
        String response = getResponseByPage(endpoint, page);
        
        JsonObject jsonResponse = new Gson().fromJson(response, JsonObject.class);
        int totalPages = jsonResponse.get("total_pages").getAsInt();
        JsonArray data = jsonResponse.getAsJsonArray("data");
        for(JsonElement el : data) {
            totalGoals += el.getAsJsonObject().get(teamnum+"goals").getAsInt();    
        }
        page = page+1;
        while(totalPages >= page) {
            response = getResponseByPage(endpoint, page);
            jsonResponse = new Gson().fromJson(response, JsonObject.class);
            data = jsonResponse.getAsJsonArray("data");
            for(JsonElement el : data) {
                totalGoals += el.getAsJsonObject().get(teamnum+"goals").getAsInt();    
            }
            page++;
        }
        
        return totalGoals;
        
    } 
    
    private static String getResponseByPage(String endpoint, int page) throws MalformedURLException, IOException, ProtocolException {
        
        URL url = new URL(endpoint+"&page="+page);
        HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
        con.setRequestMethod("GET");
        con.addRequestProperty("Content-Type", "application/json");
        
        int status = con.getResponseCode();
        if(status<200 || status>=300) {
            throw new IOException("Error HTTP status: "+status);
        }        
        
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String response;
        StringBuilder sb = new StringBuilder();
        while((response = br.readLine())!=null) {
            sb.append(response);
        }
        
        br.close();
        con.disconnect();
        
        return sb.toString();    
        
    }	
}

Runner

import java.io.*;

public class Runner {
    public static void main(String[] args) throws IOException {
        //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        //BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        //String team = bufferedReader.readLine();

        //int year = Integer.parseInt(bufferedReader.readLine().trim());

    	String team = "Barcelona";
    	int year = 2011;
    	
        int result = TeamGoals.getTotalGoals(team, year);

        
        System.out.println(result);
        //bufferedWriter.write(String.valueOf(result));
        //bufferedWriter.newLine();

        //bufferedReader.close();
        //bufferedWriter.close();
    }
}

Other - goals winner

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 java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.net.MalformedURLException;
import java.net.ProtocolException;

class Result {

    /*
     * Complete the 'getWinnerTotalGoals' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. STRING competition
     *  2. INTEGER year
     */
     
    private static final String MATCH_URL = "https://jsonmock.hackerrank.com/api/football_matches";  

    private static final String COMPETITION_URL = "https://jsonmock.hackerrank.com/api/football_competitions"; 

    public static int getWinnerTotalGoals(String competition, int year) throws Exception {
        
        try {
        String teamName = getWinnerTeamName(competition,year);
        
        String team1Url = String.format(MATCH_URL+"?competition=%s&year=%d&team1=%s",URLEncoder.encode(competition,"UTF-8"), year, URLEncoder.encode(teamName,"UTF-8"));
        String team2Url = String.format(MATCH_URL+"?competition=%s&year=%d&team2=%s",URLEncoder.encode(competition,"UTF-8"), year, URLEncoder.encode(teamName,"UTF-8")); 
        
        return getTeamGoals(team1Url,"team1", 1,0) + getTeamGoals(team2Url,"team2", 1,0);
        } catch (Exception e) {            
            System.out.println("Error Exception: "+e.toString());
            return 0;
        }       
        

    }
    
    private static String getWinnerTeamName(String competition, int year) throws Exception 
    {   
        String url = String.format(COMPETITION_URL+"?year=%d&name=%s", year, URLEncoder.encode(competition,"UTF-8"));
        
        String response = getResponseByPage(url, 1);
        
        JsonObject jsonResponse = new Gson().fromJson(response, JsonObject.class);
        JsonElement e = jsonResponse.getAsJsonArray("data").get(0);
        
        return e.getAsJsonObject().get("winner").getAsString();
    }     
    
    
    private static int getTeamGoals(String endpoint, String teamnum, int page, int totalGoals) throws Exception {
        String response = getResponseByPage(endpoint, page);
        
        JsonObject jsonResponse = new Gson().fromJson(response, JsonObject.class);
        int totalPages = jsonResponse.get("total_pages").getAsInt();
        JsonArray data = jsonResponse.getAsJsonArray("data");
        for(JsonElement el : data) {
            totalGoals += el.getAsJsonObject().get(teamnum+"goals").getAsInt();    
        }
        page = page+1;
        while(totalPages >= page) {
            response = getResponseByPage(endpoint, page);
            jsonResponse = new Gson().fromJson(response, JsonObject.class);
            data = jsonResponse.getAsJsonArray("data");
            for(JsonElement el : data) {
                totalGoals += el.getAsJsonObject().get(teamnum+"goals").getAsInt();    
            }
            page++;
        }
        
        return totalGoals;
        
    } 
    
    private static String getResponseByPage(String endpoint, int page) throws MalformedURLException, IOException, ProtocolException {
        
        URL url = new URL(endpoint+"&page="+page);
        HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
        con.setRequestMethod("GET");
        con.addRequestProperty("Content-Type", "application/json");
        
        int status = con.getResponseCode();
        if(status<200 || status>=300) {
            throw new IOException("Error HTTP status: "+status);
        }        
        
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String response;
        StringBuilder sb = new StringBuilder();
        while((response = br.readLine())!=null) {
            sb.append(response);
        }
        
        br.close();
        con.disconnect();
        
        return sb.toString();    
        
    }    
    
    
    

}
public class Solution {
    public static void main(String[] args) throws IOException, Exception {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String competition = bufferedReader.readLine();

        int year = Integer.parseInt(bufferedReader.readLine().trim());

        int result = Result.getWinnerTotalGoals(competition, year);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}