2 * Copyright (c) 2010-2021 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;
16 import java.util.Date;
17 import java.util.List;
18 import java.util.Optional;
20 import java.util.concurrent.*;
21 import java.util.function.Consumer;
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;
34 * The {@link RefreshingUrlCache} is responsible for requesting from a single URL and passing the content to the
37 * @author Jan N. Klug - Initial contribution
40 public class RefreshingUrlCache {
41 private final Logger logger = LoggerFactory.getLogger(RefreshingUrlCache.class);
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;
53 private final ScheduledFuture<?> future;
54 private @Nullable Content lastContent;
56 public RefreshingUrlCache(ScheduledExecutorService executor, RateLimitedHttpClient httpClient, String url,
57 HttpThingConfig thingConfig, String httpContent) {
58 this.httpClient = httpClient;
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;
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);
71 private void refresh() {
75 private void refresh(boolean isRetry) {
76 if (consumers.isEmpty()) {
77 // do not refresh if we don't have listeners
83 URI uri = Util.uriFromString(String.format(this.url, new Date()));
84 logger.trace("Requesting refresh (retry={}) from '{}' with timeout {}ms", isRetry, uri, timeout);
86 httpClient.newRequest(uri, httpMethod, httpContent).thenAccept(request -> {
87 request.timeout(timeout, TimeUnit.MILLISECONDS);
89 headers.forEach(header -> {
90 String[] keyValuePair = header.split("=", 2);
91 if (keyValuePair.length == 2) {
92 request.header(keyValuePair[0].trim(), keyValuePair[1].trim());
94 logger.warn("Splitting header '{}' failed. No '=' was found. Ignoring", header);
98 CompletableFuture<@Nullable Content> response = new CompletableFuture<>();
99 response.exceptionally(e -> {
100 if (e instanceof HttpAuthException) {
102 logger.warn("Retry after authentication failure failed again for '{}', failing here", uri);
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);
111 logger.warn("Could not find authentication result for '{}', failing here", uri);
116 }).thenAccept(this::processResult);
118 if (logger.isTraceEnabled()) {
119 logger.trace("Sending to '{}': {}", uri, Util.requestToLogString(request));
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);
127 logger.warn("Request to URL {} failed: {}", uri, e.getMessage());
131 } catch (IllegalArgumentException | URISyntaxException | MalformedURLException e) {
132 logger.warn("Creating request for '{}' failed: {}", url, e.getMessage());
137 // clearing all listeners to prevent further updates
139 future.cancel(false);
140 logger.trace("Stopped refresh task for URL '{}'", url);
143 public void addConsumer(Consumer<Content> consumer) {
144 consumers.add(consumer);
147 public Optional<Content> get() {
148 final Content content = lastContent;
149 if (content == null) {
150 return Optional.empty();
152 return Optional.of(content);
156 private void processResult(@Nullable Content content) {
157 if (content != null) {
158 for (Consumer<Content> consumer : consumers) {
160 consumer.accept(content);
161 } catch (IllegalArgumentException | IllegalStateException e) {
162 logger.warn("Failed processing result for URL {}: {}", url, e.getMessage());
166 lastContent = content;