001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.servlet;
016    
017    import com.liferay.portal.NoSuchLayoutException;
018    import com.liferay.portal.kernel.language.LanguageUtil;
019    import com.liferay.portal.kernel.log.Log;
020    import com.liferay.portal.kernel.log.LogFactoryUtil;
021    import com.liferay.portal.kernel.util.CharPool;
022    import com.liferay.portal.kernel.util.GetterUtil;
023    import com.liferay.portal.kernel.util.LocaleUtil;
024    import com.liferay.portal.kernel.util.StringPool;
025    import com.liferay.portal.kernel.util.Validator;
026    import com.liferay.portal.kernel.xml.Element;
027    import com.liferay.portal.util.PortalUtil;
028    import com.liferay.portal.util.PropsValues;
029    import com.liferay.portal.util.WebKeys;
030    
031    import java.io.IOException;
032    
033    import java.util.Collections;
034    import java.util.HashMap;
035    import java.util.HashSet;
036    import java.util.List;
037    import java.util.Locale;
038    import java.util.Map;
039    import java.util.Set;
040    
041    import javax.servlet.RequestDispatcher;
042    import javax.servlet.ServletContext;
043    import javax.servlet.ServletException;
044    import javax.servlet.http.HttpServlet;
045    import javax.servlet.http.HttpServletRequest;
046    import javax.servlet.http.HttpServletResponse;
047    import javax.servlet.http.HttpSession;
048    
049    import jodd.util.StringUtil;
050    
051    import org.apache.struts.Globals;
052    
053    /**
054     * @author Brian Wing Shun Chan
055     */
056    public class I18nServlet extends HttpServlet {
057    
058            public static Set<String> getLanguageIds() {
059                    return new HashSet<String>(_languageIds.values());
060            }
061    
062            public static Map<String, String> getLanguageIdsMap() {
063                    return _languageIds;
064            }
065    
066            public static void setLanguageIds(Element root) {
067                    Map<String, String> languageIds = new HashMap<String, String>();
068    
069                    List<Element> rootElements = root.elements("servlet-mapping");
070    
071                    for (Element element : rootElements) {
072                            String servletName = element.elementText("servlet-name");
073    
074                            if (servletName.equals("I18n Servlet")) {
075                                    String urlPattern = element.elementText("url-pattern");
076    
077                                    String languageId = urlPattern.substring(
078                                            0, urlPattern.lastIndexOf(CharPool.SLASH));
079    
080                                    languageIds.put(StringUtil.toLowerCase(languageId), languageId);
081                            }
082                    }
083    
084                    _languageIds = Collections.unmodifiableMap(languageIds);
085            }
086    
087            @Override
088            public void service(
089                            HttpServletRequest request, HttpServletResponse response)
090                    throws IOException, ServletException {
091    
092                    try {
093                            String[] i18nData = getI18nData(request);
094    
095                            if ((i18nData == null) ||
096                                    !PortalUtil.isValidResourceId(i18nData[2])) {
097    
098                                    PortalUtil.sendError(
099                                            HttpServletResponse.SC_NOT_FOUND,
100                                            new NoSuchLayoutException(), request, response);
101                            }
102                            else {
103                                    String i18nLanguageId = i18nData[0];
104                                    String i18nPath = i18nData[1];
105                                    String redirect = i18nData[2];
106                                    String i18nLanguageCode = i18nData[3];
107    
108                                    request.setAttribute(
109                                            WebKeys.I18N_LANGUAGE_CODE, i18nLanguageCode);
110                                    request.setAttribute(WebKeys.I18N_LANGUAGE_ID, i18nLanguageId);
111                                    request.setAttribute(WebKeys.I18N_PATH, i18nPath);
112    
113                                    Locale locale = LocaleUtil.fromLanguageId(
114                                            i18nLanguageId, true, false);
115    
116                                    HttpSession session = request.getSession();
117    
118                                    session.setAttribute(Globals.LOCALE_KEY, locale);
119    
120                                    LanguageUtil.updateCookie(request, response, locale);
121    
122                                    ServletContext servletContext = getServletContext();
123    
124                                    RequestDispatcher requestDispatcher =
125                                            servletContext.getRequestDispatcher(redirect);
126    
127                                    requestDispatcher.forward(request, response);
128                            }
129                    }
130                    catch (Exception e) {
131                            _log.error(e, e);
132    
133                            PortalUtil.sendError(
134                                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e, request,
135                                    response);
136                    }
137            }
138    
139            protected String[] getI18nData(HttpServletRequest request) {
140                    String path = GetterUtil.getString(request.getPathInfo());
141    
142                    if (Validator.isNull(path)) {
143                            path = "/";
144                    }
145    
146                    String i18nLanguageId = request.getServletPath();
147    
148                    int pos = i18nLanguageId.lastIndexOf(CharPool.SLASH);
149    
150                    i18nLanguageId = i18nLanguageId.substring(pos + 1);
151    
152                    if (_log.isDebugEnabled()) {
153                            _log.debug("Language ID " + i18nLanguageId);
154                    }
155    
156                    if (Validator.isNull(i18nLanguageId)) {
157                            return null;
158                    }
159    
160                    String i18nPath = StringPool.SLASH + i18nLanguageId;
161    
162                    Locale locale = LocaleUtil.fromLanguageId(i18nLanguageId, true, false);
163    
164                    String i18nLanguageCode = i18nLanguageId;
165    
166                    if ((locale == null) || Validator.isNull(locale.getCountry())) {
167    
168                            // Locales must contain the country code
169    
170                            locale = LanguageUtil.getLocale(i18nLanguageCode);
171                    }
172    
173                    if (locale != null) {
174                            i18nLanguageId = LocaleUtil.toLanguageId(locale);
175                            i18nLanguageCode = locale.getLanguage();
176                    }
177    
178                    if (!PropsValues.LOCALE_USE_DEFAULT_IF_NOT_AVAILABLE &&
179                            !LanguageUtil.isAvailableLocale(i18nLanguageId)) {
180    
181                            return null;
182                    }
183    
184                    String redirect = path;
185    
186                    if (_log.isDebugEnabled()) {
187                            _log.debug("Redirect " + redirect);
188                    }
189    
190                    return new String[] {
191                            i18nLanguageId, i18nPath, redirect, i18nLanguageCode
192                    };
193            }
194    
195            private static Log _log = LogFactoryUtil.getLog(I18nServlet.class);
196    
197            private static Map<String, String> _languageIds;
198    
199    }