]> git.basschouten.com Git - openhab-addons.git/blob
6f8e104d603e03e81a8cb6d90f38cab8a8b826fd
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.remoteopenhab.internal.rest;
14
15 import java.io.ByteArrayOutputStream;
16 import java.io.EOFException;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Arrays;
21 import java.util.Base64;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Objects;
26 import java.util.concurrent.CopyOnWriteArrayList;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30
31 import javax.net.ssl.HostnameVerifier;
32 import javax.net.ssl.SSLSession;
33 import javax.ws.rs.client.Client;
34 import javax.ws.rs.client.ClientBuilder;
35 import javax.ws.rs.core.HttpHeaders;
36 import javax.ws.rs.sse.InboundSseEvent;
37 import javax.ws.rs.sse.SseEventSource;
38
39 import org.eclipse.jdt.annotation.NonNullByDefault;
40 import org.eclipse.jdt.annotation.Nullable;
41 import org.eclipse.jetty.client.HttpClient;
42 import org.eclipse.jetty.client.api.ContentResponse;
43 import org.eclipse.jetty.client.api.Request;
44 import org.eclipse.jetty.client.api.Response;
45 import org.eclipse.jetty.client.util.InputStreamResponseListener;
46 import org.eclipse.jetty.client.util.StringContentProvider;
47 import org.eclipse.jetty.http.HttpMethod;
48 import org.eclipse.jetty.http.HttpStatus;
49 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabChannelDescriptionChangedEvent;
50 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabChannelTriggerEvent;
51 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabCommandDescription;
52 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabCommandOptions;
53 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabEvent;
54 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabEventPayload;
55 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabItem;
56 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabRestApi;
57 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabStateDescription;
58 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabStateOptions;
59 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabStatusInfo;
60 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabThing;
61 import org.openhab.binding.remoteopenhab.internal.exceptions.RemoteopenhabException;
62 import org.openhab.binding.remoteopenhab.internal.listener.RemoteopenhabItemsDataListener;
63 import org.openhab.binding.remoteopenhab.internal.listener.RemoteopenhabStreamingDataListener;
64 import org.openhab.binding.remoteopenhab.internal.listener.RemoteopenhabThingsDataListener;
65 import org.openhab.core.i18n.TranslationProvider;
66 import org.openhab.core.types.Command;
67 import org.osgi.framework.Bundle;
68 import org.osgi.framework.FrameworkUtil;
69 import org.osgi.service.jaxrs.client.SseEventSourceFactory;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 import com.google.gson.Gson;
74 import com.google.gson.JsonSyntaxException;
75
76 /**
77  * A client to use the openHAB REST API and to receive/parse events received from the openHAB REST API Server-Sent
78  * Events (SSE).
79  *
80  * @author Laurent Garnier - Initial contribution
81  */
82 @NonNullByDefault
83 public class RemoteopenhabRestClient {
84
85     private static final int REQUEST_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(30);
86
87     private final Logger logger = LoggerFactory.getLogger(RemoteopenhabRestClient.class);
88
89     private final ClientBuilder clientBuilder;
90     private final SseEventSourceFactory eventSourceFactory;
91     private final Gson jsonParser;
92     private final TranslationProvider i18nProvider;
93     private final Bundle bundle;
94
95     private final Object startStopLock = new Object();
96     private final List<RemoteopenhabStreamingDataListener> listeners = new CopyOnWriteArrayList<>();
97     private final List<RemoteopenhabItemsDataListener> itemsListeners = new CopyOnWriteArrayList<>();
98     private final List<RemoteopenhabThingsDataListener> thingsListeners = new CopyOnWriteArrayList<>();
99
100     private HttpClient httpClient;
101     private @Nullable String restUrl;
102     private @Nullable String restApiVersion;
103     private Map<String, @Nullable String> apiEndPointsUrls = new HashMap<>();
104     private @Nullable String topicNamespace;
105     private boolean authenticateAnyway;
106     private String accessToken;
107     private String credentialToken;
108     private boolean trustedCertificate;
109     private boolean connected;
110     private boolean completed;
111
112     private @Nullable SseEventSource eventSource;
113     private long lastEventTimestamp;
114
115     public RemoteopenhabRestClient(final HttpClient httpClient, final ClientBuilder clientBuilder,
116             final SseEventSourceFactory eventSourceFactory, final Gson jsonParser,
117             final TranslationProvider i18nProvider) {
118         this.httpClient = httpClient;
119         this.clientBuilder = clientBuilder;
120         this.eventSourceFactory = eventSourceFactory;
121         this.jsonParser = jsonParser;
122         this.i18nProvider = i18nProvider;
123         this.bundle = FrameworkUtil.getBundle(this.getClass());
124         this.accessToken = "";
125         this.credentialToken = "";
126     }
127
128     public void setHttpClient(HttpClient httpClient) {
129         this.httpClient = httpClient;
130     }
131
132     public String getRestUrl() throws RemoteopenhabException {
133         String url = restUrl;
134         if (url == null) {
135             throw new RemoteopenhabException("@text/exception.rest-client-not-setup");
136         }
137         return url;
138     }
139
140     public void setRestUrl(String restUrl) {
141         this.restUrl = restUrl;
142     }
143
144     public void setAuthenticationData(boolean authenticateAnyway, String accessToken, String username,
145             String password) {
146         this.authenticateAnyway = authenticateAnyway;
147         this.accessToken = accessToken;
148         if (username.isBlank() || password.isBlank()) {
149             this.credentialToken = "";
150         } else {
151             String token = username + ":" + password;
152             this.credentialToken = Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8));
153         }
154     }
155
156     public void setTrustedCertificate(boolean trustedCertificate) {
157         this.trustedCertificate = trustedCertificate;
158     }
159
160     public void tryApi() throws RemoteopenhabException {
161         try {
162             String jsonResponse = executeGetUrl(getRestUrl(), "application/json", false, false);
163             if (jsonResponse.isEmpty()) {
164                 throw new RemoteopenhabException("@text/exception.json-response-empty");
165             }
166             RemoteopenhabRestApi restApi = jsonParser.fromJson(jsonResponse, RemoteopenhabRestApi.class);
167             restApiVersion = restApi.version;
168             logger.debug("REST API version = {}", restApiVersion);
169             apiEndPointsUrls.clear();
170             for (int i = 0; i < restApi.links.length; i++) {
171                 apiEndPointsUrls.put(restApi.links[i].type, restApi.links[i].url);
172             }
173             logger.debug("REST API items = {}", apiEndPointsUrls.get("items"));
174             logger.debug("REST API things = {}", apiEndPointsUrls.get("things"));
175             logger.debug("REST API events = {}", apiEndPointsUrls.get("events"));
176             topicNamespace = restApi.runtimeInfo != null ? "openhab" : "smarthome";
177             logger.debug("topic namespace = {}", topicNamespace);
178         } catch (RemoteopenhabException | JsonSyntaxException e) {
179             throw new RemoteopenhabException("@text/exception.root-rest-api-failed", e);
180         }
181     }
182
183     public List<RemoteopenhabItem> getRemoteItems(@Nullable String fields) throws RemoteopenhabException {
184         try {
185             String url = String.format("%s?recursive=false", getRestApiUrl("items"));
186             if (fields != null) {
187                 url += "&fields=" + fields;
188             }
189             boolean asyncReading = fields == null || Arrays.asList(fields.split(",")).contains("state");
190             String jsonResponse = executeGetUrl(url, "application/json", false, asyncReading);
191             if (jsonResponse.isEmpty()) {
192                 throw new RemoteopenhabException("@text/exception.json-response-empty");
193             }
194             return Arrays.asList(jsonParser.fromJson(jsonResponse, RemoteopenhabItem[].class));
195         } catch (RemoteopenhabException | JsonSyntaxException e) {
196             throw new RemoteopenhabException("@text/exception.get-list-items-api-failed", e);
197         }
198     }
199
200     public String getRemoteItemState(String itemName) throws RemoteopenhabException {
201         try {
202             String url = String.format("%s/%s/state", getRestApiUrl("items"), itemName);
203             return executeGetUrl(url, "text/plain", false, true);
204         } catch (RemoteopenhabException e) {
205             throw new RemoteopenhabException("@text/get-item-state-api-failed", e, itemName);
206         }
207     }
208
209     public void sendCommandToRemoteItem(String itemName, Command command) throws RemoteopenhabException {
210         try {
211             String url = String.format("%s/%s", getRestApiUrl("items"), itemName);
212             executeUrl(HttpMethod.POST, url, "application/json", command.toFullString(), "text/plain", false, false,
213                     true);
214         } catch (RemoteopenhabException e) {
215             throw new RemoteopenhabException("@text/exception.send-item-command-api-failed", e, itemName);
216         }
217     }
218
219     public List<RemoteopenhabThing> getRemoteThings() throws RemoteopenhabException {
220         try {
221             String jsonResponse = executeGetUrl(getRestApiUrl("things"), "application/json", true, false);
222             if (jsonResponse.isEmpty()) {
223                 throw new RemoteopenhabException("@text/exception.json-response-empty");
224             }
225             return Arrays.asList(jsonParser.fromJson(jsonResponse, RemoteopenhabThing[].class));
226         } catch (RemoteopenhabException | JsonSyntaxException e) {
227             throw new RemoteopenhabException("@text/exception.get-list-things-api-failed", e);
228         }
229     }
230
231     public RemoteopenhabThing getRemoteThing(String uid) throws RemoteopenhabException {
232         try {
233             String url = String.format("%s/%s", getRestApiUrl("things"), uid);
234             String jsonResponse = executeGetUrl(url, "application/json", true, false);
235             if (jsonResponse.isEmpty()) {
236                 throw new RemoteopenhabException("@text/exception.json-response-empty");
237             }
238             return Objects.requireNonNull(jsonParser.fromJson(jsonResponse, RemoteopenhabThing.class));
239         } catch (RemoteopenhabException | JsonSyntaxException e) {
240             throw new RemoteopenhabException("@text/exception.get-thing-api-failed", e, uid);
241         }
242     }
243
244     public @Nullable String getRestApiVersion() {
245         return restApiVersion;
246     }
247
248     private String getRestApiUrl(String endPoint) throws RemoteopenhabException {
249         String url = apiEndPointsUrls.get(endPoint);
250         if (url == null) {
251             url = getRestUrl();
252             if (!url.endsWith("/")) {
253                 url += "/";
254             }
255             url += endPoint;
256         }
257         return url;
258     }
259
260     public String getTopicNamespace() {
261         String namespace = topicNamespace;
262         return namespace != null ? namespace : "openhab";
263     }
264
265     public void start() {
266         synchronized (startStopLock) {
267             logger.debug("Opening EventSource");
268             reopenEventSource();
269             logger.debug("EventSource started");
270         }
271     }
272
273     public void stop(boolean waitingForCompletion) {
274         synchronized (startStopLock) {
275             logger.debug("Closing EventSource");
276             closeEventSource(waitingForCompletion);
277             logger.debug("EventSource stopped");
278             lastEventTimestamp = 0;
279         }
280     }
281
282     private SseEventSource createEventSource(String restSseUrl) {
283         String credentialToken = restSseUrl.startsWith("https:") || authenticateAnyway ? this.credentialToken : "";
284
285         RemoteopenhabStreamingRequestFilter filter;
286         boolean filterRegistered = clientBuilder.getConfiguration()
287                 .isRegistered(RemoteopenhabStreamingRequestFilter.class);
288         if (filterRegistered) {
289             filter = clientBuilder.getConfiguration().getInstances().stream()
290                     .filter(instance -> instance instanceof RemoteopenhabStreamingRequestFilter)
291                     .map(instance -> (RemoteopenhabStreamingRequestFilter) instance).findAny().orElseThrow();
292         } else {
293             filter = new RemoteopenhabStreamingRequestFilter();
294         }
295         filter.setCredentialToken(restSseUrl, credentialToken);
296
297         Client client;
298         // Avoid a timeout exception after 1 minute by setting the read timeout to 0 (infinite)
299         if (trustedCertificate) {
300             HostnameVerifier alwaysValidHostname = new HostnameVerifier() {
301                 @Override
302                 public boolean verify(@Nullable String hostname, @Nullable SSLSession session) {
303                     return true;
304                 }
305             };
306             if (filterRegistered) {
307                 client = clientBuilder.sslContext(httpClient.getSslContextFactory().getSslContext())
308                         .hostnameVerifier(alwaysValidHostname).readTimeout(0, TimeUnit.SECONDS).build();
309             } else {
310                 client = clientBuilder.sslContext(httpClient.getSslContextFactory().getSslContext())
311                         .hostnameVerifier(alwaysValidHostname).readTimeout(0, TimeUnit.SECONDS).register(filter)
312                         .build();
313             }
314         } else {
315             if (filterRegistered) {
316                 client = clientBuilder.readTimeout(0, TimeUnit.SECONDS).build();
317             } else {
318                 client = clientBuilder.readTimeout(0, TimeUnit.SECONDS).register(filter).build();
319             }
320         }
321
322         SseEventSource eventSource = eventSourceFactory.newSource(client.target(restSseUrl));
323         eventSource.register(this::onEvent, this::onError, this::onComplete);
324         return eventSource;
325     }
326
327     private void reopenEventSource() {
328         logger.debug("Reopening EventSource");
329
330         String url;
331         try {
332             url = String.format(
333                     "%s?topics=%s/items/*/*,%s/things/*/*,%s/channels/*/triggered,openhab/channels/*/descriptionchanged",
334                     getRestApiUrl("events"), getTopicNamespace(), getTopicNamespace(), getTopicNamespace());
335         } catch (RemoteopenhabException e) {
336             logger.debug("reopenEventSource failed: {}", e.getMessage(bundle, i18nProvider));
337             return;
338         }
339
340         closeEventSource(true);
341
342         logger.debug("Opening new EventSource {}", url);
343         SseEventSource localEventSource = createEventSource(url);
344         localEventSource.open();
345
346         eventSource = localEventSource;
347     }
348
349     private void closeEventSource(boolean waitingForCompletion) {
350         SseEventSource localEventSource = eventSource;
351         if (localEventSource != null) {
352             if (!localEventSource.isOpen() || completed) {
353                 logger.debug("Existing EventSource is already closed");
354             } else if (localEventSource.close(waitingForCompletion ? 10 : 0, TimeUnit.SECONDS)) {
355                 logger.debug("Succesfully closed existing EventSource");
356             } else {
357                 logger.debug("Failed to close existing EventSource");
358             }
359             eventSource = null;
360         }
361         connected = false;
362     }
363
364     public boolean addStreamingDataListener(RemoteopenhabStreamingDataListener listener) {
365         return listeners.add(listener);
366     }
367
368     public boolean removeStreamingDataListener(RemoteopenhabStreamingDataListener listener) {
369         return listeners.remove(listener);
370     }
371
372     public boolean addItemsDataListener(RemoteopenhabItemsDataListener listener) {
373         return itemsListeners.add(listener);
374     }
375
376     public boolean removeItemsDataListener(RemoteopenhabItemsDataListener listener) {
377         return itemsListeners.remove(listener);
378     }
379
380     public boolean addThingsDataListener(RemoteopenhabThingsDataListener listener) {
381         return thingsListeners.add(listener);
382     }
383
384     public boolean removeThingsDataListener(RemoteopenhabThingsDataListener listener) {
385         return thingsListeners.remove(listener);
386     }
387
388     public long getLastEventTimestamp() {
389         return lastEventTimestamp;
390     }
391
392     private void onEvent(InboundSseEvent inboundEvent) {
393         String name = inboundEvent.getName();
394         String data = inboundEvent.readData();
395         logger.trace("Received event name {} data {}", name, data);
396
397         lastEventTimestamp = System.currentTimeMillis();
398         if (!connected) {
399             logger.debug("Connected to streaming events");
400             connected = true;
401             listeners.forEach(listener -> listener.onConnected());
402         }
403
404         if (!"message".equals(name)) {
405             logger.debug("Received unhandled event with name '{}' and data '{}'", name, data);
406             return;
407         }
408
409         try {
410             RemoteopenhabEvent event = jsonParser.fromJson(data, RemoteopenhabEvent.class);
411             String itemName;
412             String thingUID;
413             RemoteopenhabEventPayload payload;
414             RemoteopenhabItem item;
415             RemoteopenhabThing thing;
416             switch (event.type) {
417                 case "ItemStateEvent":
418                     itemName = extractItemNameFromTopic(event.topic, event.type, "state");
419                     payload = jsonParser.fromJson(event.payload, RemoteopenhabEventPayload.class);
420                     itemsListeners.forEach(
421                             listener -> listener.onItemStateEvent(itemName, payload.type, payload.value, false));
422                     break;
423                 case "ItemStateChangedEvent":
424                     itemName = extractItemNameFromTopic(event.topic, event.type, "statechanged");
425                     payload = jsonParser.fromJson(event.payload, RemoteopenhabEventPayload.class);
426                     itemsListeners.forEach(
427                             listener -> listener.onItemStateEvent(itemName, payload.type, payload.value, true));
428                     break;
429                 case "GroupItemStateChangedEvent":
430                     itemName = extractItemNameFromTopic(event.topic, event.type, "statechanged");
431                     payload = jsonParser.fromJson(event.payload, RemoteopenhabEventPayload.class);
432                     itemsListeners.forEach(
433                             listener -> listener.onItemStateEvent(itemName, payload.type, payload.value, false));
434                     break;
435                 case "ItemAddedEvent":
436                     itemName = extractItemNameFromTopic(event.topic, event.type, "added");
437                     item = Objects.requireNonNull(jsonParser.fromJson(event.payload, RemoteopenhabItem.class));
438                     itemsListeners.forEach(listener -> listener.onItemAdded(item));
439                     break;
440                 case "ItemRemovedEvent":
441                     itemName = extractItemNameFromTopic(event.topic, event.type, "removed");
442                     item = Objects.requireNonNull(jsonParser.fromJson(event.payload, RemoteopenhabItem.class));
443                     itemsListeners.forEach(listener -> listener.onItemRemoved(item));
444                     break;
445                 case "ItemUpdatedEvent":
446                     itemName = extractItemNameFromTopic(event.topic, event.type, "updated");
447                     RemoteopenhabItem[] updItem = jsonParser.fromJson(event.payload, RemoteopenhabItem[].class);
448                     if (updItem.length == 2) {
449                         itemsListeners.forEach(listener -> listener.onItemUpdated(updItem[0], updItem[1]));
450                     } else {
451                         logger.debug("Invalid payload for event type {} for topic {}", event.type, event.topic);
452                     }
453                     break;
454                 case "ThingStatusInfoChangedEvent":
455                     thingUID = extractThingUIDFromTopic(event.topic, event.type, "statuschanged");
456                     RemoteopenhabStatusInfo[] updStatus = jsonParser.fromJson(event.payload,
457                             RemoteopenhabStatusInfo[].class);
458                     if (updStatus.length == 2) {
459                         thingsListeners.forEach(listener -> listener.onThingStatusUpdated(thingUID, updStatus[0]));
460                     } else {
461                         logger.debug("Invalid payload for event type {} for topic {}", event.type, event.topic);
462                     }
463                     break;
464                 case "ThingAddedEvent":
465                     thingUID = extractThingUIDFromTopic(event.topic, event.type, "added");
466                     thing = Objects.requireNonNull(jsonParser.fromJson(event.payload, RemoteopenhabThing.class));
467                     thingsListeners.forEach(listener -> listener.onThingAdded(thing));
468                     break;
469                 case "ThingRemovedEvent":
470                     thingUID = extractThingUIDFromTopic(event.topic, event.type, "removed");
471                     thing = Objects.requireNonNull(jsonParser.fromJson(event.payload, RemoteopenhabThing.class));
472                     thingsListeners.forEach(listener -> listener.onThingRemoved(thing));
473                     break;
474                 case "ChannelTriggeredEvent":
475                     RemoteopenhabChannelTriggerEvent triggerEvent = jsonParser.fromJson(event.payload,
476                             RemoteopenhabChannelTriggerEvent.class);
477                     thingsListeners
478                             .forEach(listener -> listener.onChannelTriggered(triggerEvent.channel, triggerEvent.event));
479                     break;
480                 case "ChannelDescriptionChangedEvent":
481                     RemoteopenhabStateDescription stateDescription = new RemoteopenhabStateDescription();
482                     RemoteopenhabCommandDescription commandDescription = new RemoteopenhabCommandDescription();
483                     RemoteopenhabChannelDescriptionChangedEvent descriptionChanged = Objects.requireNonNull(
484                             jsonParser.fromJson(event.payload, RemoteopenhabChannelDescriptionChangedEvent.class));
485                     switch (descriptionChanged.field) {
486                         case "STATE_OPTIONS":
487                             RemoteopenhabStateOptions stateOptions = Objects.requireNonNull(
488                                     jsonParser.fromJson(descriptionChanged.value, RemoteopenhabStateOptions.class));
489                             stateDescription.options = stateOptions.options;
490                             break;
491                         case "COMMAND_OPTIONS":
492                             RemoteopenhabCommandOptions commandOptions = Objects.requireNonNull(
493                                     jsonParser.fromJson(descriptionChanged.value, RemoteopenhabCommandOptions.class));
494                             commandDescription.commandOptions = commandOptions.options;
495                             break;
496                         default:
497                             break;
498                     }
499                     if (stateDescription.options != null || commandDescription.commandOptions != null) {
500                         descriptionChanged.linkedItemNames.forEach(linkedItemName -> {
501                             RemoteopenhabItem item1 = new RemoteopenhabItem();
502                             item1.name = linkedItemName;
503                             item1.stateDescription = stateDescription;
504                             item1.commandDescription = commandDescription;
505                             itemsListeners.forEach(listener -> listener.onItemOptionsUpdatedd(item1));
506                         });
507                     }
508                     break;
509                 case "ItemStatePredictedEvent":
510                 case "ItemCommandEvent":
511                 case "ThingStatusInfoEvent":
512                 case "ThingUpdatedEvent":
513                     logger.trace("Ignored event type {} for topic {}", event.type, event.topic);
514                     break;
515                 default:
516                     logger.debug("Unexpected event type {} for topic {}", event.type, event.topic);
517                     break;
518             }
519         } catch (RemoteopenhabException | JsonSyntaxException e) {
520             logger.debug("An exception occurred while processing the inbound '{}' event containg data: {}", name, data,
521                     e);
522         }
523     }
524
525     private void onComplete() {
526         logger.debug("Disconnected from streaming events");
527         completed = true;
528         listeners.forEach(listener -> listener.onDisconnected());
529     }
530
531     private void onError(Throwable error) {
532         logger.debug("Error occurred while receiving events", error);
533         listeners.forEach(listener -> listener.onError("Error occurred while receiving events"));
534     }
535
536     private String extractItemNameFromTopic(String topic, String eventType, String finalPart)
537             throws RemoteopenhabException {
538         String[] parts = topic.split("/");
539         int expectedNbParts = "GroupItemStateChangedEvent".equals(eventType) ? 5 : 4;
540         if (parts.length != expectedNbParts || !getTopicNamespace().equals(parts[0]) || !"items".equals(parts[1])
541                 || !finalPart.equals(parts[parts.length - 1])) {
542             throw new RemoteopenhabException("@text/exception.invalid-event-topic", topic, eventType);
543         }
544         return parts[2];
545     }
546
547     private String extractThingUIDFromTopic(String topic, String eventType, String finalPart)
548             throws RemoteopenhabException {
549         String[] parts = topic.split("/");
550         int expectedNbParts = 4;
551         if (parts.length != expectedNbParts || !getTopicNamespace().equals(parts[0]) || !"things".equals(parts[1])
552                 || !finalPart.equals(parts[parts.length - 1])) {
553             throw new RemoteopenhabException("@text/exception.invalid-event-topic", topic, eventType);
554         }
555         return parts[2];
556     }
557
558     public String executeGetUrl(String url, String acceptHeader, boolean provideAccessToken, boolean asyncReading)
559             throws RemoteopenhabException {
560         return executeUrl(HttpMethod.GET, url, acceptHeader, null, null, provideAccessToken, asyncReading, true);
561     }
562
563     public String executeUrl(HttpMethod httpMethod, String url, String acceptHeader, @Nullable String content,
564             @Nullable String contentType, boolean provideAccessToken, boolean asyncReading, boolean retryIfEOF)
565             throws RemoteopenhabException {
566         final Request request = httpClient.newRequest(url).method(httpMethod)
567                 .timeout(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS).followRedirects(false)
568                 .header(HttpHeaders.ACCEPT, acceptHeader);
569
570         if (url.startsWith("https:") || authenticateAnyway) {
571             boolean useAlternativeHeader = false;
572             if (!credentialToken.isEmpty()) {
573                 request.header(HttpHeaders.AUTHORIZATION, "Basic " + credentialToken);
574                 useAlternativeHeader = true;
575             }
576             if (provideAccessToken && !accessToken.isEmpty()) {
577                 if (useAlternativeHeader) {
578                     request.header("X-OPENHAB-TOKEN", accessToken);
579                 } else {
580                     request.header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
581                 }
582             }
583         }
584
585         if (content != null && (HttpMethod.POST.equals(httpMethod) || HttpMethod.PUT.equals(httpMethod))
586                 && contentType != null) {
587             request.content(new StringContentProvider(content), contentType);
588         }
589
590         logger.debug("Request {} {}", request.getMethod(), request.getURI());
591
592         try {
593             if (asyncReading) {
594                 InputStreamResponseListener listener = new InputStreamResponseListener();
595                 request.send(listener);
596                 Response response = listener.get(5, TimeUnit.SECONDS);
597                 int statusCode = response.getStatus();
598                 if (statusCode != HttpStatus.OK_200) {
599                     response.abort(new Exception(response.getReason()));
600                     String statusLine = statusCode + " " + response.getReason();
601                     throw new RemoteopenhabException("@text/exception.http-call-failed", statusLine);
602                 }
603                 ByteArrayOutputStream responseContent = new ByteArrayOutputStream();
604                 try (InputStream input = listener.getInputStream()) {
605                     input.transferTo(responseContent);
606                 }
607                 return new String(responseContent.toByteArray(), StandardCharsets.UTF_8.name());
608             } else {
609                 ContentResponse response = request.send();
610                 int statusCode = response.getStatus();
611                 if (statusCode == HttpStatus.MOVED_PERMANENTLY_301 || statusCode == HttpStatus.FOUND_302) {
612                     String locationHeader = response.getHeaders().get(HttpHeaders.LOCATION);
613                     if (locationHeader != null && !locationHeader.isBlank()) {
614                         logger.debug("The remopte server redirected the request to this URL: {}", locationHeader);
615                         return executeUrl(httpMethod, locationHeader, acceptHeader, content, contentType,
616                                 provideAccessToken, asyncReading, retryIfEOF);
617                     } else {
618                         String statusLine = statusCode + " " + response.getReason();
619                         throw new RemoteopenhabException("@text/exception.http-call-failed", statusLine);
620                     }
621                 } else if (statusCode >= HttpStatus.BAD_REQUEST_400) {
622                     String statusLine = statusCode + " " + response.getReason();
623                     throw new RemoteopenhabException("@text/exception.http-call-failed", statusLine);
624                 }
625                 String encoding = response.getEncoding() != null ? response.getEncoding().replaceAll("\"", "").trim()
626                         : StandardCharsets.UTF_8.name();
627                 return new String(response.getContent(), encoding);
628             }
629         } catch (RemoteopenhabException e) {
630             throw e;
631         } catch (ExecutionException e) {
632             // After a long network outage, the first HTTP request will fail with an EOFException exception.
633             // We retry the request a second time in this case.
634             Throwable cause = e.getCause();
635             if (retryIfEOF && cause instanceof EOFException) {
636                 logger.debug("EOFException - retry the request");
637                 return executeUrl(httpMethod, url, acceptHeader, content, contentType, provideAccessToken, asyncReading,
638                         false);
639             } else {
640                 throw new RemoteopenhabException(e);
641             }
642         } catch (IOException | TimeoutException e) {
643             throw new RemoteopenhabException(e);
644         } catch (InterruptedException e) {
645             Thread.currentThread().interrupt();
646             throw new RemoteopenhabException(e);
647         }
648     }
649 }