]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/CountrySelector.java
add: factor out country selection and type-restrict internal api.
[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) throws GigiApiException {
28         this.name = name;
29         this.optional = optional;
30     }
31
32     public CountrySelector(String name, boolean optional, String state) throws GigiApiException {
33         this(name, optional);
34         selected = CountryCode.getCountryCode(state, CountryCodeType.CODE_2_CHARS);
35
36     }
37
38     public void update(HttpServletRequest r) throws GigiApiException {
39         String vS = r.getParameter(name);
40         selected = null;
41         if (vS == null || vS.equals("invalid")) {
42             if (optional) {
43                 return;
44             } else {
45                 throw new GigiApiException("Country code required.");
46             }
47         }
48         selected = CountryCode.getCountryCode(vS, CountryCodeType.CODE_2_CHARS);
49
50     }
51
52     @Override
53     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
54         vars.put("countryCode", new ArrayIterable<CountryCode>(all) {
55
56             @Override
57             public void apply(CountryCode t, Language l, Map<String, Object> vars) {
58                 vars.put("cc", t.getCountryCode());
59                 vars.put("display", t.getCountry());
60                 if (selected != null && t.getCountryCode().equals(selected.getCountryCode())) {
61                     vars.put("selected", "selected");
62                 } else {
63                     vars.put("selected", "");
64                 }
65             }
66         });
67         vars.put("optional", optional);
68         vars.put("name", name);
69         t.output(out, l, vars);
70     }
71
72     public CountryCode getCountry() {
73         return selected;
74     }
75
76 }