1
22
23 package com.liferay.portlet.journal.util;
24
25 import com.liferay.portal.kernel.util.LocaleUtil;
26 import com.liferay.portal.kernel.util.StringPool;
27 import com.liferay.portal.kernel.util.StringUtil;
28 import com.liferay.util.LocalizationUtil;
29
30 import java.io.StringReader;
31
32 import java.util.List;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36
37 import org.dom4j.Document;
38 import org.dom4j.Element;
39 import org.dom4j.io.SAXReader;
40
41
47 public class LocaleTransformerListener extends TransformerListener {
48
49 public String onXml(String s) {
50 if (_log.isDebugEnabled()) {
51 _log.debug("onXml");
52 }
53
54 s = localize(s);
55
56 return s;
57 }
58
59 public String onScript(String s) {
60 if (_log.isDebugEnabled()) {
61 _log.debug("onScript");
62 }
63
64 s = StringUtil.replace(s, "@language_id@", _requestedLocale);
65
66 return s;
67 }
68
69 public String onOutput(String s) {
70 if (_log.isDebugEnabled()) {
71 _log.debug("onOutput");
72 }
73
74 return s;
75 }
76
77 protected String localize(String xml) {
78 if (xml == null) {
79 return xml;
80 }
81
82 _requestedLocale = getLanguageId();
83
84 if (!isTemplateDriven()) {
85 return LocalizationUtil.getLocalization(xml, _requestedLocale);
86 }
87
88 try {
89 SAXReader reader = new SAXReader();
90
91 Document doc = reader.read(new StringReader(xml));
92
93 Element root = doc.getRootElement();
94
95 String defaultLanguageId = LocaleUtil.toLanguageId(
96 LocaleUtil.getDefault());
97
98 String[] availableLocales = StringUtil.split(
99 root.attributeValue("available-locales", defaultLanguageId));
100
101 String defaultLocale = root.attributeValue(
102 "default-locale", defaultLanguageId);
103
104 boolean isSupportedLocale = false;
105
106 for (int i = 0; i < availableLocales.length; i++) {
107 if (availableLocales[i].equalsIgnoreCase(getLanguageId())) {
108 isSupportedLocale = true;
109
110 break;
111 }
112 }
113
114 if (!isSupportedLocale) {
115 setLanguageId(defaultLocale);
116 }
117
118 localize(root);
119
120 xml = JournalUtil.formatXML(doc);
121 }
122 catch (Exception e) {
123 _log.error(e);
124 }
125
126 return xml;
127 }
128
129 protected void localize(Element root) {
130 List<Element> children = root.elements();
131
132 int listIndex = children.size() - 1;
133
134 while (listIndex >= 0) {
135 Element child = children.get(listIndex);
136
137 String languageId =
138 child.attributeValue("language-id", getLanguageId());
139
140 if (!languageId.equalsIgnoreCase(getLanguageId())) {
141 root.remove(child);
142 }
143 else{
144 localize(child);
145 }
146
147 listIndex--;
148 }
149 }
150
151 private static Log _log =
152 LogFactory.getLog(LocaleTransformerListener.class);
153
154 private String _requestedLocale = StringPool.BLANK;
155
156 }