2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.enturno.internal.connection;
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;
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;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.TimeoutException;
33 import java.util.stream.Collectors;
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;
52 import com.google.gson.Gson;
53 import com.google.gson.JsonObject;
54 import com.google.gson.JsonParser;
55 import com.google.gson.JsonSyntaxException;
58 * The {@link EnturNoConnection} is responsible for handling connection to Entur.no API
60 * @author Michal Kloc - Initial contribution
63 public class EnturNoConnection {
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";
72 private static final String PARAM_STOPID = "stopid";
73 private static final String PARAM_START_DATE_TIME = "startDateTime";
75 private static final String REALTIME_URL = "https://api.entur.io/journey-planner/v2/graphql";
77 private final EnturNoHandler handler;
78 private final HttpClient httpClient;
80 private final JsonParser parser = new JsonParser();
81 private final Gson gson = new Gson();
83 public EnturNoConnection(EnturNoHandler handler, HttpClient httpClient) {
84 this.handler = handler;
85 this.httpClient = httpClient;
89 * Requests the real-time timetable for specified line and stop place
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
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");
105 Map<String, String> params = getRequestParams(handler.getEnturNoConfiguration());
107 EnturJsonData enturJsonData = gson.fromJson(getResponse(REALTIME_URL, params), EnturJsonData.class);
109 if (enturJsonData == null) {
110 throw new EnturCommunicationException("Error when deserializing response to EnturJsonData.class");
113 return processData(enturJsonData.data.stopPlace, lineCode);
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()));
124 private String getResponse(String url, Map<String, String> params) {
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));
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)));
138 logger.trace("Request body: {}", getRequestBody(params));
140 ContentResponse contentResponse = request.send();
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) {
149 case BAD_REQUEST_400:
151 errorMessage = getErrorMessage(content);
152 logger.debug("Entur server responded with status code {}: {}", httpStatus, errorMessage);
153 throw new EnturConfigurationException(errorMessage);
155 errorMessage = getErrorMessage(content);
156 logger.debug("Entur server responded with status code {}: {}", httpStatus, errorMessage);
157 throw new EnturCommunicationException(errorMessage);
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);
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();
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"));
182 return json.replaceAll("\\{stopPlaceId}", "" + params.get(PARAM_STOPID)).replaceAll("\\{startDateTime}",
183 "" + params.get(PARAM_START_DATE_TIME));
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));
194 List<DisplayData> processedData = new ArrayList<>();
195 if (departures.keySet().size() > 0) {
196 DisplayData processedData01 = getDisplayData(stopPlace, departures, 0);
197 processedData.add(processedData01);
200 if (departures.keySet().size() > 1) {
201 DisplayData processedData02 = getDisplayData(stopPlace, departures, 1);
202 processedData.add(processedData02);
205 return processedData;
208 private DisplayData getDisplayData(StopPlace stopPlace, Map<String, List<EstimatedCalls>> departures,
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());
216 List<String> estimatedFlags = quayCalls.stream().map(es -> es.realtime).collect(Collectors.toList());
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;
227 processedData.stopPlaceId = stopPlace.id;
228 processedData.stopName = stopPlace.name;
229 processedData.transportMode = stopPlace.transportMode;
230 return processedData;
233 private String getIsoDateTime(String dateTimeWithoutColonInZone) {
234 String dateTime = StringUtils.substringBeforeLast(dateTimeWithoutColonInZone, "+");
235 String offset = StringUtils.substringAfterLast(dateTimeWithoutColonInZone, "+");
237 StringBuilder builder = new StringBuilder();
238 return builder.append(dateTime).append("+").append(StringUtils.substring(offset, 0, 2)).append(":00")