]> git.basschouten.com Git - openhab-addons.git/blob
2feb601bcc7bac84ba7c176f29db4cd39e1334aa
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.bticinosmarther.internal.api;
14
15 import static org.eclipse.jetty.http.HttpStatus.*;
16
17 import java.util.concurrent.CompletableFuture;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.TimeoutException;
22 import java.util.function.Function;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jetty.client.HttpClient;
26 import org.eclipse.jetty.client.api.ContentResponse;
27 import org.eclipse.jetty.client.api.Request;
28 import org.eclipse.jetty.http.HttpStatus;
29 import org.openhab.binding.bticinosmarther.internal.api.exception.SmartherAuthorizationException;
30 import org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException;
31 import org.openhab.binding.bticinosmarther.internal.api.exception.SmartherInvalidResponseException;
32 import org.openhab.binding.bticinosmarther.internal.api.exception.SmartherSubscriptionAlreadyExistsException;
33 import org.openhab.binding.bticinosmarther.internal.api.exception.SmartherTokenExpiredException;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 import com.google.gson.JsonElement;
38 import com.google.gson.JsonObject;
39 import com.google.gson.JsonParser;
40 import com.google.gson.JsonSyntaxException;
41
42 /**
43  * The {@code SmartherApiConnector} class is used to perform the actual call to the API gateway.
44  * It handles the returned http status codes and the error codes eventually returned by the API gateway itself.
45  *
46  * Response mappings:
47  * <ul>
48  * <li>Plants : 200, 204, 400, 401, 404, 408, 469, 470, 500</li>
49  * <li>Topology : 200, 400, 401, 404, 408, 469, 470, 500</li>
50  * <li>Measures : 200, 400, 401, 404, 408, 469, 470, 500</li>
51  * <li>ProgramList : 200, 400, 401, 404, 408, 469, 470, 500</li>
52  * <li>Get Status : 200, 400, 401, 404, 408, 469, 470, 500</li>
53  * <li>Set Status : 200, 400, 401, 404, 408, 430, 469, 470, 486, 500</li>
54  * <li>Get Subscriptions : 200, 204, 400, 401, 404, 500</li>
55  * <li>Subscribe : 201, 400, 401, 404, 409, 500</li>
56  * <li>Delete Subscription : 200, 400, 401, 404, 500</li>
57  * </ul>
58  *
59  * @author Fabio Possieri - Initial contribution
60  */
61 @NonNullByDefault
62 public class SmartherApiConnector {
63
64     private static final String RETRY_AFTER_HEADER = "Retry-After";
65     private static final String AUTHORIZATION_HEADER = "Authorization";
66     private static final String SUBSCRIPTION_HEADER = "Ocp-Apim-Subscription-Key";
67
68     private static final String ERROR_CODE = "statusCode";
69     private static final String ERROR_MESSAGE = "message";
70     private static final String TOKEN_EXPIRED = "expired";
71     private static final String AUTHORIZATION_ERROR = "error_description";
72
73     private static final int HTTP_CLIENT_TIMEOUT_SECONDS = 10;
74     private static final int HTTP_CLIENT_RETRY_COUNT = 5;
75
76     // Set Chronothermostat Status > Wrong input parameters
77     private static final int WRONG_INPUT_PARAMS_430 = 430;
78     // Official application password expired: password used in the Thermostat official app is expired.
79     private static final int APP_PASSWORD_EXPIRED_469 = 469;
80     // Official application terms and conditions expired: terms and conditions for Thermostat official app are expired.
81     private static final int APP_TERMS_EXPIRED_470 = 470;
82     // Set Chronothermostat Status > Busy visual user interface
83     private static final int BUSY_VISUAL_UI_486 = 486;
84
85     private final Logger logger = LoggerFactory.getLogger(SmartherApiConnector.class);
86
87     private final HttpClient httpClient;
88     private final ScheduledExecutorService scheduler;
89
90     /**
91      * Constructs a {@code SmartherApiConnector} to the API gateway with the specified scheduler and http client.
92      *
93      * @param scheduler
94      *            the scheduler to be used to reschedule calls when rate limit exceeded or call not succeeded
95      * @param httpClient
96      *            the http client to be used to make http calls to the API gateway
97      */
98     public SmartherApiConnector(ScheduledExecutorService scheduler, HttpClient httpClient) {
99         this.scheduler = scheduler;
100         this.httpClient = httpClient;
101     }
102
103     /**
104      * Performs a call to the API gateway and returns the raw response.
105      *
106      * @param requester
107      *            the function to construct the request, using the http client that is passed as argument to the
108      *            function itself
109      * @param subscription
110      *            the subscription string to be used in the call {@code Subscription} header
111      * @param authorization
112      *            the authorization string to be used in the call {@code Authorization} header
113      *
114      * @return the raw response returned by the API gateway
115      *
116      * @throws {@link SmartherGatewayException}
117      *             if the call failed due to an issue with the API gateway
118      */
119     public ContentResponse request(Function<HttpClient, Request> requester, String subscription, String authorization)
120             throws SmartherGatewayException {
121         final Caller caller = new Caller(requester, subscription, authorization);
122
123         try {
124             return caller.call().get();
125         } catch (InterruptedException e) {
126             Thread.currentThread().interrupt();
127             throw new SmartherGatewayException("Thread interrupted");
128         } catch (ExecutionException e) {
129             final Throwable cause = e.getCause();
130
131             if (cause instanceof SmartherGatewayException) {
132                 throw (SmartherGatewayException) cause;
133             } else {
134                 throw new SmartherGatewayException(e.getMessage(), e);
135             }
136         }
137     }
138
139     /**
140      * The {@code Caller} class represents the handler to make calls to the API gateway.
141      * In case of rate limiting or not finished jobs, it will retry a number of times in a specified timeframe then
142      * gives up with an exception.
143      *
144      * @author Fabio Possieri - Initial contribution
145      */
146     private class Caller {
147         private final Function<HttpClient, Request> requester;
148         private final String subscription;
149         private final String authorization;
150
151         private final CompletableFuture<ContentResponse> future = new CompletableFuture<>();
152         private int delaySeconds;
153         private int attempts;
154
155         /**
156          * Constructs a {@code Caller} to the API gateway with the specified requester, subscription and authorization.
157          *
158          * @param requester
159          *            the function to construct the request, using the http client that is passed as argument to the
160          *            function itself
161          * @param subscription
162          *            the subscription string to be used in the call {@code Subscription} header
163          * @param authorization
164          *            the authorization string to be used in the call {@code Authorization} header
165          */
166         public Caller(Function<HttpClient, Request> requester, String subscription, String authorization) {
167             this.requester = requester;
168             this.subscription = subscription;
169             this.authorization = authorization;
170         }
171
172         /**
173          * Performs the request as a {@link CompletableFuture}, setting its state once finished.
174          * The original caller should call the {@code get} method on the Future to wait for the call to finish.
175          * The first attempt is not scheduled so, if the first call succeeds, the {@code get} method directly returns
176          * the value. This method is rescheduled in case the call is to be retried.
177          *
178          * @return the {@link CompletableFuture} holding the call
179          */
180         public CompletableFuture<ContentResponse> call() {
181             attempts++;
182             try {
183                 final boolean success = processResponse(requester.apply(httpClient)
184                         .header(SUBSCRIPTION_HEADER, subscription).header(AUTHORIZATION_HEADER, authorization)
185                         .timeout(HTTP_CLIENT_TIMEOUT_SECONDS, TimeUnit.SECONDS).send());
186
187                 if (!success) {
188                     if (attempts < HTTP_CLIENT_RETRY_COUNT) {
189                         logger.debug("API Gateway call attempt: {}", attempts);
190
191                         scheduler.schedule(this::call, delaySeconds, TimeUnit.SECONDS);
192                     } else {
193                         logger.debug("Giving up on accessing API Gateway. Check network connectivity!");
194                         future.completeExceptionally(new SmartherGatewayException(
195                                 String.format("Could not reach the API Gateway after %s retries.", attempts)));
196                     }
197                 }
198             } catch (ExecutionException e) {
199                 Throwable cause = e.getCause();
200                 future.completeExceptionally(cause != null ? cause : e);
201             } catch (SmartherGatewayException e) {
202                 future.completeExceptionally(e);
203             } catch (RuntimeException | TimeoutException e) {
204                 future.completeExceptionally(e);
205             } catch (InterruptedException e) {
206                 Thread.currentThread().interrupt();
207                 future.completeExceptionally(e);
208             }
209             return future;
210         }
211
212         /**
213          * Processes the response from the API gateway call and handles the http status codes.
214          *
215          * @param response
216          *            the response content returned by the API gateway
217          *
218          * @return {@code true} if the call was successful, {@code false} if the call failed in a way that can be
219          *         retried
220          *
221          * @throws {@link SmartherGatewayException}
222          *             if the call failed due to an irrecoverable issue and cannot be retried (user should be informed)
223          */
224         private boolean processResponse(ContentResponse response) throws SmartherGatewayException {
225             boolean success = false;
226
227             logger.debug("Response Code: {}", response.getStatus());
228             if (logger.isTraceEnabled()) {
229                 logger.trace("Response Data: {}", response.getContentAsString());
230             }
231             switch (response.getStatus()) {
232                 case OK_200:
233                 case CREATED_201:
234                 case NO_CONTENT_204:
235                 case NOT_MODIFIED_304:
236                     future.complete(response);
237                     success = true;
238                     break;
239
240                 case ACCEPTED_202:
241                     logger.debug(
242                             "API Gateway returned error status 202 (the request has been accepted for processing, but the processing has not been completed)");
243                     future.complete(response);
244                     success = true;
245                     break;
246
247                 case FORBIDDEN_403:
248                     // Process for authorization error, and logging.
249                     processErrorState(response);
250                     future.complete(response);
251                     success = true;
252                     break;
253
254                 case BAD_REQUEST_400:
255                 case NOT_FOUND_404:
256                 case REQUEST_TIMEOUT_408:
257                 case WRONG_INPUT_PARAMS_430:
258                 case APP_PASSWORD_EXPIRED_469:
259                 case APP_TERMS_EXPIRED_470:
260                 case BUSY_VISUAL_UI_486:
261                 case INTERNAL_SERVER_ERROR_500:
262                     throw new SmartherGatewayException(processErrorState(response));
263
264                 case UNAUTHORIZED_401:
265                     throw new SmartherAuthorizationException(processErrorState(response));
266
267                 case CONFLICT_409:
268                     // Subscribe to C2C notifications > Subscription already exists.
269                     throw new SmartherSubscriptionAlreadyExistsException(processErrorState(response));
270
271                 case TOO_MANY_REQUESTS_429:
272                     // Response Code 429 means requests rate limits exceeded.
273                     final String retryAfter = response.getHeaders().get(RETRY_AFTER_HEADER);
274                     logger.debug(
275                             "API Gateway returned error status 429 (rate limit exceeded - retry after {} seconds, decrease polling interval of bridge, going to sleep...)",
276                             retryAfter);
277                     delaySeconds = Integer.parseInt(retryAfter);
278                     break;
279
280                 case BAD_GATEWAY_502:
281                 case SERVICE_UNAVAILABLE_503:
282                 default:
283                     throw new SmartherGatewayException(String.format("API Gateway returned error status %s (%s)",
284                             response.getStatus(), HttpStatus.getMessage(response.getStatus())));
285             }
286             return success;
287         }
288
289         /**
290          * Processes the responded content if the status code indicated an error.
291          *
292          * @param response
293          *            the response content returned by the API gateway
294          *
295          * @return the error message extracted from the response content
296          *
297          * @throws {@link SmartherTokenExpiredException}
298          *             if the authorization access token used to communicate with the API gateway has expired
299          * @throws {@link SmartherAuthorizationException}
300          *             if a generic authorization issue with the API gateway has occurred
301          * @throws {@link SmartherInvalidResponseException}
302          *             if the response received from the API gateway cannot be parsed
303          */
304         private String processErrorState(ContentResponse response)
305                 throws SmartherTokenExpiredException, SmartherAuthorizationException, SmartherInvalidResponseException {
306             try {
307                 final JsonElement element = JsonParser.parseString(response.getContentAsString());
308
309                 if (element.isJsonObject()) {
310                     final JsonObject object = element.getAsJsonObject();
311                     if (object.has(ERROR_CODE) && object.has(ERROR_MESSAGE)) {
312                         final String message = object.get(ERROR_MESSAGE).getAsString();
313
314                         // Bad request can be anything, from authorization problems to plant or module problems.
315                         // Therefore authorization type errors are filtered and handled differently.
316                         logger.debug("Bad request: {}", message);
317                         if (message.contains(TOKEN_EXPIRED)) {
318                             throw new SmartherTokenExpiredException(message);
319                         } else {
320                             return message;
321                         }
322                     } else if (object.has(AUTHORIZATION_ERROR)) {
323                         final String errorDescription = object.get(AUTHORIZATION_ERROR).getAsString();
324                         throw new SmartherAuthorizationException(errorDescription);
325                     }
326                 }
327                 logger.debug("Unknown response: {}", response);
328                 return "Unknown response";
329             } catch (JsonSyntaxException e) {
330                 logger.warn("Response was not json: ", e);
331                 throw new SmartherInvalidResponseException(e.getMessage());
332             }
333         }
334     }
335 }