1 /*
2  * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License").
5  * You may not use this file except in compliance with the License.
6  * A copy of the License is located at
7  *
8  *  http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */

15
16 package software.amazon.awssdk.awscore.retry.conditions;
17
18 import java.util.Arrays;
19 import java.util.Set;
20 import java.util.stream.Collectors;
21 import software.amazon.awssdk.annotations.SdkPublicApi;
22 import software.amazon.awssdk.awscore.exception.AwsServiceException;
23 import software.amazon.awssdk.core.retry.RetryPolicyContext;
24 import software.amazon.awssdk.core.retry.conditions.RetryCondition;
25
26 /**
27  * Retry condition implementation that retries if the exception or the cause of the exception matches the error codes defined.
28  */

29 @SdkPublicApi
30 public final class RetryOnErrorCodeCondition implements RetryCondition {
31
32     private final Set<String> retryableErrorCodes;
33
34     private RetryOnErrorCodeCondition(Set<String> retryableErrorCodes) {
35         this.retryableErrorCodes = retryableErrorCodes;
36     }
37
38     @Override
39     public boolean shouldRetry(RetryPolicyContext context) {
40
41         Exception ex = context.exception();
42         if (ex instanceof AwsServiceException) {
43             AwsServiceException exception = (AwsServiceException) ex;
44
45             return retryableErrorCodes.contains(exception.awsErrorDetails().errorCode());
46         }
47         return false;
48     }
49
50     public static RetryOnErrorCodeCondition create(String... retryableErrorCodes) {
51         return new RetryOnErrorCodeCondition(Arrays.stream(retryableErrorCodes).collect(Collectors.toSet()));
52     }
53
54     public static RetryOnErrorCodeCondition create(Set<String> retryableErrorCodes) {
55         return new RetryOnErrorCodeCondition(retryableErrorCodes);
56     }
57 }
58