1 package org.cacert.gigi.dbObjects;
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.LinkedList;
9 import java.util.Random;
11 import org.cacert.gigi.GigiApiException;
12 import org.cacert.gigi.database.GigiPreparedStatement;
13 import org.cacert.gigi.database.GigiResultSet;
14 import org.cacert.gigi.output.template.SprintfCommand;
16 public class Country {
18 public enum CountryCodeType {
22 private final int len;
24 private CountryCodeType(int len) {
35 private final String country;
37 private final String countryCode2;
39 private final String countryCode3;
41 private static final List<Country> countries;
43 private static final Map<String, Country> byString;
45 LinkedList<Country> cs = new LinkedList<>();
46 HashMap<String, Country> ccd = new HashMap<>();
47 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id`, `english` as country, `code2`, `code3` FROM `countryIsoCode`", true)) {
48 GigiResultSet rs = ps.executeQuery();
50 Country e = new Country(rs);
51 ccd.put(e.countryCode2, e);
52 ccd.put(e.countryCode3, e);
56 countries = Collections.unmodifiableList(new ArrayList<>(cs));
57 byString = Collections.unmodifiableMap(ccd);
60 private Country(GigiResultSet rs) {
61 this.id = rs.getInt("id");
62 this.country = rs.getString("country");
63 this.countryCode2 = rs.getString("code2");
64 this.countryCode3 = rs.getString("code3");
71 public String getName() {
75 public String getCode() {
79 public String getCode(CountryCodeType type) {
86 throw new IllegalArgumentException("Enum switch was non-exhaustive");
90 public static List<Country> getCountries() {
94 public static void checkCountryCode(String countrycode, CountryCodeType cType) throws GigiApiException {
95 getCountryByCode(countrycode, cType);
98 public static Country getCountryByCode(String countrycode, CountryCodeType cType) throws GigiApiException {
99 if (countrycode.length() != cType.getLen()) {
100 throw new GigiApiException(SprintfCommand.createSimple("Country code length does not have the required length of {0} characters", Integer.toString(cType.getLen())));
102 Country i = byString.get(countrycode);
104 throw new GigiApiException("Country Code was wrong.");
109 public static Country getRandomCountry() {
110 List<Country> cc = Country.getCountries();
111 int rnd = new Random().nextInt(cc.size());