1 package org.cacert.gigi.dbObjects;
3 import org.cacert.gigi.GigiApiException;
4 import org.cacert.gigi.database.GigiPreparedStatement;
5 import org.cacert.gigi.database.GigiResultSet;
6 import org.cacert.gigi.output.template.SprintfCommand;
8 public class CountryCode {
10 public enum CountryCodeType {
11 CODE_2_CHARS(2, "SELECT `id`, `english` as country, `code2` as countrycode FROM `countryIsoCode` ORDER BY code2", "SELECT 1 FROM `countryIsoCode` WHERE `code2`=?"),//
12 CODE_3_CHARS(3, "SELECT `id`, `english` as country, `code3` as countrycode FROM `countryIsoCode` ORDER BY code3", "SELECT 1 FROM `countryIsoCode` WHERE `code3`=?");
14 private final String listQuery;
16 private final String validationQuery;
18 private final int len;
20 private CountryCodeType(int len, String listQuery, String validationQuery) {
22 this.listQuery = listQuery;
23 this.validationQuery = validationQuery;
30 public String getListQuery() {
34 public String getValidationQuery() {
35 return validationQuery;
41 private final String country;
43 private final String countryCode;
45 public CountryCode(int id, String country, String countryCode) {
47 this.country = country;
48 this.countryCode = countryCode;
55 public String getCountry() {
59 public String getCountryCode() {
63 public static CountryCode[] getCountryCodes(CountryCodeType clength) throws GigiApiException {
64 try (GigiPreparedStatement ps = new GigiPreparedStatement(clength.getListQuery(), true)) {
65 GigiResultSet rs = ps.executeQuery();
68 int totalCount = rs.getRow();
72 CountryCode[] finalResult = new CountryCode[totalCount];
74 finalResult[i] = new CountryCode(rs.getInt("id"), rs.getString("country"), rs.getString("countrycode"));
82 public static void checkCountryCode(String countrycode, CountryCodeType cType) throws GigiApiException {
83 if (countrycode.length() != cType.getLen()) {
84 throw new GigiApiException(SprintfCommand.createSimple("Country code length does not have the required length of {0} characters", Integer.toString(cType.getLen())));
86 try (GigiPreparedStatement ps = new GigiPreparedStatement(cType.getValidationQuery())) {
87 ps.setString(1, countrycode.toUpperCase());
88 GigiResultSet rs = ps.executeQuery();
91 throw new GigiApiException(SprintfCommand.createSimple("Country code {0} is not available in database", countrycode.toUpperCase()));