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