View Javadoc
1   /*
2    * Copyright (c) 2016 ingenieux Labs
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    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package br.com.ingenieux.mojo.beanstalk.util;
18  
19  import com.google.common.base.Predicate;
20  
21  import com.amazonaws.regions.Region;
22  import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
23  
24  import org.apache.commons.lang.StringUtils;
25  
26  import java.util.Set;
27  import java.util.TreeSet;
28  import java.util.regex.Matcher;
29  import java.util.regex.Pattern;
30  
31  import static java.lang.String.format;
32  
33  public class EnvironmentHostnameUtil {
34    public static final Pattern PATTERN_HOSTNAME =
35        Pattern.compile("(?<cnamePrefix>[\\p{Alnum}\\-]{4,63})(?<regionName>.\\p{Alpha}{2}\\-\\p{Alpha}{4,9}\\-\\p{Digit})?\\Q.elasticbeanstalk.com\\E$");
36  
37    public static Predicate<EnvironmentDescription> getHostnamePredicate(Region region, String cnamePrefix) {
38      final Set<String> hostnamesToMatch = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
39  
40      hostnamesToMatch.add(format("%s.elasticbeanstalk.com", cnamePrefix).toLowerCase());
41      hostnamesToMatch.add(format("%s.%s.elasticbeanstalk.com", cnamePrefix, region.getName()).toLowerCase());
42  
43      return new Predicate<EnvironmentDescription>() {
44        @Override
45        public boolean apply(EnvironmentDescription t) {
46          return hostnamesToMatch.contains(t.getCNAME());
47        }
48  
49        @Override
50        public String toString() {
51          return format("... with cname belonging to %s", StringUtils.join(hostnamesToMatch.iterator(), " or "));
52        }
53      };
54    }
55  
56    public static String ensureSuffix(String cname, Region region) {
57      if (PATTERN_HOSTNAME.matcher(cname).matches()) {
58        return cname;
59      } else {
60        return format("%s.%s.elasticbeanstalk.com", cname, region.toString());
61      }
62    }
63  
64    public static String ensureSuffixStripped(String cnamePrefix) {
65      final Matcher matcher = PATTERN_HOSTNAME.matcher(cnamePrefix);
66  
67      if (matcher.matches()) {
68        return matcher.group("cnamePrefix");
69      }
70  
71      return cnamePrefix;
72    }
73  }