1 package org.cacert.gigi.localisation;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.util.HashMap;
7 import java.util.LinkedList;
8 import java.util.Locale;
10 import javax.xml.parsers.DocumentBuilder;
11 import javax.xml.parsers.DocumentBuilderFactory;
12 import javax.xml.parsers.ParserConfigurationException;
14 import org.w3c.dom.Document;
15 import org.w3c.dom.Element;
16 import org.w3c.dom.NodeList;
17 import org.xml.sax.SAXException;
19 public class Language {
21 public static final String SESSION_ATTRIB_NAME = "lang";
23 private static Locale[] supportedLocales;
26 LinkedList<Locale> supported = new LinkedList<>();
27 File locales = new File("locale");
28 for (File f : locales.listFiles()) {
29 if ( !f.getName().endsWith(".xml")) {
32 String language = f.getName().split("\\.", 2)[0];
33 supported.add(getLocaleFromString(language));
35 supportedLocales = supported.toArray(new Locale[supported.size()]);
38 public static Locale getLocaleFromString(String language) {
39 if (language.contains("_")) {
40 String[] parts = language.split("_", 2);
41 return new Locale(parts[0], parts[1]);
44 return new Locale(language);
48 public static Locale[] getSupportedLocales() {
49 return supportedLocales;
52 private static HashMap<String, Language> langs = new HashMap<String, Language>();
54 private HashMap<String, String> translations = new HashMap<String, String>();
58 private static Locale project(Locale l) {
60 return Locale.getDefault();
62 File file = new File("locale", l.toString() + ".xml");
63 if ( !file.exists()) {
64 return new Locale(l.getLanguage());
69 protected Language(Locale loc) throws ParserConfigurationException, IOException, SAXException {
70 File file = new File("locale", loc.toString() + ".xml");
72 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
73 DocumentBuilder db = dbf.newDocumentBuilder();
74 Document d = db.parse(new FileInputStream(file));
75 NodeList nl = d.getDocumentElement().getChildNodes();
76 for (int i = 0; i < nl.getLength(); i++) {
77 if ( !(nl.item(i) instanceof Element)) {
80 Element e = (Element) nl.item(i);
81 Element id = (Element) e.getElementsByTagName("id").item(0);
82 Element msg = (Element) e.getElementsByTagName("msg").item(0);
83 translations.put(id.getTextContent(), msg.getTextContent());
85 System.out.println(translations.size() + " strings loaded.");
88 public String getTranslation(String text) {
89 String string = translations.get(text);
90 if (string == null || string.equals("")) {
96 public static Language getInstance(Locale language) {
97 language = project(language);
98 File file = new File("locale", language.toString() + ".xml");
99 if ( !file.exists()) {
102 Language l = langs.get(language.toString());
105 l = new Language(language);
106 langs.put(language.toString(), l);
107 } catch (ParserConfigurationException e) {
109 } catch (IOException e) {
111 } catch (SAXException e) {
118 public Locale getLocale() {