1
22
23 package com.liferay.portal.servlet;
24
25 import com.liferay.portal.kernel.language.LanguageUtil;
26 import com.liferay.portal.kernel.util.LocaleUtil;
27 import com.liferay.portal.kernel.util.StringPool;
28 import com.liferay.portal.kernel.util.StringUtil;
29 import com.liferay.portal.kernel.util.Validator;
30 import com.liferay.portal.util.PortalInstances;
31 import com.liferay.util.servlet.ServletResponseUtil;
32
33 import java.io.IOException;
34
35 import java.util.Locale;
36
37 import javax.servlet.ServletException;
38 import javax.servlet.http.HttpServlet;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41
42 import org.apache.commons.logging.Log;
43 import org.apache.commons.logging.LogFactory;
44
45
51 public class LanguageServlet extends HttpServlet {
52
53 public void service(HttpServletRequest req, HttpServletResponse res)
54 throws IOException, ServletException {
55
56 String path = req.getPathInfo();
57
58 if (_log.isDebugEnabled()) {
59 _log.debug("Path " + path);
60 }
61
62 if (Validator.isNotNull(path) && path.startsWith(StringPool.SLASH)) {
63 path = path.substring(1, path.length());
64 }
65
66 String[] pathArray = StringUtil.split(path, StringPool.SLASH);
67
68 if (pathArray.length == 0) {
69 _log.error("Language id is not specified");
70
71 return;
72 }
73
74 if (pathArray.length == 1) {
75 _log.error("Language key is not specified");
76
77 return;
78 }
79
80 Locale locale = LocaleUtil.fromLanguageId(pathArray[0]);
81 String key = pathArray[1];
82
83 Object[] arguments = null;
84
85 if (pathArray.length > 2) {
86 arguments = new Object[pathArray.length - 2];
87
88 System.arraycopy(pathArray, 2, arguments, 0, arguments.length);
89 }
90
91 String value = key;
92
93 try {
94 long companyId = PortalInstances.getCompanyId(req);
95
96 if ((arguments == null) || (arguments.length == 0)) {
97 value = LanguageUtil.get(companyId, locale, key);
98 }
99 else {
100 value = LanguageUtil.format(companyId, locale, key, arguments);
101 }
102 }
103 catch (Exception e) {
104 if (_log.isWarnEnabled()) {
105 _log.warn(e, e);
106 }
107 }
108
109 res.setContentType(_CONTENT_TYPE);
110
111 ServletResponseUtil.write(res, value.getBytes("UTF-8"));
112 }
113
114 private static final String _CONTENT_TYPE = "text/plain; charset=UTF-8";
115
116 private static Log _log = LogFactory.getLog(LanguageServlet.class);
117
118 }