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