1 /*
2  * Copyright 2011-2020 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 package com.amazonaws.regions;
16
17
18 import com.amazonaws.SdkClientException;
19 import com.amazonaws.annotation.SdkTestInternalApi;
20 import com.amazonaws.auth.profile.internal.AllProfiles;
21 import com.amazonaws.auth.profile.internal.AwsProfileNameLoader;
22 import com.amazonaws.auth.profile.internal.BasicProfile;
23 import com.amazonaws.auth.profile.internal.BasicProfileConfigLoader;
24 import com.amazonaws.profile.path.AwsProfileFileLocationProvider;
25 import com.amazonaws.util.StringUtils;
26
27 import java.io.File;
28
29 /**
30  * Loads region information from the shared AWS config file. Uses the default profile unless
31  * otherwise specified.
32  */

33 public class AwsProfileRegionProvider extends AwsRegionProvider {
34
35     private final String profileName;
36     private final AwsProfileFileLocationProvider locationProvider;
37     private final BasicProfileConfigLoader profileConfigLoader;
38
39     public AwsProfileRegionProvider() {
40         this(AwsProfileNameLoader.INSTANCE.loadProfileName());
41     }
42
43     public AwsProfileRegionProvider(String profileName) {
44         this(profileName, AwsProfileFileLocationProvider.DEFAULT_CONFIG_LOCATION_PROVIDER,
45              BasicProfileConfigLoader.INSTANCE);
46     }
47
48     @SdkTestInternalApi
49     AwsProfileRegionProvider(String profileName, AwsProfileFileLocationProvider locationProvider,
50                              BasicProfileConfigLoader configLoader) {
51         this.profileName = profileName;
52         this.locationProvider = locationProvider;
53         this.profileConfigLoader = configLoader;
54     }
55
56     @Override
57     public String getRegion() throws SdkClientException {
58         File configFile = locationProvider.getLocation();
59         if (configFile != null && configFile.exists()) {
60             BasicProfile profile = loadProfile(configFile);
61             if (profile != null && !StringUtils.isNullOrEmpty(profile.getRegion())) {
62                 return profile.getRegion();
63             }
64         }
65         return null;
66     }
67
68     private BasicProfile loadProfile(File configFile) {
69         final AllProfiles allProfiles = profileConfigLoader.loadProfiles(configFile);
70         return allProfiles.getProfile(profileName);
71     }
72
73 }
74