]> git.basschouten.com Git - openhab-addons.git/blob
d28fc960fe52fc87ca05eb63e1d2f6a1979fb7be
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.salus.internal.rest;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 /**
21  * @author Martin GrzeĊ›lowski - Initial contribution
22  */
23 @NonNullByDefault
24 public class RetryHttpClient implements RestClient {
25     private final Logger logger = LoggerFactory.getLogger(RetryHttpClient.class);
26     private final RestClient restClient;
27     private final int maxRetries;
28
29     public RetryHttpClient(RestClient restClient, int maxRetries) {
30         this.restClient = restClient;
31         if (maxRetries <= 0) {
32             throw new IllegalArgumentException("maxRetries cannot be lower or equal to 0, but was " + maxRetries);
33         }
34         this.maxRetries = maxRetries;
35     }
36
37     @Override
38     public @Nullable String get(String url, @Nullable Header... headers) throws SalusApiException {
39         for (int i = 0; i < maxRetries; i++) {
40             try {
41                 return restClient.get(url, headers);
42             } catch (SalusApiException ex) {
43                 if (i < maxRetries - 1) {
44                     logger.debug("Error while calling GET {}. Retrying {}/{}...", i + 1, maxRetries, url, ex);
45                 } else {
46                     throw ex;
47                 }
48             }
49         }
50         throw new IllegalStateException("Should not happen!");
51     }
52
53     @Override
54     public @Nullable String post(String url, Content content, @Nullable Header... headers) throws SalusApiException {
55         for (int i = 0; i < maxRetries; i++) {
56             try {
57                 return restClient.post(url, content, headers);
58             } catch (SalusApiException ex) {
59                 if (i < maxRetries - 1) {
60                     logger.debug("Error while calling POST {}. Retrying {}/{}...", i + 1, maxRetries, url, ex);
61                 } else {
62                     throw ex;
63                 }
64             }
65         }
66         throw new IllegalStateException("Should not happen!");
67     }
68 }