Corona virus Spring application Example

  • By Greg Eke
  • 17 Oct, 2019
Corona virus Spring application Example

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore

package com.pintofcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories
@SpringBootApplication
public class AppApplication {

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

}
package com.pintofcode;

import lombok.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
@Entity
@EntityListeners(AuditingEntityListener.class)

public class Corona implements Serializable {

    @Id
    @Column(name="id", updatable=false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    String combinedKey;

    Long active;

    Long activeChanges;

    Long recovered;

    Long recoveredChanges;

    Long confirmed;

    Long confirmedChanges;

    LocalDateTime lastUpdate;
}

package com.pintofcode;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface CoronaRepository extends JpaRepository<Corona, Long> {
    List<Corona> findByLastUpdateBetween(LocalDateTime from, LocalDateTime to);

    List<Corona> findByCombinedKey(String combinedKey);
}
import com.opencsv.CSVReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
public class CoronaService {

    CoronaRepository coronaRepository;

    public CoronaService(CoronaRepository coronaRepository) {
        this.coronaRepository = coronaRepository;
    }

    public void save (Corona corona){
        coronaRepository.save(corona);
    }

    @Scheduled(cron = "0 4 * * *")
    public void populateDatabase() throws IOException {
        URL url = new URL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/06-07-2020.csv");
        HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        int responseCode = huc.getResponseCode();

        log.info(String.valueOf(huc.getResponseCode()));
        if(responseCode == 200){
            log.info("-- Successfully connected to Github --");

            CSVReader reader = null;
            try {
                BufferedReader input = new BufferedReader(new InputStreamReader(huc.getInputStream()), 8192);
                reader = new CSVReader(input);
                String[] line;
                int i = 0;
                while ((line = reader.readNext()) != null) {
                    if(i == 0){
                        i++;
                        continue;
                    }

                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                    Corona corona = new Corona();
                    corona.setLastUpdate(LocalDateTime.parse(line[4], formatter));
                    corona.setConfirmed(Long.valueOf(line[7]));
                    corona.setRecovered(Long.valueOf(line[9]));
                    corona.setActive(Long.valueOf(line[10]));
                    corona.setCombinedKey(line[11]);

                    List<Corona> coronaList = findByCombinedKey(corona.getCombinedKey());
                    if(!coronaList.isEmpty()){
                        corona.setConfirmedChanges(corona.getConfirmed() - coronaList.get(coronaList.size() - 1).getConfirmed());
                        corona.setRecoveredChanges(corona.getRecovered() - coronaList.get(coronaList.size() - 1).getRecovered());
                        corona.setActiveChanges(corona.getActive() - coronaList.get(coronaList.size() - 1).getActive());
                    }

                    coronaRepository.save(corona);
                    log.info(corona.toString());

                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally { // closing the reader in the finally block
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    public void populateDatabase2() throws IOException {
        URL url = new URL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/06-06-2020.csv");
        HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        int responseCode = huc.getResponseCode();

        log.info(String.valueOf(huc.getResponseCode()));
        if(responseCode == 200){
            log.info("-- Successfully connected to Github --");

            CSVReader reader = null;
            try {
                BufferedReader input = new BufferedReader(new InputStreamReader(huc.getInputStream()), 8192);
                reader = new CSVReader(input);
                String[] line;
                int i = 0;
                while ((line = reader.readNext()) != null) {
                    if(i == 0){
                        i++;
                        continue;
                    }

                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                    Corona corona = new Corona();
                    corona.setLastUpdate(LocalDateTime.parse(line[4], formatter));
                    corona.setConfirmed(Long.valueOf(line[7]));
                    corona.setRecovered(Long.valueOf(line[9]));
                    corona.setActive(Long.valueOf(line[10]));
                    corona.setCombinedKey(line[11]);

                    List<Corona> coronaList = findByCombinedKey(corona.getCombinedKey());
                    if(!coronaList.isEmpty()){
                        corona.setConfirmedChanges(corona.getConfirmed() - coronaList.get(coronaList.size() - 1).getConfirmed());
                        corona.setRecoveredChanges(corona.getRecovered() - coronaList.get(coronaList.size() - 1).getRecovered());
                        corona.setActiveChanges(corona.getActive() - coronaList.get(coronaList.size() - 1).getActive());
                    }

                    coronaRepository.save(corona);
                    log.info(corona.toString());

                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally { // closing the reader in the finally block
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    private List<Corona> findByCombinedKey(String combinedKey) {
        return coronaRepository.findByCombinedKey(combinedKey);
    }

    public List<Corona> findByLastUpdate(LocalDate localDate) {
        return coronaRepository.findByLastUpdateBetween(LocalDateTime.of(localDate, LocalTime.MIN), LocalDateTime.of(localDate, LocalTime.MAX));
    }

    public List<Corona> findAll() {
        return coronaRepository.findAll();
    }
}
package com.example.app;

import com.opencsv.CSVReader;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Controller
public class MainController {

    CoronaService coronaService;

    public MainController(CoronaService coronaService) {
        this.coronaService = coronaService;
    }

    @GetMapping("/test")
    public String testMethod (Model model) throws IOException {
        model.addAttribute("test1", "Hello user");
        coronaService.populateDatabase2();
        coronaService.populateDatabase();
        return "mainTemplate";
    }

    @GetMapping("/")
    public String root (Model model) throws IOException {
        model.addAttribute("coronaData", coronaService.findByLastUpdate(LocalDate.now()));
        return "mainTemplate";
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Corona Tracker</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">

</head>
<body>
    <nav class="teal">
        <div class="nav-wrapper">
            <a href="#" class="brand-logo center">Corona tracker</a>
        </div>
    </nav>

    <div class="container">
        <table id="corona-table" class="striped">
            <thead>
                <tr>
                    <th>Place</th>
                    <th>Confirmed</th>
                    <th>Confirmed changes</th>
                    <th>Active</th>
                    <th>Active changes</th>
                    <th>Recovered</th>
                    <th>Recovered changes</th>
                </tr>
            </thead>
            <tbody>
                <tr th:each="corona : ${coronaData}">
                    <td><p th:text="${corona.combinedKey}"></p></td>
                    <td th:text="${corona.confirmed}"></td>

                    <td>
                        <span th:if="${corona.confirmedChanges > 0 }" th:text="${'+' + corona.confirmedChanges}" class="badge red white-text"></span>
                        <span th:if="${corona.confirmedChanges == 0 }" th:text="${corona.confirmedChanges}" class="badge grey black-text"></span>
                        <span th:if="${corona.confirmedChanges < 0 }" th:text="${corona.confirmedChanges}" class="badge teal white-text"></span>
                    </td>
                    <td th:text="${corona.active}"></td>
                    <td>
                        <span th:if="${corona.activeChanges > 0 }" th:text="${'+' + corona.activeChanges}" class="badge red white-text"></span>
                        <span th:if="${corona.activeChanges == 0 }" th:text="${corona.activeChanges}" class="badge grey black-text"></span>
                        <span th:if="${corona.activeChanges < 0 }" th:text="${corona.activeChanges}" class="badge teal white-text"></span>
                    </td>
                    <td th:text="${corona.recovered}"></td>
                    <td>
                        <span th:if="${corona.recoveredChanges > 0 }" th:text="${'+' + corona.recoveredChanges}" class="badge red white-text"></span>
                        <span th:if="${corona.recoveredChanges == 0 }" th:text="${corona.recoveredChanges}" class="badge grey black-text"></span>
                        <span th:if="${corona.recoveredChanges < 0 }" th:text="${corona.recoveredChanges}" class="badge teal white-text"></span>
                    </td>

                </tr>
            </tbody>
        </table>

    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

    <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

    <script>
        $(document).ready(function() {
            $('#corona-table').DataTable( {
                autoWidth: false,
                columnDefs: [
                    {
                        targets: ['_all'],
                        className: 'mdc-data-table__cell',
                    }
                ]
            } );
        } );
    </script>
</body>
</html>
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/corona?allowPublicKeyRetrieval=true&useSSL=false
    username: root
    password: your_passwordasdfasdf##3232

  jpa:
    hibernate:
      ddl-auto: update
    #        database: mysql
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>app</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>app</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>11</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.opencsv</groupId>
			<artifactId>opencsv</artifactId>
			<version>3.8</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilis

And yes, it does attach an image of you selecting a text on Medium instead of just quoting the text. What a mess with blog.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore

aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilis

Check our YouTube channel for FREE Java tutorials

Subscribe and be notified of new videos!

Pint Of Code YouTube channel