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