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.fronius.internal.api;
15 import java.io.IOException;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jetty.http.HttpMethod;
19 import org.openhab.core.io.net.http.HttpUtil;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
25 * A version of HttpUtil implementation that retries on failure.
27 * @author Jimmy Tanagra - Initial contribution
31 public class FroniusHttpUtil {
32 private static final Logger logger = LoggerFactory.getLogger(FroniusHttpUtil.class);
35 * Issue a HTTP request and retry on failure.
37 * @param httpMethod the HTTP method to use
38 * @param url the url to execute
39 * @param timeout the socket timeout in milliseconds to wait for data
40 * @return the response body
41 * @throws FroniusCommunicationException when the request execution failed or interrupted
43 public static synchronized String executeUrl(HttpMethod httpMethod, String url, int timeout)
44 throws FroniusCommunicationException {
48 Throwable lastException = null;
51 result = HttpUtil.executeUrl(httpMethod.asString(), url, timeout);
52 } catch (IOException e) {
53 // HttpUtil::executeUrl wraps InterruptedException into IOException.
54 // Unwrap and rethrow it so that we don't retry on InterruptedException
55 Throwable cause = e.getCause();
56 if (cause instanceof InterruptedException interruptException) {
57 throw interruptException;
63 if (attemptCount > 1) {
64 logger.debug("Attempt #{} successful {}", attemptCount, url);
69 if (attemptCount >= 3) {
70 logger.debug("Failed connecting to {} after {} attempts.", url, attemptCount, lastException);
71 throw new FroniusCommunicationException("Unable to connect", lastException);
74 logger.debug("HTTP error on attempt #{} {}", attemptCount, url);
75 Thread.sleep(500 * attemptCount);
78 } catch (InterruptedException e) {
79 Thread.currentThread().interrupt();
80 throw new FroniusCommunicationException("Interrupted", e);