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