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