aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/xml/LocalizedContent.java
blob: c327ded8340447ed8aba8408133e9a08558e36a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package de.pixart.messenger.xml;

import com.google.common.collect.Iterables;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class LocalizedContent {

    public static final String STREAM_LANGUAGE = "en";

    public final String content;
    public final String language;
    public final int count;

    private LocalizedContent(String content, String language, int count) {
        this.content = content;
        this.language = language;
        this.count = count;
    }

    public static LocalizedContent get(final Element element, String name) {
        final HashMap<String, String> contents = new HashMap<>();
        final String parentLanguage = element.getAttribute("xml:lang");
        for (Element child : element.children) {
            if (name.equals(child.getName())) {
                final String namespace = child.getNamespace();
                final String childLanguage = child.getAttribute("xml:lang");
                final String lang = childLanguage == null ? parentLanguage : childLanguage;
                final String content = child.getContent();
                if (content != null && (namespace == null || "jabber:client".equals(namespace))) {
                    if (contents.put(lang, content) != null) {
                        //anything that has multiple contents for the same language is invalid
                        return null;
                    }
                }
            }
        }
        if (contents.size() == 0) {
            return null;
        }
        final String userLanguage = Locale.getDefault().getLanguage();
        final String localized = contents.get(userLanguage);
        if (localized != null) {
            return new LocalizedContent(localized, userLanguage, contents.size());
        }
        final String defaultLanguageContent = contents.get(null);
        if (defaultLanguageContent != null) {
            return new LocalizedContent(defaultLanguageContent, STREAM_LANGUAGE, contents.size());
        }
        final String streamLanguageContent = contents.get(STREAM_LANGUAGE);
        if (streamLanguageContent != null) {
            return new LocalizedContent(streamLanguageContent, STREAM_LANGUAGE, contents.size());
        }
        final Map.Entry<String, String> first = Iterables.get(contents.entrySet(), 0);
        return new LocalizedContent(first.getValue(), first.getKey(), contents.size());
    }
}