summaryrefslogtreecommitdiffstats
path: root/org/madore/damlengine/LangHelper.java
blob: aea1240330f0ab2094222f8e0c8dde6f4bbb601c (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
60
61
62
63
64
65
package org.madore.damlengine;

import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.w3c.dom.Attr;

public class LangHelper {

    public static final String LANG = "lang";

    public static String getLangNorec(Node node) {
	// Returns null when no xml:lang attribute is found,
	// otherwise, returns its value.
	if ( node instanceof Element ) {
	    Attr lang = ((Element)node).
		getAttributeNodeNS(DamlEngine.XML_NS, LANG);
	    if ( lang == null )
		return null;
	    else
		return lang.getValue();
	} else
	    return null;
    }

    public static void setLangNorec(Element node, String lang) {
	if ( lang == null )
	    throw new NullPointerException("lang is null in setLangNorec");
	node.setAttributeNS(DamlEngine.XML_NS, LANG, lang);
    }

    public static void unsetLangNorec(Element node) {
	node.removeAttributeNS(DamlEngine.XML_NS, LANG);
    }

    public static void setWeakLangNorec(Element node, String lang) {
	if ( lang == null )
	    throw new NullPointerException("lang is null in setWeakLangNorec");
	String currentLang = getLangNorec(node);
	if ( currentLang == null )
	    setLangNorec(node,lang);
    }

    public static String getLangRec(Node node) {
	// Never returns null (returns the empty string for no language).
	// node may be null (in which case, return "").
	while ( node != null ) {
	    String lang = getLangNorec(node);
	    if ( lang != null )
		return lang;
	    node = node.getParentNode();
	}
	return "";
    }

    public static void setLangRec(Element node, String lang) {
	if ( lang == null )
	    throw new NullPointerException("lang is null in setLangRec");
	String parentLang = getLangRec(node.getParentNode());
	if ( lang.equals(parentLang) )
	    unsetLangNorec(node);
	else
	    setLangNorec(node,lang);
    }

}