Spring Boot How To Retrieve Data For Corona Statistics Real-Time

5
389
Spread the love

Spring Boot Hoe real-time gegevens voor Corona- statistieken op te halen:

Gegevens in CSV-formattering zijn afkomstig van: 

https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv

We zullen AngularJs gebruiken om gegevens op de webpagina weer te geven.

package com.example.TestSpringBoot;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.StringReader;
import java.net.http.HttpClient;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;


@Service
public class CoronaServices {
  private static String CORONA_VIRUS_API =
          "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
  private List<Entity> alldata = new ArrayList<>();

@PostConstruct
@Scheduled(cron="* * 1 * * *")
public List<Entity> fetchDataFromCSV() throws IOException, InterruptedException {
    List<Entity> newList = new ArrayList<>();
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder().uri(URI.create(CORONA_VIRUS_API)).build();
    HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
    // System.out.println(httpResponse.body());
     StringReader csvReader = new StringReader(httpResponse.body());
     Iterable<CSVRecord> csv = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(csvReader);
     for(CSVRecord record : csv){
        Entity e = new Entity();
        e.setCountry(record.get("Country/Region"));
        e.setProvince("Province/State");
        e.setTotal(String.valueOf(Integer.parseInt(record.get(record.size() - 1))));
        System.out.println(e);
         newList.add(e);
     }
     this.alldata = newList;
    return newList;
}
}
package com.example.TestSpringBoot;

public class Entity {

    private String province;
    private String country;
    private String total;

    public Entity(String province, String country, String total) {
        this.province = province;
        this.country = country;
        this.total = total;
    }

    public Entity(){}

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    @Override
    public String toString() {
        return "Entity{" +
                "province='" + province + '\'' +
                ", country='" + country + '\'' +
                ", total='" + total + '\'' +
                '}';
    }
}
package com.example.TestSpringBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestSpringBootApplication {

	public static void main(String[] args) {
		SpringApplication.run(TestSpringBootApplication.class, args);
	}

}
package com.example.TestSpringBoot;

import com.example.Exception.ApiRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;

@RestController
public class Controller {

    @Autowired
    private CoronaServices coronaServices ;

    @GetMapping("/")
    public String test(){
        return "home";
    }

    @GetMapping("/test")
    public List <Entity> fetchData() throws IOException, InterruptedException {
        return coronaServices.fetchDataFromCSV();
    }
}
<!DOCTYPE html>
<html  ng-app="">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
	<div>
<style>
  h1{
    color:red;
  }

  body{
    bgcolor:black;
  }
</style>
	<h1>Fetch API GET REQUEST | CORONA_VIRUS_API </h1>

	<!-- Table to display fetched user data -->
	<table id="test"></table>
	</div>
	<!-- Link JavaScript file -->
	<script>
  // GET request using fetch()
  fetch("http://localhost:8080/test")
  	// Converting received data to JSON
  	.then(response => response.json())
  	.then(json =>{
  		// Create a variable to store HTML
  		let li = `<tr><th>COUNTRY</th><th>CASES</th><th>FLAG</th></tr>`;
  		// Loop through each data and add a table row
  		json.forEach(test => {
  			li += `<tr>
          <td>${test.country}</td>
  				<td>${test.total} </td>

  			</tr>`;
  		});
  	// Display result
  	document.getElementById("test").innerHTML = li;
  });
  </script>
</body>
</html>

5 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here