]> git.basschouten.com Git - openhab-addons.git/blob
5a62be6f22af759ca2f38519781275262d455f52
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.enturno.internal.connection;
14
15 import static java.util.stream.Collectors.groupingBy;
16 import static org.eclipse.jetty.http.HttpMethod.POST;
17 import static org.eclipse.jetty.http.HttpStatus.*;
18 import static org.openhab.binding.enturno.internal.EnturNoBindingConstants.TIME_ZONE;
19
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InputStreamReader;
24 import java.time.LocalDateTime;
25 import java.time.ZoneId;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.TimeoutException;
33 import java.util.stream.Collectors;
34
35 import org.apache.commons.lang.StringUtils;
36 import org.eclipse.jdt.annotation.NonNullByDefault;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.eclipse.jetty.client.HttpClient;
39 import org.eclipse.jetty.client.api.ContentResponse;
40 import org.eclipse.jetty.client.api.Request;
41 import org.eclipse.jetty.client.util.StringContentProvider;
42 import org.eclipse.jetty.http.HttpHeader;
43 import org.openhab.binding.enturno.internal.EnturNoConfiguration;
44 import org.openhab.binding.enturno.internal.EnturNoHandler;
45 import org.openhab.binding.enturno.internal.model.EnturJsonData;
46 import org.openhab.binding.enturno.internal.model.estimated.EstimatedCalls;
47 import org.openhab.binding.enturno.internal.model.simplified.DisplayData;
48 import org.openhab.binding.enturno.internal.model.stopplace.StopPlace;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 import com.google.gson.Gson;
53 import com.google.gson.JsonObject;
54 import com.google.gson.JsonParser;
55 import com.google.gson.JsonSyntaxException;
56
57 /**
58  * The {@link EnturNoConnection} is responsible for handling connection to Entur.no API
59  *
60  * @author Michal Kloc - Initial contribution
61  */
62 @NonNullByDefault
63 public class EnturNoConnection {
64
65     private final Logger logger = LoggerFactory.getLogger(EnturNoConnection.class);
66     private static final String REQUEST_BODY = "realtime_request.graphql";
67     private static final String PROPERTY_MESSAGE = "message";
68     private static final String CONTENT_TYPE = "application/graphql";
69     private static final String REQUIRED_CLIENT_NAME_HEADER = "ET-Client-Name";
70     private static final String REQUIRED_CLIENT_NAME = "openHAB-enturnobinding";
71
72     private static final String PARAM_STOPID = "stopid";
73     private static final String PARAM_START_DATE_TIME = "startDateTime";
74
75     private static final String REALTIME_URL = "https://api.entur.io/journey-planner/v2/graphql";
76
77     private final EnturNoHandler handler;
78     private final HttpClient httpClient;
79
80     private final JsonParser parser = new JsonParser();
81     private final Gson gson = new Gson();
82
83     public EnturNoConnection(EnturNoHandler handler, HttpClient httpClient) {
84         this.handler = handler;
85         this.httpClient = httpClient;
86     }
87
88     /**
89      * Requests the real-time timetable for specified line and stop place
90      *
91      * @param stopPlaceId stop place id see https://en-tur.no
92      * @return the real-time timetable
93      * @throws JsonSyntaxException
94      * @throws EnturCommunicationException
95      * @throws EnturConfigurationException
96      */
97     public synchronized List<DisplayData> getEnturTimeTable(@Nullable String stopPlaceId, @Nullable String lineCode)
98             throws JsonSyntaxException, EnturConfigurationException, EnturCommunicationException {
99         if (StringUtils.isBlank(stopPlaceId)) {
100             throw new EnturConfigurationException("Stop place id cannot be empty or null");
101         } else if (lineCode == null || StringUtils.isBlank(lineCode)) {
102             throw new EnturConfigurationException("Line code cannot be empty or null");
103         }
104
105         Map<String, String> params = getRequestParams(handler.getEnturNoConfiguration());
106
107         EnturJsonData enturJsonData = gson.fromJson(getResponse(REALTIME_URL, params), EnturJsonData.class);
108
109         if (enturJsonData == null) {
110             throw new EnturCommunicationException("Error when deserializing response to EnturJsonData.class");
111         }
112
113         return processData(enturJsonData.data.stopPlace, lineCode);
114     }
115
116     private Map<String, String> getRequestParams(EnturNoConfiguration config) {
117         Map<String, String> params = new HashMap<>();
118         params.put(PARAM_STOPID, StringUtils.trimToEmpty(config.getStopPlaceId()));
119         params.put(PARAM_START_DATE_TIME, StringUtils.trimToEmpty(LocalDateTime.now(ZoneId.of(TIME_ZONE)).toString()));
120
121         return params;
122     }
123
124     private String getResponse(String url, Map<String, String> params) {
125         try {
126             if (logger.isTraceEnabled()) {
127                 logger.trace("Entur request: URL = '{}', graphQL parameters -> startTime = '{}', stopId = '{}'",
128                         REALTIME_URL, params.get(PARAM_START_DATE_TIME), params.get(PARAM_STOPID));
129             }
130
131             Request request = httpClient.newRequest(url);
132             request.method(POST);
133             request.timeout(10, TimeUnit.SECONDS);
134             request.header(HttpHeader.CONTENT_TYPE, CONTENT_TYPE);
135             request.header(REQUIRED_CLIENT_NAME_HEADER, REQUIRED_CLIENT_NAME);
136             request.content(new StringContentProvider(getRequestBody(params)));
137
138             logger.trace("Request body: {}", getRequestBody(params));
139
140             ContentResponse contentResponse = request.send();
141
142             int httpStatus = contentResponse.getStatus();
143             String content = contentResponse.getContentAsString();
144             String errorMessage = StringUtils.EMPTY;
145             logger.trace("Entur response: status = {}, content = '{}'", httpStatus, content);
146             switch (httpStatus) {
147                 case OK_200:
148                     return content;
149                 case BAD_REQUEST_400:
150                 case NOT_FOUND_404:
151                     errorMessage = getErrorMessage(content);
152                     logger.debug("Entur server responded with status code {}: {}", httpStatus, errorMessage);
153                     throw new EnturConfigurationException(errorMessage);
154                 default:
155                     errorMessage = getErrorMessage(content);
156                     logger.debug("Entur server responded with status code {}: {}", httpStatus, errorMessage);
157                     throw new EnturCommunicationException(errorMessage);
158             }
159         } catch (ExecutionException e) {
160             String errorMessage = e.getLocalizedMessage();
161             logger.debug("Exception occurred during execution: {}", errorMessage, e);
162             throw new EnturCommunicationException(errorMessage, e);
163         } catch (InterruptedException | TimeoutException | IOException e) {
164             logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e);
165             throw new EnturCommunicationException(e.getLocalizedMessage(), e);
166         }
167     }
168
169     private String getErrorMessage(String response) {
170         JsonObject jsonResponse = parser.parse(response).getAsJsonObject();
171         if (jsonResponse.has(PROPERTY_MESSAGE)) {
172             return jsonResponse.get(PROPERTY_MESSAGE).getAsString();
173         }
174         return response;
175     }
176
177     private String getRequestBody(Map<String, String> params) throws IOException {
178         try (InputStream inputStream = EnturNoConnection.class.getClassLoader().getResourceAsStream(REQUEST_BODY);
179                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
180             String json = bufferedReader.lines().collect(Collectors.joining("\n"));
181
182             return json.replaceAll("\\{stopPlaceId}", "" + params.get(PARAM_STOPID)).replaceAll("\\{startDateTime}",
183                     "" + params.get(PARAM_START_DATE_TIME));
184         }
185     }
186
187     private List<DisplayData> processData(StopPlace stopPlace, String lineCode) {
188         Map<String, List<EstimatedCalls>> departures = stopPlace.estimatedCalls.stream()
189                 .filter(call -> StringUtils.equalsIgnoreCase(
190                         StringUtils.trimToEmpty(call.serviceJourney.journeyPattern.line.publicCode),
191                         StringUtils.trimToEmpty(lineCode)))
192                 .collect(groupingBy(call -> call.quay.id));
193
194         List<DisplayData> processedData = new ArrayList<>();
195         if (departures.keySet().size() > 0) {
196             DisplayData processedData01 = getDisplayData(stopPlace, departures, 0);
197             processedData.add(processedData01);
198         }
199
200         if (departures.keySet().size() > 1) {
201             DisplayData processedData02 = getDisplayData(stopPlace, departures, 1);
202             processedData.add(processedData02);
203         }
204
205         return processedData;
206     }
207
208     private DisplayData getDisplayData(StopPlace stopPlace, Map<String, List<EstimatedCalls>> departures,
209             int quayIndex) {
210         List<String> keys = new ArrayList<>(departures.keySet());
211         DisplayData processedData = new DisplayData();
212         List<EstimatedCalls> quayCalls = departures.get(keys.get(quayIndex));
213         List<String> departureTimes = quayCalls.stream().map(eq -> eq.expectedDepartureTime).map(this::getIsoDateTime)
214                 .collect(Collectors.toList());
215
216         List<String> estimatedFlags = quayCalls.stream().map(es -> es.realtime).collect(Collectors.toList());
217
218         if (quayCalls.size() > quayIndex) {
219             String lineCode = quayCalls.get(0).serviceJourney.journeyPattern.line.publicCode;
220             String frontText = quayCalls.get(0).destinationDisplay.frontText;
221             processedData.lineCode = lineCode;
222             processedData.frontText = frontText;
223             processedData.departures = departureTimes;
224             processedData.estimatedFlags = estimatedFlags;
225         }
226
227         processedData.stopPlaceId = stopPlace.id;
228         processedData.stopName = stopPlace.name;
229         processedData.transportMode = stopPlace.transportMode;
230         return processedData;
231     }
232
233     private String getIsoDateTime(String dateTimeWithoutColonInZone) {
234         String dateTime = StringUtils.substringBeforeLast(dateTimeWithoutColonInZone, "+");
235         String offset = StringUtils.substringAfterLast(dateTimeWithoutColonInZone, "+");
236
237         StringBuilder builder = new StringBuilder();
238         return builder.append(dateTime).append("+").append(StringUtils.substring(offset, 0, 2)).append(":00")
239                 .toString();
240     }
241 }