1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 }