1
2
3
4 package de.powerstat.validation.values;
5
6
7 import java.util.Objects;
8 import java.util.regex.Pattern;
9
10 import de.powerstat.validation.generated.GeneratedISO3166A2;
11 import de.powerstat.validation.interfaces.IValueObject;
12
13
14
15
16
17
18
19
20
21 public final class Country implements Comparable<Country>, IValueObject
22 {
23
24
25
26
27
28
29
30
31 @SuppressWarnings("java:S5867")
32 private static final Pattern COUNTRY_REGEXP = Pattern.compile("^[A-Z]{2}$");
33
34
35
36
37 private final String alpha2;
38
39
40
41
42
43
44
45
46
47 private Country(final String alpha2)
48 {
49 super();
50 Objects.requireNonNull(alpha2, "alpha2");
51 if (alpha2.length() != 2)
52 {
53 throw new IllegalArgumentException("Length is not 2");
54 }
55 if (!Country.COUNTRY_REGEXP.matcher(alpha2).matches())
56 {
57 throw new IllegalArgumentException("alpha2 contains illegal character");
58 }
59 if (!GeneratedISO3166A2.contains(alpha2))
60 {
61 throw new IllegalArgumentException("Unknown ISO3166 Alpha-2 code: " + alpha2);
62 }
63 this.alpha2 = alpha2;
64 }
65
66
67
68
69
70
71
72
73 public static Country of(final String alpha2)
74 {
75
76
77
78
79
80
81
82
83
84
85
86
87
88 return new Country(alpha2);
89 }
90
91
92
93
94
95
96
97 @Override
98 public String stringValue()
99 {
100 return this.alpha2;
101 }
102
103
104
105
106
107
108
109 public String getEnglishCountryName()
110 {
111 return GeneratedISO3166A2.getName(this.alpha2);
112 }
113
114
115
116
117
118
119
120
121 @Override
122 public int hashCode()
123 {
124 return this.alpha2.hashCode();
125 }
126
127
128
129
130
131
132
133
134
135 @Override
136 public boolean equals(final Object obj)
137 {
138 if (this == obj)
139 {
140 return true;
141 }
142 if (!(obj instanceof Country))
143 {
144 return false;
145 }
146 final Country other = (Country)obj;
147 return this.alpha2.equals(other.alpha2);
148 }
149
150
151
152
153
154
155
156
157
158
159
160
161 @Override
162 public String toString()
163 {
164 final var builder = new StringBuilder();
165 builder.append("Country[alpha2=").append(this.alpha2).append(']');
166 return builder.toString();
167 }
168
169
170
171
172
173
174
175
176
177 @Override
178 public int compareTo(final Country obj)
179 {
180 Objects.requireNonNull(obj, "obj");
181 return this.alpha2.compareTo(obj.alpha2);
182 }
183
184 }