2 * Copyright (c) 2010-2024 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.http.internal.http;
15 import java.net.MalformedURLException;
17 import java.net.URISyntaxException;
18 import java.util.Date;
20 import java.util.Optional;
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;
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;
40 * The {@link RefreshingUrlCache} is responsible for requesting from a single URL and passing the content to the
43 * @author Jan N. Klug - Initial contribution
46 public class RefreshingUrlCache {
47 private final Logger logger = LoggerFactory.getLogger(RefreshingUrlCache.class);
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;
62 private final ScheduledFuture<?> future;
63 private @Nullable ChannelHandlerContent lastContent;
65 public RefreshingUrlCache(ScheduledExecutorService executor, RateLimitedHttpClient httpClient, String url,
66 HttpThingConfig thingConfig, String httpContent, @Nullable String httpContentType,
67 HttpStatusListener httpStatusListener) {
68 this.httpClient = httpClient;
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;
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);
84 private void refresh() {
88 private void refresh(boolean isRetry) {
89 if (consumers.isEmpty()) {
90 // do not refresh if we don't have listeners
96 URI uri = Util.uriFromString(String.format(this.url, new Date()));
97 logger.trace("Requesting refresh (retry={}) from '{}' with timeout {}ms", isRetry, uri, timeout);
99 httpClient.newRequest(uri, httpMethod, httpContent, httpContentType).thenAccept(request -> {
100 request.timeout(timeout, TimeUnit.MILLISECONDS);
101 headers.forEach(request::header);
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");
114 }).thenAccept(this::processResult);
116 if (logger.isTraceEnabled()) {
117 logger.trace("Sending to '{}': {}", uri, Util.requestToLogString(request));
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);
126 logger.warn("Request to URL {} failed: {}", uri, e.getMessage());
130 } catch (IllegalArgumentException | URISyntaxException | MalformedURLException e) {
131 logger.warn("Creating request for '{}' failed: {}", url, e.getMessage());
136 // clearing all listeners to prevent further updates
138 future.cancel(false);
139 logger.trace("Stopped refresh task for URL '{}'", url);
142 public void addConsumer(Consumer<@Nullable ChannelHandlerContent> consumer) {
143 consumers.add(consumer);
146 public Optional<ChannelHandlerContent> get() {
147 return Optional.ofNullable(lastContent);
150 private void processResult(@Nullable ChannelHandlerContent content) {
151 if (content != null || strictErrorHandling) {
152 for (Consumer<@Nullable ChannelHandlerContent> consumer : consumers) {
154 consumer.accept(content);
155 } catch (IllegalArgumentException | IllegalStateException e) {
156 logger.warn("Failed processing result for URL {}: {}", url, e.getMessage());
160 lastContent = content;