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.auth.credentials.internal;
17
18 import java.util.function.Supplier;
19 import software.amazon.awssdk.annotations.SdkInternalApi;
20 import software.amazon.awssdk.auth.credentials.AwsCredentials;
21 import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
22 import software.amazon.awssdk.utils.IoUtils;
23 import software.amazon.awssdk.utils.Lazy;
24 import software.amazon.awssdk.utils.SdkAutoCloseable;
25 import software.amazon.awssdk.utils.ToString;
26
27 /**
28  * A wrapper for {@link AwsCredentialsProvider} that defers creation of the underlying provider until the first time the
29  * {@link AwsCredentialsProvider#resolveCredentials()} method is invoked.
30  */

31 @SdkInternalApi
32 public class LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable {
33     private final Lazy<AwsCredentialsProvider> delegate;
34
35     private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> delegateConstructor) {
36         this.delegate = new Lazy<>(delegateConstructor);
37     }
38
39     public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) {
40         return new LazyAwsCredentialsProvider(delegateConstructor);
41     }
42
43     @Override
44     public AwsCredentials resolveCredentials() {
45         return delegate.getValue().resolveCredentials();
46     }
47
48     @Override
49     public void close() {
50         IoUtils.closeIfCloseable(delegate, null);
51     }
52
53     @Override
54     public String toString() {
55         return ToString.builder("LazyAwsCredentialsProvider")
56                        .add("delegate", delegate)
57                        .build();
58     }
59 }
60