2 * Copyright (c) 2010-2024 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.salus.internal.rest;
15 import static java.util.Objects.requireNonNull;
16 import static java.util.concurrent.TimeUnit.SECONDS;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.TimeoutException;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.eclipse.jetty.client.HttpResponseException;
24 import org.eclipse.jetty.client.api.Request;
25 import org.eclipse.jetty.client.util.StringContentProvider;
28 * @author Martin GrzeĊlowski - Initial contribution
31 public class HttpClient implements RestClient {
32 private static final int TIMEOUT = 10;
33 private static final int IDLE_TIMEOUT = TIMEOUT;
34 private final org.eclipse.jetty.client.HttpClient client;
36 public HttpClient(org.eclipse.jetty.client.HttpClient client) {
37 this.client = requireNonNull(client, "client");
38 if (this.client.isStopped()) {
39 throw new IllegalStateException("HttpClient is stopped");
44 public @Nullable String get(String url, @Nullable Header... headers) throws SalusApiException {
45 var request = requireNonNull(client.newRequest(url));
46 return execute(request, headers, url);
50 public @Nullable String post(String url, @Nullable Content content, @Nullable Header... headers)
51 throws SalusApiException {
52 var request = requireNonNull(client.POST(url));
53 if (content != null) {
54 request.content(new StringContentProvider(content.body()), content.type());
56 return execute(request, headers, url);
59 @SuppressWarnings("ConstantValue")
60 private @Nullable String execute(Request request, @Nullable Header[] headers, String url) throws SalusApiException {
62 if (headers != null) {
63 for (var header : headers) {
67 for (var value : header.values()) {
68 request.header(header.name(), value);
72 request.timeout(TIMEOUT, SECONDS);
73 request.idleTimeout(IDLE_TIMEOUT, SECONDS);
74 var response = request.send();
75 var status = response.getStatus();
76 if (status < 200 || status >= 399) {
77 throw new HttpSalusApiException(status, response.getReason());
79 return response.getContentAsString();
80 } catch (RuntimeException | TimeoutException | ExecutionException | InterruptedException ex) {
82 while (cause != null) {
83 if (cause instanceof HttpResponseException hte) {
84 var response = hte.getResponse();
85 throw new HttpSalusApiException(response.getStatus(), response.getReason(), hte);
87 cause = cause.getCause();
89 throw new SalusApiException("Error while executing request to " + url, ex);