]> git.basschouten.com Git - openhab-addons.git/blob
d86fa1d798c20c448713ca9d9005e839274b2562
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.Map;
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.http.HttpMethod;
33 import org.openhab.binding.http.internal.Util;
34 import org.openhab.binding.http.internal.config.HttpThingConfig;
35 import org.openhab.core.thing.binding.generic.ChannelHandlerContent;
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 RateLimitedHttpClient httpClient;
51     private final boolean strictErrorHandling;
52     private final int timeout;
53     private final int bufferSize;
54     private final @Nullable String fallbackEncoding;
55     private final Set<Consumer<@Nullable ChannelHandlerContent>> consumers = ConcurrentHashMap.newKeySet();
56     private final Map<String, String> headers;
57     private final HttpMethod httpMethod;
58     private final String httpContent;
59     private final @Nullable String httpContentType;
60     private final HttpStatusListener httpStatusListener;
61
62     private final ScheduledFuture<?> future;
63     private @Nullable ChannelHandlerContent lastContent;
64
65     public RefreshingUrlCache(ScheduledExecutorService executor, RateLimitedHttpClient httpClient, String url,
66             HttpThingConfig thingConfig, String httpContent, @Nullable String httpContentType,
67             HttpStatusListener httpStatusListener) {
68         this.httpClient = httpClient;
69         this.url = url;
70         this.strictErrorHandling = thingConfig.strictErrorHandling;
71         this.timeout = thingConfig.timeout;
72         this.bufferSize = thingConfig.bufferSize;
73         this.httpMethod = thingConfig.stateMethod;
74         this.headers = thingConfig.getHeaders();
75         this.httpContent = httpContent;
76         this.httpContentType = httpContentType;
77         this.httpStatusListener = httpStatusListener;
78         fallbackEncoding = thingConfig.encoding;
79
80         future = executor.scheduleWithFixedDelay(this::refresh, 1, thingConfig.refresh, TimeUnit.SECONDS);
81         logger.trace("Started refresh task for URL '{}' with interval {}s", url, thingConfig.refresh);
82     }
83
84     private void refresh() {
85         refresh(false);
86     }
87
88     private void refresh(boolean isRetry) {
89         if (consumers.isEmpty()) {
90             // do not refresh if we don't have listeners
91             return;
92         }
93
94         // format URL
95         try {
96             URI uri = Util.uriFromString(String.format(this.url, new Date()));
97             logger.trace("Requesting refresh (retry={}) from '{}' with timeout {}ms", isRetry, uri, timeout);
98
99             httpClient.newRequest(uri, httpMethod, httpContent, httpContentType).thenAccept(request -> {
100                 request.timeout(timeout, TimeUnit.MILLISECONDS);
101                 headers.forEach(request::header);
102
103                 CompletableFuture<@Nullable ChannelHandlerContent> responseContentFuture = new CompletableFuture<>();
104                 responseContentFuture.exceptionally(t -> {
105                     if (t instanceof HttpAuthException) {
106                         if (isRetry || !httpClient.reAuth(uri)) {
107                             logger.debug("Authentication failed for '{}', retry={}", uri, isRetry);
108                             httpStatusListener.onHttpError("Authentication failed");
109                         } else {
110                             refresh(true);
111                         }
112                     }
113                     return null;
114                 }).thenAccept(this::processResult);
115
116                 if (logger.isTraceEnabled()) {
117                     logger.trace("Sending to '{}': {}", uri, Util.requestToLogString(request));
118                 }
119
120                 request.send(new HttpResponseListener(responseContentFuture, fallbackEncoding, bufferSize,
121                         httpStatusListener));
122             }).exceptionally(e -> {
123                 if (e instanceof CancellationException) {
124                     logger.debug("Request to URL {} was cancelled by thing handler.", uri);
125                 } else {
126                     logger.warn("Request to URL {} failed: {}", uri, e.getMessage());
127                 }
128                 return null;
129             });
130         } catch (IllegalArgumentException | URISyntaxException | MalformedURLException e) {
131             logger.warn("Creating request for '{}' failed: {}", url, e.getMessage());
132         }
133     }
134
135     public void stop() {
136         // clearing all listeners to prevent further updates
137         consumers.clear();
138         future.cancel(false);
139         logger.trace("Stopped refresh task for URL '{}'", url);
140     }
141
142     public void addConsumer(Consumer<@Nullable ChannelHandlerContent> consumer) {
143         consumers.add(consumer);
144     }
145
146     public Optional<ChannelHandlerContent> get() {
147         return Optional.ofNullable(lastContent);
148     }
149
150     private void processResult(@Nullable ChannelHandlerContent content) {
151         if (content != null || strictErrorHandling) {
152             for (Consumer<@Nullable ChannelHandlerContent> consumer : consumers) {
153                 try {
154                     consumer.accept(content);
155                 } catch (IllegalArgumentException | IllegalStateException e) {
156                     logger.warn("Failed processing result for URL {}: {}", url, e.getMessage());
157                 }
158             }
159         }
160         lastContent = content;
161     }
162 }