]> git.basschouten.com Git - openhab-addons.git/blob
c7f98e1eee8e735013f04177412b9fa5edb2c680
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.synopanalyzer.internal.stationdb;
14
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.InputStreamReader;
18 import java.io.Reader;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Arrays;
21 import java.util.List;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.osgi.service.component.annotations.Activate;
25 import org.osgi.service.component.annotations.Component;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import com.google.gson.FieldNamingPolicy;
30 import com.google.gson.Gson;
31 import com.google.gson.GsonBuilder;
32 import com.google.gson.JsonIOException;
33 import com.google.gson.JsonSyntaxException;
34
35 /**
36  * The {@link StationDbService} makes available a list of known Synop stations.
37  *
38  * @author GaĆ«l L'hopital - Initial Contribution
39  */
40
41 @Component(service = StationDbService.class)
42 @NonNullByDefault
43 public class StationDbService {
44     private final Logger logger = LoggerFactory.getLogger(StationDbService.class);
45
46     private List<Station> stations;
47
48     @Activate
49     public StationDbService() {
50         try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("/db/stations.json");
51                 Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
52             Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
53             stations = Arrays.asList(gson.fromJson(reader, Station[].class));
54         } catch (IOException | JsonSyntaxException | JsonIOException e) {
55             logger.warn("Unable to load station list : {}", e.getMessage());
56             stations = List.of();
57         }
58     }
59
60     public List<Station> getStations() {
61         return stations;
62     }
63 }