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;
15 import java.net.MalformedURLException;
17 import java.net.URISyntaxException;
18 import java.util.Date;
19 import java.util.List;
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.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;
41 * The {@link RefreshingUrlCache} is responsible for requesting from a single URL and passing the content to the
44 * @author Jan N. Klug - Initial contribution
47 public class RefreshingUrlCache {
48 private final Logger logger = LoggerFactory.getLogger(RefreshingUrlCache.class);
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;
60 private final ScheduledFuture<?> future;
61 private @Nullable Content lastContent;
63 public RefreshingUrlCache(ScheduledExecutorService executor, RateLimitedHttpClient httpClient, String url,
64 HttpThingConfig thingConfig, String httpContent) {
65 this.httpClient = httpClient;
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;
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);
78 private void refresh() {
82 private void refresh(boolean isRetry) {
83 if (consumers.isEmpty()) {
84 // do not refresh if we don't have listeners
90 URI uri = Util.uriFromString(String.format(this.url, new Date()));
91 logger.trace("Requesting refresh (retry={}) from '{}' with timeout {}ms", isRetry, uri, timeout);
93 httpClient.newRequest(uri, httpMethod, httpContent).thenAccept(request -> {
94 request.timeout(timeout, TimeUnit.MILLISECONDS);
96 headers.forEach(header -> {
97 String[] keyValuePair = header.split("=", 2);
98 if (keyValuePair.length == 2) {
99 request.header(keyValuePair[0].trim(), keyValuePair[1].trim());
101 logger.warn("Splitting header '{}' failed. No '=' was found. Ignoring", header);
105 CompletableFuture<@Nullable Content> response = new CompletableFuture<>();
106 response.exceptionally(e -> {
107 if (e instanceof HttpAuthException) {
109 logger.warn("Retry after authentication failure failed again for '{}', failing here", uri);
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);
118 logger.warn("Could not find authentication result for '{}', failing here", uri);
123 }).thenAccept(this::processResult);
125 if (logger.isTraceEnabled()) {
126 logger.trace("Sending to '{}': {}", uri, Util.requestToLogString(request));
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);
134 logger.warn("Request to URL {} failed: {}", uri, e.getMessage());
138 } catch (IllegalArgumentException | URISyntaxException | MalformedURLException e) {
139 logger.warn("Creating request for '{}' failed: {}", url, e.getMessage());
144 // clearing all listeners to prevent further updates
146 future.cancel(false);
147 logger.trace("Stopped refresh task for URL '{}'", url);
150 public void addConsumer(Consumer<Content> consumer) {
151 consumers.add(consumer);
154 public Optional<Content> get() {
155 final Content content = lastContent;
156 if (content == null) {
157 return Optional.empty();
159 return Optional.of(content);
163 private void processResult(@Nullable Content content) {
164 if (content != null) {
165 for (Consumer<Content> consumer : consumers) {
167 consumer.accept(content);
168 } catch (IllegalArgumentException | IllegalStateException e) {
169 logger.warn("Failed processing result for URL {}: {}", url, e.getMessage());
173 lastContent = content;