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