1 /*
2  * Copyright 2010-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.internal.config;
16
17 import java.util.regex.Pattern;
18 import java.util.regex.PatternSyntaxException;
19
20 import com.amazonaws.annotation.Immutable;
21
22 @Immutable
23 public class HostRegexToRegionMapping {
24
25     private final String regionName;
26     private final Pattern hostNameRegexPattern;
27
28     public HostRegexToRegionMapping(
29             String hostNameRegex, String regionName) {
30         if (hostNameRegex == null || hostNameRegex.isEmpty()) {
31             throw new IllegalArgumentException(
32                     "Invalid HostRegexToRegionMapping configuration: " +
33                     "hostNameRegex must be non-empty");
34         }
35         try {
36             this.hostNameRegexPattern = Pattern.compile(hostNameRegex);
37         } catch (PatternSyntaxException e) {
38             throw new IllegalArgumentException(
39                     "Invalid HostRegexToRegionMapping configuration: " +
40                     "hostNameRegex is not a valid regex",
41                     e);
42         }
43         if (regionName == null || regionName.isEmpty()) {
44             throw new IllegalArgumentException(
45                     "Invalid HostRegexToRegionMapping configuration: " +
46                     "regionName must be non-empty");
47         }
48         this.regionName = regionName;
49     }
50
51     public String getRegionName() {
52         return regionName;
53     }
54     
55     public boolean isHostNameMatching(String hostname) {
56         return hostNameRegexPattern.matcher(hostname).matches();
57     }
58 }
59