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