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