DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Build Chatbots with Dialogflow - Step By Step Guidelines
  • How to Quickly Build a Progressive Web App Using Lightning Web Components
  • 6 of the Best API Testing Tools in the Market
  • Configuring Java Apps With Kubernetes ConfigMaps and Helm

Trending

  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Unlocking AI Coding Assistants Part 3: Generating Diagrams, Open API Specs, And Test Data
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  1. DZone
  2. Coding
  3. Java
  4. How to Build a Coronavirus Dashboard in Java

How to Build a Coronavirus Dashboard in Java

By 
Alejandro Duarte user avatar
Alejandro Duarte
DZone Core CORE ·
Updated May. 11, 20 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
20.3K Views

Join the DZone community and get the full member experience.

Join For Free

This tutorial explains how to create a simple dashboard to track coronavirus data using the Java programming language. The dashboard is a web application implemented with Spring Boot 2.2.6 and Vaadin 14.1.25. It includes features of Progressive Web Applications (PWA), such as responsive design and the possibility to install the app onto the home screen of mobile phones and other devices.

The source code is available on GitHub.

Setting Up a New Project

To set up a new project:

  1. Go to https://start.spring.io and generate a new Maven project with JAR packaging and the following dependencies:

    • OpenFeign: Declarative REST Client. OpenFeign creates a dynamic implementation of an interface decorated with JAX-RS or Spring MVC annotations.

    • Vaadin: Java framework for building rich client apps based on Web Components.

  2. Import the Maven project into your favorite IDE. This tutorial uses IntelliJ IDEA.

  3. Add the following dependencies to the pom.xml file:

XML
 




xxxxxxxxxx
1
12


 
1
<dependency>
2
    <groupId>com.vaadin</groupId>
3
    <artifactId>vaadin-board-flow</artifactId>
4
</dependency>
5
<dependency>
6
    <groupId>com.vaadin</groupId>
7
    <artifactId>vaadin-charts-flow</artifactId>
8
</dependency>
9
<dependency>
10
    <groupId>com.vaadin</groupId>
11
    <artifactId>vaadin-cookie-consent-flow</artifactId>
12
</dependency>



Connecting to a REST Web Service

The dashboard uses data from the REST web service available for free (at the time of writing this article) at https://corona-api.com.

Generating the Data Model

To create the data model (POJOs to store data from the web service):

  1. Add the following Maven plugin into the  <plugins>  section of the  <build>  section:

XML
 




xxxxxxxxxx
1
20


 
1
<plugin>
2
    <groupId>org.jsonschema2pojo</groupId>
3
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
4
    <version>1.0.2</version>
5
    <configuration>
6
        <sourcePaths>${basedir}/src/main/resources/timeline.json</sourcePaths>
7
        <sourceType>json</sourceType>
8
        <includeAdditionalProperties>false</includeAdditionalProperties>
9
        <includeToString>false</includeToString>
10
        <includeHashcodeAndEquals>false</includeHashcodeAndEquals>
11
        <targetPackage>com.example</targetPackage>
12
    </configuration>
13
    <executions>
14
        <execution>
15
            <goals>
16
                <goal>generate</goal>
17
            </goals>
18
        </execution>
19
    </executions>
20
</plugin>


  1. Create a new  timeline.json  file in the  src/main/resources/  directory with the following sample JSON content taken from the web service:

JSON
 




xxxxxxxxxx
1
28


 
1
{
2
  "data": [
3
    {
4
      "updated_at": "2020-04-24T16:24:27.242Z",
5
      "date": "2020-04-24",
6
      "deaths": 193851,
7
      "confirmed": 2759409,
8
      "recovered": 764188,
9
      "active": 1801370,
10
      "new_confirmed": 52374,
11
      "new_recovered": 26541,
12
      "new_deaths": 3029,
13
      "is_in_progress": true
14
    },
15
    {
16
      "updated_at": "2020-04-23T08:58:50.000Z",
17
      "date": "2020-04-23",
18
      "deaths": 190822,
19
      "confirmed": 2707035,
20
      "recovered": 737647,
21
      "new_confirmed": 85448,
22
      "new_recovered": 28768,
23
      "new_deaths": 7831,
24
      "active": 1778566
25
    }
26
  ],
27
  "_cacheHit": true
28
}


  1. To compile the application, you need to install Node.js. Once installed, execute  mvn package  and confirm that the POJOs are generated in the target/generated-sources/jsonschema2pojo/com/example/  directory.

  2. Mark the  target/generated-sources/jsonschema2pojo/  directory as source root in your IDE (on IntelliJ IDEA, right-click the directory, and select Mark Directory As > Sources Root).

Implementing the Web Service Client

To create a web service client:

  1. Enable Feign clients as follows:

Java
 




xxxxxxxxxx
1


 
1
@SpringBootApplication
2
@EnableFeignClients
3
public class CoronavirusDashboardApplication {
4

          
5
    public static void main(String[] args) {
6
        SpringApplication.run(CoronavirusDashboardApplication.class, args);
7
    }
8

          
9
}


  1. Create the following Java interface:

Java
 




xxxxxxxxxx
1


 
1
@FeignClient(name = "corona-ip", url = "https://corona-api.com/")
2
public interface CoronavirusService {
3

          
4
    @RequestMapping(value = "/timeline")
5
    Timeline timeline();
6

          
7
}


Implementing the UI

To implement the UI to show the data:

  1. Implement a UI component to show a number as follows:

Java
 




