1
14
15 package com.liferay.portal.servlet;
16
17 import com.liferay.portal.kernel.language.LanguageUtil;
18 import com.liferay.portal.kernel.log.Log;
19 import com.liferay.portal.kernel.log.LogFactoryUtil;
20 import com.liferay.portal.kernel.util.ContentTypes;
21 import com.liferay.portal.kernel.util.LocaleUtil;
22 import com.liferay.portal.kernel.util.StringPool;
23 import com.liferay.portal.kernel.util.StringUtil;
24 import com.liferay.portal.kernel.util.Validator;
25 import com.liferay.util.servlet.ServletResponseUtil;
26
27 import java.io.IOException;
28
29 import java.util.Locale;
30
31 import javax.servlet.http.HttpServlet;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34
35
40 public class LanguageServlet extends HttpServlet {
41
42 public void service(
43 HttpServletRequest request, HttpServletResponse response)
44 throws IOException {
45
46 String path = request.getPathInfo();
47
48 if (_log.isDebugEnabled()) {
49 _log.debug("Path " + path);
50 }
51
52 if (Validator.isNotNull(path) && path.startsWith(StringPool.SLASH)) {
53 path = path.substring(1, path.length());
54 }
55
56 String[] pathArray = StringUtil.split(path, StringPool.SLASH);
57
58 if (pathArray.length == 0) {
59 _log.error("Language id is not specified");
60
61 return;
62 }
63
64 if (pathArray.length == 1) {
65 _log.error("Language key is not specified");
66
67 return;
68 }
69
70 Locale locale = LocaleUtil.fromLanguageId(pathArray[0]);
71 String key = pathArray[1];
72
73 Object[] arguments = null;
74
75 if (pathArray.length > 2) {
76 arguments = new Object[pathArray.length - 2];
77
78 System.arraycopy(pathArray, 2, arguments, 0, arguments.length);
79 }
80
81 String value = key;
82
83 try {
84 if ((arguments == null) || (arguments.length == 0)) {
85 value = LanguageUtil.get(locale, key);
86 }
87 else {
88 value = LanguageUtil.format(locale, key, arguments);
89 }
90 }
91 catch (Exception e) {
92 if (_log.isWarnEnabled()) {
93 _log.warn(e, e);
94 }
95 }
96
97 response.setContentType(ContentTypes.TEXT_PLAIN_UTF8);
98
99 ServletResponseUtil.write(response, value.getBytes(StringPool.UTF8));
100 }
101
102 private static Log _log = LogFactoryUtil.getLog(LanguageServlet.class);
103
104 }