2 * Copyright (c) 2010-2022 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.mielecloud.internal.webservice.retry;
15 import java.util.function.Consumer;
16 import java.util.function.Supplier;
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;
25 * {@link RetryStrategy} retrying a failing operation for a number of times.
27 * @author Björn Lange - Initial contribution
30 public class NTimesRetryStrategy implements RetryStrategy {
31 private final int numberOfRetries;
34 * Creates a new {@link NTimesRetryStrategy}.
36 * @param numberOfRetries The number of retries to make.
37 * @throws IllegalArgumentException if {@code numberOfRetries} is smaller than zero.
39 public NTimesRetryStrategy(int numberOfRetries) {
40 if (numberOfRetries < 0) {
41 throw new IllegalArgumentException("Number of retries must not be negative.");
44 this.numberOfRetries = numberOfRetries;
48 public <@Nullable T> T performRetryableOperation(Supplier<T> operation, Consumer<Exception> onException) {
49 boolean obtainedReturnValue = false;
51 MieleWebserviceTransientException lastException = null;
52 for (int i = 0; !obtainedReturnValue && i < numberOfRetries + 1; i++) {
54 returnValue = operation.get();
55 obtainedReturnValue = true;
56 } catch (MieleWebserviceTransientException e) {
58 if (i < numberOfRetries) {
59 onException.accept(e);
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());