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.core.retry.conditions;
17
18 import java.util.Collections;
19 import java.util.LinkedHashSet;
20 import java.util.Set;
21 import software.amazon.awssdk.annotations.SdkPublicApi;
22 import software.amazon.awssdk.core.retry.RetryPolicyContext;
23 import software.amazon.awssdk.utils.ToString;
24 import software.amazon.awssdk.utils.Validate;
25
26 /**
27  * Composite {@link RetryCondition} that evaluates to true when all contained retry conditions evaluate to true.
28  */

29 @SdkPublicApi
30 public final class AndRetryCondition implements RetryCondition {
31
32     private final Set<RetryCondition> conditions = new LinkedHashSet<>();
33
34     private AndRetryCondition(RetryCondition... conditions) {
35         Collections.addAll(this.conditions, Validate.notEmpty(conditions, "%s cannot be empty.""conditions"));
36     }
37
38     public static AndRetryCondition create(RetryCondition... conditions) {
39         return new AndRetryCondition(conditions);
40     }
41
42     /**
43      * @return True if all conditions are truefalse otherwise.
44      */

45     @Override
46     public boolean shouldRetry(RetryPolicyContext context) {
47         return conditions.stream().allMatch(r -> r.shouldRetry(context));
48     }
49
50     @Override
51     public void requestWillNotBeRetried(RetryPolicyContext context) {
52         conditions.forEach(c -> c.requestWillNotBeRetried(context));
53     }
54
55     @Override
56     public void requestSucceeded(RetryPolicyContext context) {
57         conditions.forEach(c -> c.requestSucceeded(context));
58     }
59
60     @Override
61     public boolean equals(Object o) {
62         if (this == o) {
63             return true;
64         }
65         if (o == null || getClass() != o.getClass()) {
66             return false;
67         }
68
69         AndRetryCondition that = (AndRetryCondition) o;
70
71         return conditions.equals(that.conditions);
72     }
73
74     @Override
75     public int hashCode() {
76         return conditions.hashCode();
77     }
78
79     @Override
80     public String toString() {
81         return ToString.builder("AndRetryCondition")
82                        .add("conditions", conditions)
83                        .build();
84     }
85 }
86