]> git.basschouten.com Git - openhab-addons.git/blob
8a8d4ef510f6154ed0ec4a8498f079df0661d5cb
[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.http.internal.http;
14
15 import java.net.URI;
16 import java.net.URISyntaxException;
17 import java.util.Date;
18 import java.util.List;
19 import java.util.Optional;
20 import java.util.Set;
21 import java.util.concurrent.CompletableFuture;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26 import java.util.function.Consumer;
27
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.eclipse.jetty.client.HttpClient;
31 import org.eclipse.jetty.client.api.Authentication;
32 import org.eclipse.jetty.client.api.AuthenticationStore;
33 import org.eclipse.jetty.client.api.Request;
34 import org.openhab.binding.http.internal.Util;
35 import org.openhab.binding.http.internal.config.HttpThingConfig;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * The {@link RefreshingUrlCache} is responsible for requesting from a single URL and passing the content to the
41  * channels
42  *
43  * @author Jan N. Klug - Initial contribution
44  */
45 @NonNullByDefault
46 public class RefreshingUrlCache {
47     private final Logger logger = LoggerFactory.getLogger(RefreshingUrlCache.class);
48
49     private final String url;
50     private final HttpClient httpClient;
51     private final int timeout;
52     private final @Nullable String fallbackEncoding;
53     private final Set<Consumer<Content>> consumers = ConcurrentHashMap.newKeySet();
54     private final List<String> headers;
55
56     private final ScheduledFuture<?> future;
57     private @Nullable Content lastContent;
58
59     public RefreshingUrlCache(ScheduledExecutorService executor, HttpClient httpClient, String url,
60             HttpThingConfig thingConfig) {
61         this.httpClient = httpClient;
62         this.url = url;
63         this.timeout = thingConfig.timeout;
64         this.headers = thingConfig.headers;
65         fallbackEncoding = thingConfig.encoding;
66
67         future = executor.scheduleWithFixedDelay(this::refresh, 0, thingConfig.refresh, TimeUnit.SECONDS);
68         logger.trace("Started refresh task for URL '{}' with interval {}s", url, thingConfig.refresh);
69     }
70
71     private void refresh() {
72         refresh(false);
73     }
74
75     private void refresh(boolean isRetry) {
76         if (consumers.isEmpty()) {
77             // do not refresh if we don't have listeners
78             return;
79         }
80
81         // format URL
82         try {
83             URI finalUrl = new URI(String.format(this.url, new Date()));
84
85             logger.trace("Requesting refresh (retry={}) from '{}' with timeout {}ms", isRetry, finalUrl, timeout);
86             Request request = httpClient.newRequest(finalUrl).timeout(timeout, TimeUnit.MILLISECONDS);
87
88             headers.forEach(header -> {
89                 String[] keyValuePair = header.split("=", 2);
90                 if (keyValuePair.length == 2) {
91                     request.header(keyValuePair[0].trim(), keyValuePair[1].trim());
92                 } else {
93                     logger.warn("Splitting header '{}' failed. No '=' was found. Ignoring", header);
94                 }
95             });
96
97             CompletableFuture<@Nullable Content> response = new CompletableFuture<>();
98             response.exceptionally(e -> {
99                 if (e instanceof HttpAuthException) {
100                     if (isRetry) {
101                         logger.warn("Retry after authentication  failure failed again for '{}', failing here",
102                                 finalUrl);
103                     } else {
104                         AuthenticationStore authStore = httpClient.getAuthenticationStore();
105                         Authentication.Result authResult = authStore.findAuthenticationResult(finalUrl);
106                         if (authResult != null) {
107                             authStore.removeAuthenticationResult(authResult);
108                             logger.debug("Cleared authentication result for '{}', retrying immediately", finalUrl);
109                             refresh(true);
110                         } else {
111                             logger.warn("Could not find authentication result for '{}', failing here", finalUrl);
112                         }
113                     }
114                 }
115                 return null;
116             }).thenAccept(this::processResult);
117
118             if (logger.isTraceEnabled()) {
119                 logger.trace("Sending to '{}': {}", finalUrl, Util.requestToLogString(request));
120             }
121
122             request.send(new HttpResponseListener(response, fallbackEncoding));
123         } catch (IllegalArgumentException | URISyntaxException e) {
124             logger.warn("Creating request for '{}' failed: {}", url, e.getMessage());
125         }
126     }
127
128     public void stop() {
129         // clearing all listeners to prevent further updates
130         consumers.clear();
131         future.cancel(false);
132         logger.trace("Stopped refresh task for URL '{}'", url);
133     }
134
135     public void addConsumer(Consumer<Content> consumer) {
136         consumers.add(consumer);
137     }
138
139     public Optional<Content> get() {
140         final Content content = lastContent;
141         if (content == null) {
142             return Optional.empty();
143         } else {
144             return Optional.of(content);
145         }
146     }
147
148     private void processResult(@Nullable Content content) {
149         if (content != null) {
150             for (Consumer<Content> consumer : consumers) {
151                 try {
152                     consumer.accept(content);
153                 } catch (IllegalArgumentException | IllegalStateException e) {
154                     logger.warn("Failed processing result for URL {}: {}", url, e.getMessage());
155                 }
156             }
157         }
158         lastContent = content;
159     }
160 }