2 * Copyright (c) 2010-2023 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.exception;
15 import java.time.Duration;
16 import java.time.LocalDateTime;
17 import java.time.format.DateTimeFormatter;
18 import java.time.format.DateTimeParseException;
19 import java.util.Locale;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 * {@link RuntimeException} indicating that too many requests have been made against the cloud service.
29 * @author Björn Lange - Initial contribution
32 public class TooManyRequestsException extends RuntimeException {
33 private static final long serialVersionUID = 3393292912418862566L;
36 private final String retryAfter;
38 private final Logger logger = LoggerFactory.getLogger(this.getClass());
40 public TooManyRequestsException(String message, @Nullable String retryAfter) {
42 this.retryAfter = retryAfter;
46 * Gets whether a hint on when to retry the operation is available.
48 * @return Whether a hint on when to retry the operation is available.
50 public boolean hasRetryAfterHint() {
51 return retryAfter != null;
55 * Gets the number of seconds until the operation may be retried.
57 * @return The number of seconds until the operation may be retried. This will return -1 if no Retry-After header
58 * was present or parsing the data from the header fails.
60 public long getSecondsUntilRetry() {
61 String retryAfter = this.retryAfter;
62 if (retryAfter == null) {
63 logger.debug("Received no Retry-After header.");
67 logger.debug("Received Retry-After header: {}", retryAfter);
69 long seconds = Long.parseLong(retryAfter);
70 logger.debug("Interpreted Retry-After header value: {} seconds", seconds);
72 } catch (NumberFormatException e) {
73 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ccc, d MMM yyyy HH:mm:ss z", Locale.US);
76 LocalDateTime dateTime = LocalDateTime.parse(retryAfter, formatter);
77 logger.debug("Interpreted Retry-After header value: {}", dateTime);
79 Duration duration = Duration.between(LocalDateTime.now(), dateTime);
81 long seconds = Math.max(0, duration.toMillis() / 1000);
82 logger.debug("Interpreted Retry-After header value: {} seconds.", seconds);
84 } catch (DateTimeParseException dateTimeParseException) {
85 logger.warn("Unable to parse Retry-After header: {}", retryAfter);