]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/CountrySelector.java
chg: Refactor CountryCode class
[gigi.git] / src / org / cacert / gigi / output / CountrySelector.java
1 package org.cacert.gigi.output;
2
3 import java.io.PrintWriter;
4 import java.util.Map;
5
6 import javax.servlet.http.HttpServletRequest;
7
8 import org.cacert.gigi.GigiApiException;
9 import org.cacert.gigi.dbObjects.CountryCode;
10 import org.cacert.gigi.dbObjects.CountryCode.CountryCodeType;
11 import org.cacert.gigi.localisation.Language;
12 import org.cacert.gigi.output.template.Outputable;
13 import org.cacert.gigi.output.template.Template;
14
15 public class CountrySelector implements Outputable {
16
17     private static final Template t = new Template(CountrySelector.class.getResource("CountrySelector.templ"));
18
19     private CountryCode[] all = CountryCode.getCountryCodes(CountryCodeType.CODE_2_CHARS);
20
21     private String name;
22
23     private CountryCode selected;
24
25     private boolean optional;
26
27     public CountrySelector(String name, boolean optional) {
28         this.name = name;
29         this.optional = optional;
30     }
31
32     public CountrySelector(String name, boolean optional, CountryCode state) {
33         this(name, optional);
34         selected = state == null ? null : state.convertToCountryCodeType(CountryCodeType.CODE_2_CHARS);
35     }
36
37     public void update(HttpServletRequest r) throws GigiApiException {
38         String vS = r.getParameter(name);
39
40         selected = null;
41
42         if (vS == null || vS.equals("invalid")) {
43             if (optional) {
44                 return;
45             } else {
46                 throw new GigiApiException("Country code required.");
47             }
48         }
49
50         selected = CountryCode.getCountryCode(vS, CountryCodeType.CODE_2_CHARS);
51     }
52
53     @Override
54     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
55         vars.put("countryCode", new ArrayIterable<CountryCode>(all) {
56
57             @Override
58             public void apply(CountryCode t, Language l, Map<String, Object> vars) {
59                 vars.put("cc", t.getCountryCode());
60                 vars.put("display", t.getCountry());
61                 if (selected != null && t.getCountryCode().equals(selected.getCountryCode())) {
62                     vars.put("selected", "selected");
63                 } else {
64                     vars.put("selected", "");
65                 }
66             }
67
68         });
69
70         vars.put("optional", optional);
71         vars.put("name", name);
72
73         t.output(out, l, vars);
74     }
75
76     public CountryCode getCountry() {
77         return selected;
78     }
79
80 }