summaryrefslogtreecommitdiff
path: root/src/cfetch/main.java
blob: fccb0059f159c5f80230732f0d61b9286dee4f72 (plain)
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
package cfetch;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.json.*;

public class main {
    public static void main(String[] args) throws IOException, InterruptedException {
        /* System date is required to make the API call use local date not server date */
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDateTime now = LocalDateTime.now();
        JSONObject obj;

        if (args.length > 0) {
            obj = request("http://calapi.inadiutorium.cz/api/v0/en/calendars/general-en/"
                    + args[0]);
        } else {
            obj = request("http://calapi.inadiutorium.cz/api/v0/en/calendars/general-en/"
                    + dtf.format(now));
        }

        JSONArray arr = obj.getJSONArray("celebrations");

        String date, season, title, color, celebration, output;

        date = obj.getString("date");
        season = obj.getString("season");
        title = arr.getJSONObject(0).getString("title");
        color = arr.getJSONObject(0).getString("colour");

        output = date + "\nToday: " + title + "\nSeason: " + season + "\nColor: " + color;

        if (arr.length() > 1) {
            celebration = arr.getJSONObject(1).getString("title");
            output += "\nCelebration: " + celebration;
        }

        System.out.println(output);
    }

    private static JSONObject request(String url) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .build();

        HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());

        String jsonString = response.body();
        return new JSONObject(jsonString);
    }
}