xxxxxxxxxx
1
15


 
1
public class DashboardNumber extends VerticalLayout {
2

          
3
    public DashboardNumber(String description, Number number) {
4
        Div descriptionDiv = new Div(new Text(description));
5
        descriptionDiv.getStyle().set("font-size", "small");
6

          
7
        Div numberDiv = new Div(new Text("" + number));
8
        numberDiv.getStyle().set("font-size", "xx-large");
9
        numberDiv.getStyle().set("font-weight", "bold");
10
        numberDiv.getStyle().set("margin-top", "0");
11

          
12
        add(descriptionDiv, numberDiv);
13
    }
14

          
15
}


  1. Implement a UI component to show a chart as follows:

Java
 




xxxxxxxxxx
1
32


 
1
public class DashboardChart extends VerticalLayout {
2

          
3
    public DashboardChart(List<Datum> data, ChartType type, String title,
4
            Function<Datum, Number> getConfirmed, Function<Datum, Number>        
5
                    getDeaths, Function<Datum, Number> getRecovered) {
6

          
7
        Chart chart = new Chart(type);
8
        Configuration configuration = chart.getConfiguration();
9
        configuration.setTitle(title);
10
        configuration.getTooltip().setEnabled(true);
11
        configuration.getxAxis().setType(AxisType.DATETIME);
12
        configuration.addSeries(getDataSeries(data.stream(), getConfirmed, "Confirmed"));
13
        configuration.addSeries(getDataSeries(data.stream(), getDeaths, "Deaths"));
14
        configuration.addSeries(getDataSeries(data.stream(), getRecovered, "Recovered"));
15

          
16
        add(chart);
17
    }
18

          
19
    private DataSeries getDataSeries(Stream<Datum> data, Function<Datum,
20
                                     Number> function, String name) {
21
        DataSeries dataSeries = new DataSeries(data
22
                .map(d -> new DataSeriesItem(
23
                        LocalDate.parse(d.getDate()).atStartOfDay().toInstant(ZoneOffset.UTC),
24
                        function.apply(d)
25
                ))
26
                .collect(Collectors.toList()));
27
        dataSeries.setName(name);
28

          
29
        return dataSeries;
30
    }
31

          
32
}


  1. Implement a view by creating the following class:

Java
x
1
@Route("")
2
public class DashboardView extends VerticalLayout {
3
4
    public DashboardView(CoronavirusService service) {
5
        List<Datum> data = service.timeline().getData();
6
        Datum latest = data.get(0);
7
8
        add(
9
                new H1("Coronavirus dashboard"),
10
                new DashboardNumber("Confirmed", latest.getConfirmed()),
11
                new DashboardNumber("Deaths", latest.getDeaths()),
12
                new DashboardNumber("Recovered", latest.getRecovered()),
13
                new DashboardChart(data, ChartType.SPLINE, "Cumulative",
14
                        Datum::getConfirmed, Datum::getDeaths,
15
                                   Datum::getRecovered),
16
                new DashboardChart(data.subList(0, 7), ChartType.COLUMN, "Daily",
17
                        Datum::getNewConfirmed, Datum::getNewDeaths,
18
                                   Datum::getNewRecovered)
19
        );
20
    }
21
22
}


Adding PWA Features to the Application

At this point, the application is functional. However, there are two improvements that are easy to add.

Adding Responsiveness to the UI

To add responsive features to the application, replace the call to the add method in the DashboardView  class with the following:

Java
x
 
1
Board board = new Board();
2
board.addRow(
3
        new DashboardNumber("Confirmed", latest.getConfirmed()),
4
        new DashboardNumber("Deaths", latest.getDeaths()),
5
        new DashboardNumber("Recovered", latest.getRecovered())
6
7
);
8
board.addRow(
9
        new DashboardChart(data, ChartType.SPLINE, "Cumulative",
10
                Datum::getConfirmed, Datum::getDeaths, Datum::getRecovered),
11
        new DashboardChart(data.subList(0, 7), ChartType.COLUMN, "Daily",
12
                Datum::getNewConfirmed, Datum::getNewDeaths,
13
                           Datum::getNewRecovered)
14
);
15
16
add(
17
        new H1("Coronavirus dashboard"),
18
        board
19
);


Making the Application Installable

To make the application installable on devices such as mobile phones, annotate the DashboardView class as follows:

Java
 




xxxxxxxxxx
1


 
1
@Route("")
2
@PWA(name = "Coronavirus Dashboard", shortName = "Coronavirus",
3
        description = "A Coronavirus dashboard app")
4
public class DashboardView extends VerticalLayout {
5
    ...
6
}



Compiling and Running the Application

Note that you need to install Node.js to compile the application. Compile and run the application by running the following:

Shell
 




xxxxxxxxxx
1


 
1
mvn package
2

          
3
java -jar target/coronavirus-dashboard-0.0.1-SNAPSHOT.jar



Here's a screenshot of the application:

Application frontend

What's Next?

Try installing the application on your phone. On Safari, you might have to use the share option and select Add to Home Screen. Keep in mind that unless deployed on localhost, you'll need to serve your app through HTTPS for this to work.

Try activating the dark theme of Vaadin by adding the following annotation to the  DashboardView  class:

Java
 




xxxxxxxxxx
1


 
1
@Theme(value = Lumo.class, variant = Lumo.DARK)



See the web service documentation and all the available types of charts in Vaadin and try adding new charts to the dashboard or an option to show data by country.

Java (programming language) mobile app Dashboard (Mac OS) Web Service Build (game engine)

Opinions expressed by DZone contributors are their own.

Related

  • Build Chatbots with Dialogflow - Step By Step Guidelines
  • How to Quickly Build a Progressive Web App Using Lightning Web Components
  • 6 of the Best API Testing Tools in the Market
  • Configuring Java Apps With Kubernetes ConfigMaps and Helm

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!