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