001
014
015 package com.liferay.portal.servlet;
016
017 import com.liferay.portal.kernel.language.LanguageUtil;
018 import com.liferay.portal.kernel.log.Log;
019 import com.liferay.portal.kernel.log.LogFactoryUtil;
020 import com.liferay.portal.kernel.util.ContentTypes;
021 import com.liferay.portal.kernel.util.LocaleUtil;
022 import com.liferay.portal.kernel.util.StringPool;
023 import com.liferay.portal.kernel.util.StringUtil;
024 import com.liferay.portal.kernel.util.Validator;
025 import com.liferay.util.servlet.ServletResponseUtil;
026
027 import java.io.IOException;
028
029 import java.util.Locale;
030
031 import javax.servlet.http.HttpServlet;
032 import javax.servlet.http.HttpServletRequest;
033 import javax.servlet.http.HttpServletResponse;
034
035
038 public class LanguageServlet extends HttpServlet {
039
040 public void service(
041 HttpServletRequest request, HttpServletResponse response)
042 throws IOException {
043
044 String path = request.getPathInfo();
045
046 if (_log.isDebugEnabled()) {
047 _log.debug("Path " + path);
048 }
049
050 if (Validator.isNotNull(path) && path.startsWith(StringPool.SLASH)) {
051 path = path.substring(1, path.length());
052 }
053
054 String[] pathArray = StringUtil.split(path, StringPool.SLASH);
055
056 if (pathArray.length == 0) {
057 _log.error("Language id is not specified");
058
059 return;
060 }
061
062 if (pathArray.length == 1) {
063 _log.error("Language key is not specified");
064
065 return;
066 }
067
068 Locale locale = LocaleUtil.fromLanguageId(pathArray[0]);
069 String key = pathArray[1];
070
071 Object[] arguments = null;
072
073 if (pathArray.length > 2) {
074 arguments = new Object[pathArray.length - 2];
075
076 System.arraycopy(pathArray, 2, arguments, 0, arguments.length);
077 }
078
079 String value = key;
080
081 try {
082 if ((arguments == null) || (arguments.length == 0)) {
083 value = LanguageUtil.get(locale, key);
084 }
085 else {
086 value = LanguageUtil.format(locale, key, arguments);
087 }
088 }
089 catch (Exception e) {
090 if (_log.isWarnEnabled()) {
091 _log.warn(e, e);
092 }
093 }
094
095 response.setContentType(ContentTypes.TEXT_PLAIN_UTF8);
096
097 ServletResponseUtil.write(response, value.getBytes(StringPool.UTF8));
098 }
099
100 private static Log _log = LogFactoryUtil.getLog(LanguageServlet.class);
101
102 }