2 * Copyright (c) 2010-2020 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.net.URISyntaxException;
17 import java.util.Date;
18 import java.util.List;
19 import java.util.Optional;
21 import java.util.concurrent.CompletableFuture;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26 import java.util.function.Consumer;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.eclipse.jetty.client.HttpClient;
31 import org.eclipse.jetty.client.api.Authentication;
32 import org.eclipse.jetty.client.api.AuthenticationStore;
33 import org.eclipse.jetty.client.api.Request;
34 import org.openhab.binding.http.internal.Util;
35 import org.openhab.binding.http.internal.config.HttpThingConfig;
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 HttpClient httpClient;
51 private final int timeout;
52 private final @Nullable String fallbackEncoding;
53 private final Set<Consumer<Content>> consumers = ConcurrentHashMap.newKeySet();
54 private final List<String> headers;
56 private final ScheduledFuture<?> future;
57 private @Nullable Content lastContent;
59 public RefreshingUrlCache(ScheduledExecutorService executor, HttpClient httpClient, String url,
60 HttpThingConfig thingConfig) {
61 this.httpClient = httpClient;
63 this.timeout = thingConfig.timeout;
64 this.headers = thingConfig.headers;
65 fallbackEncoding = thingConfig.encoding;
67 future = executor.scheduleWithFixedDelay(this::refresh, 0, 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 finalUrl = new URI(String.format(this.url, new Date()));
85 logger.trace("Requesting refresh (retry={}) from '{}' with timeout {}ms", isRetry, finalUrl, timeout);
86 Request request = httpClient.newRequest(finalUrl).timeout(timeout, TimeUnit.MILLISECONDS);
88 headers.forEach(header -> {
89 String[] keyValuePair = header.split("=", 2);
90 if (keyValuePair.length == 2) {
91 request.header(keyValuePair[0].trim(), keyValuePair[1].trim());
93 logger.warn("Splitting header '{}' failed. No '=' was found. Ignoring", header);
97 CompletableFuture<@Nullable Content> response = new CompletableFuture<>();
98 response.exceptionally(e -> {
99 if (e instanceof HttpAuthException) {
101 logger.warn("Retry after authentication failure failed again for '{}', failing here",
104 AuthenticationStore authStore = httpClient.getAuthenticationStore();
105 Authentication.Result authResult = authStore.findAuthenticationResult(finalUrl);
106 if (authResult != null) {
107 authStore.removeAuthenticationResult(authResult);
108 logger.debug("Cleared authentication result for '{}', retrying immediately", finalUrl);
111 logger.warn("Could not find authentication result for '{}', failing here", finalUrl);
116 }).thenAccept(this::processResult);
118 if (logger.isTraceEnabled()) {
119 logger.trace("Sending to '{}': {}", finalUrl, Util.requestToLogString(request));
122 request.send(new HttpResponseListener(response, fallbackEncoding));
123 } catch (IllegalArgumentException | URISyntaxException e) {
124 logger.warn("Creating request for '{}' failed: {}", url, e.getMessage());
129 // clearing all listeners to prevent further updates
131 future.cancel(false);
132 logger.trace("Stopped refresh task for URL '{}'", url);
135 public void addConsumer(Consumer<Content> consumer) {
136 consumers.add(consumer);
139 public Optional<Content> get() {
140 final Content content = lastContent;
141 if (content == null) {
142 return Optional.empty();
144 return Optional.of(content);
148 private void processResult(@Nullable Content content) {
149 if (content != null) {
150 for (Consumer<Content> consumer : consumers) {
152 consumer.accept(content);
153 } catch (IllegalArgumentException | IllegalStateException e) {
154 logger.warn("Failed processing result for URL {}: {}", url, e.getMessage());
158 lastContent = content;