]> git.basschouten.com Git - openhab-addons.git/blob
45730114716c182df34a2321eafc39fd03e452d0
[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.mielecloud.internal.webservice.retry;
14
15 import java.util.function.Consumer;
16 import java.util.function.Supplier;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.mielecloud.internal.webservice.ConnectionError;
21 import org.openhab.binding.mielecloud.internal.webservice.exception.MieleWebserviceException;
22 import org.openhab.binding.mielecloud.internal.webservice.exception.MieleWebserviceTransientException;
23
24 /**
25  * {@link RetryStrategy} retrying a failing operation for a number of times.
26  *
27  * @author Björn Lange - Initial contribution
28  */
29 @NonNullByDefault
30 public class NTimesRetryStrategy implements RetryStrategy {
31     private final int numberOfRetries;
32
33     /**
34      * Creates a new {@link NTimesRetryStrategy}.
35      *
36      * @param numberOfRetries The number of retries to make.
37      * @throws IllegalArgumentException if {@code numberOfRetries} is smaller than zero.
38      */
39     public NTimesRetryStrategy(int numberOfRetries) {
40         if (numberOfRetries < 0) {
41             throw new IllegalArgumentException("Number of retries must not be negative.");
42         }
43
44         this.numberOfRetries = numberOfRetries;
45     }
46
47     @Override
48     public <@Nullable T> T performRetryableOperation(Supplier<T> operation, Consumer<Exception> onException) {
49         boolean obtainedReturnValue = false;
50         T returnValue = null;
51         MieleWebserviceTransientException lastException = null;
52         for (int i = 0; !obtainedReturnValue && i < numberOfRetries + 1; i++) {
53             try {
54                 returnValue = operation.get();
55                 obtainedReturnValue = true;
56             } catch (MieleWebserviceTransientException e) {
57                 lastException = e;
58                 if (i < numberOfRetries) {
59                     onException.accept(e);
60                 }
61             }
62         }
63
64         if (!obtainedReturnValue) {
65             throw new MieleWebserviceException(
66                     "Unable to perform operation. Operation failed " + (numberOfRetries + 1) + " times.", lastException,
67                     lastException == null ? ConnectionError.UNKNOWN : lastException.getConnectionError());
68         } else {
69             return returnValue;
70         }
71     }
72 }