]> git.basschouten.com Git - openhab-addons.git/blob
a9b0bee84d3d62979a5d2dd2dbecbd3c71fad9a8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.nio.charset.StandardCharsets;
16 import java.util.Objects;
17 import java.util.concurrent.CompletableFuture;
18 import java.util.stream.Collectors;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.eclipse.jetty.client.api.Request;
23 import org.eclipse.jetty.client.api.Response;
24 import org.eclipse.jetty.client.api.Result;
25 import org.eclipse.jetty.client.util.BufferingResponseListener;
26 import org.eclipse.jetty.http.HttpField;
27 import org.eclipse.jetty.http.HttpStatus;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * The {@link HttpResponseListener} is responsible for processing the result of a HTTP request
33  *
34  * @author Jan N. Klug - Initial contribution
35  */
36 @NonNullByDefault
37 public class HttpResponseListener extends BufferingResponseListener {
38     private final Logger logger = LoggerFactory.getLogger(HttpResponseListener.class);
39     private final CompletableFuture<@Nullable Content> future;
40     private final String fallbackEncoding;
41
42     /**
43      * the HttpResponseListener is responsible
44      *
45      * @param future Content future to complete with the result of the request
46      * @param fallbackEncoding a fallback encoding for the content (UTF-8 if null)
47      * @param bufferSize the buffer size for the content in kB (default 2048 kB)
48      */
49     public HttpResponseListener(CompletableFuture<@Nullable Content> future, @Nullable String fallbackEncoding,
50             int bufferSize) {
51         super(bufferSize * 1024);
52         this.future = future;
53         this.fallbackEncoding = fallbackEncoding != null ? fallbackEncoding : StandardCharsets.UTF_8.name();
54     }
55
56     @Override
57     public void onComplete(@NonNullByDefault({}) Result result) {
58         Response response = result.getResponse();
59         if (logger.isTraceEnabled()) {
60             logger.trace("Received from '{}': {}", result.getRequest().getURI(), responseToLogString(response));
61         }
62         Request request = result.getRequest();
63         if (result.isFailed()) {
64             logger.warn("Requesting '{}' (method='{}', content='{}') failed: {}", request.getURI(), request.getMethod(),
65                     request.getContent(), result.getFailure().toString());
66             future.complete(null);
67         } else if (HttpStatus.isSuccess(response.getStatus())) {
68             String encoding = Objects.requireNonNullElse(getEncoding(), fallbackEncoding);
69             future.complete(new Content(getContent(), encoding, getMediaType()));
70         } else {
71             switch (response.getStatus()) {
72                 case HttpStatus.UNAUTHORIZED_401:
73                     logger.debug("Requesting '{}' (method='{}', content='{}') failed: Authorization error",
74                             request.getURI(), request.getMethod(), request.getContent());
75                     future.completeExceptionally(new HttpAuthException());
76                     break;
77                 default:
78                     logger.warn("Requesting '{}' (method='{}', content='{}') failed: {} {}", request.getURI(),
79                             request.getMethod(), request.getContent(), response.getStatus(), response.getReason());
80                     future.completeExceptionally(new IllegalStateException("Response - Code" + response.getStatus()));
81             }
82         }
83     }
84
85     private String responseToLogString(Response response) {
86         String logString = "Code = {" + response.getStatus() + "}, Headers = {"
87                 + response.getHeaders().stream().map(HttpField::toString).collect(Collectors.joining(", "))
88                 + "}, Content = {" + getContentAsString() + "}";
89         return logString;
90     }
91 }