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.regions.providers;
17
18 import java.util.function.Supplier;
19 import software.amazon.awssdk.annotations.SdkProtectedApi;
20 import software.amazon.awssdk.core.exception.SdkClientException;
21 import software.amazon.awssdk.profiles.ProfileFile;
22 import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
23 import software.amazon.awssdk.profiles.ProfileProperty;
24 import software.amazon.awssdk.regions.Region;
25
26 /**
27  * Loads region information from the {@link ProfileFile#defaultProfileFile()} using the default profile name.
28  */

29 @SdkProtectedApi
30 public final class AwsProfileRegionProvider implements AwsRegionProvider {
31     private final Supplier<ProfileFile> profileFile;
32     private final String profileName;
33
34     public AwsProfileRegionProvider() {
35         this(nullnull);
36     }
37
38     public AwsProfileRegionProvider(Supplier<ProfileFile> profileFile, String profileName) {
39         this.profileFile = profileFile != null ? profileFile : ProfileFile::defaultProfileFile;
40         this.profileName = profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
41     }
42
43     @Override
44     public Region getRegion() {
45         return profileFile.get()
46                           .profile(profileName)
47                           .map(p -> p.properties().get(ProfileProperty.REGION))
48                           .map(Region::of)
49                           .orElseThrow(() -> SdkClientException.builder()
50                                                                .message("No region provided in profile: " + profileName)
51                                                                .build());
52     }
53 }
54
55