]> WPIA git - gigi.git/blob - src/org/cacert/gigi/Language.java
6c03b19ca59694020952ff79e3c6159eb96137e4
[gigi.git] / src / org / cacert / gigi / Language.java
1 package org.cacert.gigi;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.util.HashMap;
7 import java.util.Locale;
8
9 import javax.xml.parsers.DocumentBuilder;
10 import javax.xml.parsers.DocumentBuilderFactory;
11 import javax.xml.parsers.ParserConfigurationException;
12
13 import org.cacert.gigi.util.HTMLEncoder;
14 import org.w3c.dom.Document;
15 import org.w3c.dom.Element;
16 import org.w3c.dom.NodeList;
17 import org.xml.sax.SAXException;
18
19 public class Language {
20
21     private static HashMap<String, Language> langs = new HashMap<String, Language>();
22
23     HashMap<String, String> translations = new HashMap<String, String>();
24
25     Locale l;
26
27     private Language(String language) throws ParserConfigurationException, IOException, SAXException {
28         if (language.contains("_")) {
29             String[] parts = language.split("_");
30             l = new Locale(parts[0], parts[1]);
31         } else {
32             l = new Locale(language);
33         }
34
35         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
36         DocumentBuilder db = dbf.newDocumentBuilder();
37         Document d = db.parse(new FileInputStream(new File("locale", language + ".xml")));
38         NodeList nl = d.getDocumentElement().getChildNodes();
39         for (int i = 0; i < nl.getLength(); i++) {
40             if ( !(nl.item(i) instanceof Element)) {
41                 continue;
42             }
43             Element e = (Element) nl.item(i);
44             Element id = (Element) e.getElementsByTagName("id").item(0);
45             Element msg = (Element) e.getElementsByTagName("msg").item(0);
46             translations.put(id.getTextContent(), HTMLEncoder.encodeHTML(msg.getTextContent()));
47         }
48         System.out.println(translations.size() + " strings loaded.");
49     }
50
51     public String getTranslation(String text) {
52         String string = translations.get(text);
53         if (string == null || string.equals("")) {
54             return text;
55         }
56         return string;
57     }
58
59     public static Language getInstance(String language) {
60         Language l = langs.get(language);
61         if (l == null) {
62             try {
63                 l = new Language(language);
64                 langs.put(language, l);
65             } catch (ParserConfigurationException e) {
66                 e.printStackTrace();
67             } catch (IOException e) {
68                 e.printStackTrace();
69             } catch (SAXException e) {
70                 e.printStackTrace();
71             }
72         }
73         return l;
74     }
75
76     public Locale getLocale() {
77         return l;
78     }
79
80 }