001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.servlet;
016    
017    import com.liferay.portal.NoSuchLayoutException;
018    import com.liferay.portal.dao.shard.ShardDataSourceTargetSource;
019    import com.liferay.portal.events.EventsProcessorUtil;
020    import com.liferay.portal.events.StartupAction;
021    import com.liferay.portal.kernel.cache.Lifecycle;
022    import com.liferay.portal.kernel.cache.ThreadLocalCacheManager;
023    import com.liferay.portal.kernel.deploy.hot.HotDeployUtil;
024    import com.liferay.portal.kernel.exception.PortalException;
025    import com.liferay.portal.kernel.exception.SystemException;
026    import com.liferay.portal.kernel.language.LanguageUtil;
027    import com.liferay.portal.kernel.log.Log;
028    import com.liferay.portal.kernel.log.LogFactoryUtil;
029    import com.liferay.portal.kernel.patcher.PatchInconsistencyException;
030    import com.liferay.portal.kernel.patcher.PatcherUtil;
031    import com.liferay.portal.kernel.plugin.PluginPackage;
032    import com.liferay.portal.kernel.servlet.DynamicServletRequest;
033    import com.liferay.portal.kernel.servlet.PortalSessionThreadLocal;
034    import com.liferay.portal.kernel.servlet.SerializableSessionAttributeListener;
035    import com.liferay.portal.kernel.util.ContentTypes;
036    import com.liferay.portal.kernel.util.GetterUtil;
037    import com.liferay.portal.kernel.util.HttpUtil;
038    import com.liferay.portal.kernel.util.InfrastructureUtil;
039    import com.liferay.portal.kernel.util.InstanceFactory;
040    import com.liferay.portal.kernel.util.LocaleUtil;
041    import com.liferay.portal.kernel.util.ParamUtil;
042    import com.liferay.portal.kernel.util.PortalLifecycleUtil;
043    import com.liferay.portal.kernel.util.PropsKeys;
044    import com.liferay.portal.kernel.util.ReleaseInfo;
045    import com.liferay.portal.kernel.util.StringPool;
046    import com.liferay.portal.kernel.util.StringUtil;
047    import com.liferay.portal.kernel.util.Validator;
048    import com.liferay.portal.kernel.xml.Document;
049    import com.liferay.portal.kernel.xml.DocumentException;
050    import com.liferay.portal.kernel.xml.Element;
051    import com.liferay.portal.kernel.xml.UnsecureSAXReaderUtil;
052    import com.liferay.portal.model.Company;
053    import com.liferay.portal.model.Group;
054    import com.liferay.portal.model.GroupConstants;
055    import com.liferay.portal.model.Layout;
056    import com.liferay.portal.model.LayoutConstants;
057    import com.liferay.portal.model.LayoutTemplate;
058    import com.liferay.portal.model.Portlet;
059    import com.liferay.portal.model.PortletApp;
060    import com.liferay.portal.model.PortletFilter;
061    import com.liferay.portal.model.PortletURLListener;
062    import com.liferay.portal.model.Theme;
063    import com.liferay.portal.model.User;
064    import com.liferay.portal.plugin.PluginPackageUtil;
065    import com.liferay.portal.security.auth.CompanyThreadLocal;
066    import com.liferay.portal.security.auth.PrincipalException;
067    import com.liferay.portal.security.permission.ResourceActionsUtil;
068    import com.liferay.portal.server.capabilities.ServerCapabilitiesUtil;
069    import com.liferay.portal.service.CompanyLocalServiceUtil;
070    import com.liferay.portal.service.GroupLocalServiceUtil;
071    import com.liferay.portal.service.LayoutLocalServiceUtil;
072    import com.liferay.portal.service.LayoutTemplateLocalServiceUtil;
073    import com.liferay.portal.service.PortletLocalServiceUtil;
074    import com.liferay.portal.service.ResourceActionLocalServiceUtil;
075    import com.liferay.portal.service.ThemeLocalServiceUtil;
076    import com.liferay.portal.service.UserLocalServiceUtil;
077    import com.liferay.portal.servlet.filters.absoluteredirects.AbsoluteRedirectsResponse;
078    import com.liferay.portal.servlet.filters.i18n.I18nFilter;
079    import com.liferay.portal.setup.SetupWizardUtil;
080    import com.liferay.portal.struts.PortletRequestProcessor;
081    import com.liferay.portal.struts.StrutsUtil;
082    import com.liferay.portal.util.ClassLoaderUtil;
083    import com.liferay.portal.util.ExtRegistry;
084    import com.liferay.portal.util.MaintenanceUtil;
085    import com.liferay.portal.util.Portal;
086    import com.liferay.portal.util.PortalInstances;
087    import com.liferay.portal.util.PortalUtil;
088    import com.liferay.portal.util.PropsUtil;
089    import com.liferay.portal.util.PropsValues;
090    import com.liferay.portal.util.ShutdownUtil;
091    import com.liferay.portal.util.WebKeys;
092    import com.liferay.portlet.PortletBagFactory;
093    import com.liferay.portlet.PortletConfigFactoryUtil;
094    import com.liferay.portlet.PortletFilterFactory;
095    import com.liferay.portlet.PortletInstanceFactoryUtil;
096    import com.liferay.portlet.PortletURLListenerFactory;
097    import com.liferay.portlet.social.util.SocialConfigurationUtil;
098    import com.liferay.util.ContentUtil;
099    import com.liferay.util.servlet.EncryptedServletRequest;
100    
101    import java.io.IOException;
102    import java.io.PrintWriter;
103    
104    import java.util.ArrayList;
105    import java.util.List;
106    import java.util.Locale;
107    import java.util.Set;
108    
109    import javax.portlet.PortletConfig;
110    import javax.portlet.PortletContext;
111    import javax.portlet.PortletException;
112    
113    import javax.servlet.RequestDispatcher;
114    import javax.servlet.ServletContext;
115    import javax.servlet.ServletException;
116    import javax.servlet.http.HttpServletRequest;
117    import javax.servlet.http.HttpServletResponse;
118    import javax.servlet.http.HttpSession;
119    import javax.servlet.jsp.PageContext;
120    
121    import org.apache.struts.Globals;
122    import org.apache.struts.action.ActionServlet;
123    import org.apache.struts.action.RequestProcessor;
124    import org.apache.struts.config.ControllerConfig;
125    import org.apache.struts.config.ModuleConfig;
126    import org.apache.struts.tiles.TilesUtilImpl;
127    
128    /**
129     * @author Brian Wing Shun Chan
130     * @author Jorge Ferrer
131     * @author Brian Myunghun Kim
132     */
133    public class MainServlet extends ActionServlet {
134    
135            @Override
136            public void destroy() {
137                    if (_log.isDebugEnabled()) {
138                            _log.debug("Destroy plugins");
139                    }
140    
141                    PortalLifecycleUtil.flushDestroys();
142    
143                    List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();
144    
145                    if (_log.isDebugEnabled()) {
146                            _log.debug("Destroy portlets");
147                    }
148    
149                    try {
150                            destroyPortlets(portlets);
151                    }
152                    catch (Exception e) {
153                            _log.error(e, e);
154                    }
155    
156                    if (_log.isDebugEnabled()) {
157                            _log.debug("Destroy companies");
158                    }
159    
160                    try {
161                            destroyCompanies();
162                    }
163                    catch (Exception e) {
164                            _log.error(e, e);
165                    }
166    
167                    if (_log.isDebugEnabled()) {
168                            _log.debug("Process global shutdown events");
169                    }
170    
171                    try {
172                            processGlobalShutdownEvents();
173                    }
174                    catch (Exception e) {
175                            _log.error(e, e);
176                    }
177    
178                    if (_log.isDebugEnabled()) {
179                            _log.debug("Destroy");
180                    }
181    
182                    callParentDestroy();
183            }
184    
185            @Override
186            public void init() throws ServletException {
187                    if (_log.isDebugEnabled()) {
188                            _log.debug("Initialize");
189                    }
190    
191                    ServletContext servletContext = getServletContext();
192    
193                    servletContext.setAttribute(MainServlet.class.getName(), Boolean.TRUE);
194    
195                    callParentInit();
196    
197                    if (_log.isDebugEnabled()) {
198                            _log.debug("Verify patch levels");
199                    }
200    
201                    try {
202                            PatcherUtil.verifyPatchLevels();
203                    }
204                    catch (PatchInconsistencyException pie) {
205                            if (!PropsValues.VERIFY_PATCH_LEVELS_DISABLED) {
206                                    _log.error(
207                                            "Stopping the server due to the inconsistent patch levels");
208    
209                                    if (_log.isWarnEnabled()) {
210                                            _log.warn(
211                                                    "Set the property \"verify.patch.levels.disabled\" " +
212                                                            "to override stopping the server due to the " +
213                                                                    "inconsistent patch levels");
214                                    }
215    
216                                    System.exit(0);
217                            }
218                    }
219    
220                    if (_log.isDebugEnabled()) {
221                            _log.debug("Initialize listeners");
222                    }
223    
224                    initListeners();
225    
226                    if (_log.isDebugEnabled()) {
227                            _log.debug("Process startup events");
228                    }
229    
230                    try {
231                            processStartupEvents();
232                    }
233                    catch (Exception e) {
234                            _log.error(e, e);
235    
236                            System.out.println(
237                                    "Stopping the server due to unexpected startup errors");
238    
239                            System.exit(0);
240                    }
241    
242                    if (_log.isDebugEnabled()) {
243                            _log.debug("Initialize server detector");
244                    }
245    
246                    try {
247                            initServerDetector();
248                    }
249                    catch (Exception e) {
250                            _log.error(e, e);
251                    }
252    
253                    if (_log.isDebugEnabled()) {
254                            _log.debug("Initialize plugin package");
255                    }
256    
257                    PluginPackage pluginPackage = null;
258    
259                    try {
260                            pluginPackage = initPluginPackage();
261                    }
262                    catch (Exception e) {
263                            _log.error(e, e);
264                    }
265    
266                    if (_log.isDebugEnabled()) {
267                            _log.debug("Initialize portlets");
268                    }
269    
270                    List<Portlet> portlets = new ArrayList<Portlet>();
271    
272                    try {
273                            portlets.addAll(initPortlets(pluginPackage));
274                    }
275                    catch (Exception e) {
276                            _log.error(e, e);
277                    }
278    
279                    if (_log.isDebugEnabled()) {
280                            _log.debug("Initialize layout templates");
281                    }
282    
283                    try {
284                            initLayoutTemplates(pluginPackage, portlets);
285                    }
286                    catch (Exception e) {
287                            _log.error(e, e);
288                    }
289    
290                    if (_log.isDebugEnabled()) {
291                            _log.debug("Initialize social");
292                    }
293    
294                    try {
295                            initSocial(pluginPackage);
296                    }
297                    catch (Exception e) {
298                            _log.error(e, e);
299                    }
300    
301                    if (_log.isDebugEnabled()) {
302                            _log.debug("Initialize themes");
303                    }
304    
305                    try {
306                            initThemes(pluginPackage, portlets);
307                    }
308                    catch (Exception e) {
309                            _log.error(e, e);
310                    }
311    
312                    if (_log.isDebugEnabled()) {
313                            _log.debug("Initialize web settings");
314                    }
315    
316                    try {
317                            initWebSettings();
318                    }
319                    catch (Exception e) {
320                            _log.error(e, e);
321                    }
322    
323                    if (_log.isDebugEnabled()) {
324                            _log.debug("Initialize extension environment");
325                    }
326    
327                    try {
328                            initExt();
329                    }
330                    catch (Exception e) {
331                            _log.error(e, e);
332                    }
333    
334                    if (_log.isDebugEnabled()) {
335                            _log.debug("Process global startup events");
336                    }
337    
338                    try {
339                            processGlobalStartupEvents();
340                    }
341                    catch (Exception e) {
342                            _log.error(e, e);
343                    }
344    
345                    if (_log.isDebugEnabled()) {
346                            _log.debug("Initialize resource actions");
347                    }
348    
349                    try {
350                            initResourceActions(portlets);
351                    }
352                    catch (Exception e) {
353                            _log.error(e, e);
354                    }
355    
356                    if (_log.isDebugEnabled()) {
357                            _log.debug("Initialize companies");
358                    }
359    
360                    try {
361                            initCompanies();
362                    }
363                    catch (Exception e) {
364                            _log.error(e, e);
365                    }
366    
367                    if (_log.isDebugEnabled()) {
368                            _log.debug("Initialize plugins");
369                    }
370    
371                    try {
372                            initPlugins();
373                    }
374                    catch (Exception e) {
375                            _log.error(e, e);
376                    }
377    
378                    servletContext.setAttribute(WebKeys.STARTUP_FINISHED, true);
379    
380                    ThreadLocalCacheManager.clearAll(Lifecycle.REQUEST);
381            }
382    
383            @Override
384            public void service(
385                            HttpServletRequest request, HttpServletResponse response)
386                    throws IOException, ServletException {
387    
388                    if (_log.isDebugEnabled()) {
389                            _log.debug("Process service request");
390                    }
391    
392                    if (processShutdownRequest(request, response)) {
393                            if (_log.isDebugEnabled()) {
394                                    _log.debug("Processed shutdown request");
395                            }
396    
397                            return;
398                    }
399    
400                    if (processMaintenanceRequest(request, response)) {
401                            if (_log.isDebugEnabled()) {
402                                    _log.debug("Processed maintenance request");
403                            }
404    
405                            return;
406                    }
407    
408                    if (_log.isDebugEnabled()) {
409                            _log.debug("Get company id");
410                    }
411    
412                    long companyId = getCompanyId(request);
413    
414                    if (processCompanyInactiveRequest(request, response, companyId)) {
415                            if (_log.isDebugEnabled()) {
416                                    _log.debug("Processed company inactive request");
417                            }
418    
419                            return;
420                    }
421    
422                    try {
423                            if (processGroupInactiveRequest(request, response)) {
424                                    if (_log.isDebugEnabled()) {
425                                            _log.debug("Processed site inactive request");
426                                    }
427    
428                                    return;
429                            }
430                    }
431                    catch (Exception e) {
432                            if (e instanceof NoSuchLayoutException) {
433                                    if (_log.isDebugEnabled()) {
434                                            _log.debug(e, e);
435                                    }
436                            }
437                            else {
438                                    _log.error(e, e);
439                            }
440                    }
441    
442                    if (_log.isDebugEnabled()) {
443                            _log.debug("Set portal port");
444                    }
445    
446                    setPortalPort(request);
447    
448                    if (_log.isDebugEnabled()) {
449                            _log.debug("Check variables");
450                    }
451    
452                    checkServletContext(request);
453                    checkPortletRequestProcessor(request);
454                    checkTilesDefinitionsFactory();
455    
456                    if (_log.isDebugEnabled()) {
457                            _log.debug("Handle non-serializable request");
458                    }
459    
460                    if (_log.isDebugEnabled()) {
461                            _log.debug("Encrypt request");
462                    }
463    
464                    request = encryptRequest(request, companyId);
465    
466                    long userId = getUserId(request);
467    
468                    String remoteUser = getRemoteUser(request, userId);
469    
470                    try {
471                            if (_log.isDebugEnabled()) {
472                                    _log.debug(
473                                            "Authenticate user id " + userId + " and remote user " +
474                                                    remoteUser);
475                            }
476    
477                            userId = loginUser(
478                                    request, response, companyId, userId, remoteUser);
479    
480                            if (_log.isDebugEnabled()) {
481                                    _log.debug("Authenticated user id " + userId);
482                            }
483                    }
484                    catch (Exception e) {
485                            _log.error(e, e);
486                    }
487    
488                    if (_log.isDebugEnabled()) {
489                            _log.debug("Set session thread local");
490                    }
491    
492                    PortalSessionThreadLocal.setHttpSession(request.getSession());
493    
494                    if (_log.isDebugEnabled()) {
495                            _log.debug("Process service pre events");
496                    }
497    
498                    if (processServicePre(request, response, userId)) {
499                            if (_log.isDebugEnabled()) {
500                                    _log.debug("Processing service pre events has errors");
501                            }
502    
503                            return;
504                    }
505    
506                    if (hasAbsoluteRedirect(request)) {
507                            if (_log.isDebugEnabled()) {
508                                    String currentURL = PortalUtil.getCurrentURL(request);
509    
510                                    _log.debug(
511                                            "Current URL " + currentURL + " has absolute redirect");
512                            }
513    
514                            return;
515                    }
516    
517                    if (!hasThemeDisplay(request)) {
518                            if (_log.isDebugEnabled()) {
519                                    String currentURL = PortalUtil.getCurrentURL(request);
520    
521                                    _log.debug(
522                                            "Current URL " + currentURL +
523                                                    " does not have a theme display");
524                            }
525    
526                            return;
527                    }
528    
529                    try {
530                            if (_log.isDebugEnabled()) {
531                                    _log.debug("Call parent service");
532                            }
533    
534                            callParentService(request, response);
535                    }
536                    finally {
537                            if (_log.isDebugEnabled()) {
538                                    _log.debug("Process service post events");
539                            }
540    
541                            processServicePost(request, response);
542                    }
543            }
544    
545            protected void callParentDestroy() {
546                    super.destroy();
547            }
548    
549            protected void callParentInit() throws ServletException {
550                    super.init();
551            }
552    
553            protected void callParentService(
554                            HttpServletRequest request, HttpServletResponse response)
555                    throws IOException, ServletException {
556    
557                    super.service(request, response);
558            }
559    
560            protected void checkPortletRequestProcessor(HttpServletRequest request)
561                    throws ServletException {
562    
563                    ServletContext servletContext = getServletContext();
564    
565                    PortletRequestProcessor portletReqProcessor =
566                            (PortletRequestProcessor)servletContext.getAttribute(
567                                    WebKeys.PORTLET_STRUTS_PROCESSOR);
568    
569                    if (portletReqProcessor == null) {
570                            ModuleConfig moduleConfig = getModuleConfig(request);
571    
572                            portletReqProcessor = PortletRequestProcessor.getInstance(
573                                    this, moduleConfig);
574    
575                            servletContext.setAttribute(
576                                    WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
577                    }
578            }
579    
580            protected void checkServletContext(HttpServletRequest request) {
581                    ServletContext servletContext = getServletContext();
582    
583                    request.setAttribute(WebKeys.CTX, servletContext);
584    
585                    String contextPath = request.getContextPath();
586    
587                    servletContext.setAttribute(WebKeys.CTX_PATH, contextPath);
588            }
589    
590            protected void checkTilesDefinitionsFactory() {
591                    ServletContext servletContext = getServletContext();
592    
593                    if (servletContext.getAttribute(
594                                    TilesUtilImpl.DEFINITIONS_FACTORY) != null) {
595    
596                            return;
597                    }
598    
599                    servletContext.setAttribute(
600                            TilesUtilImpl.DEFINITIONS_FACTORY,
601                            servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
602            }
603    
604            protected void checkWebSettings(String xml) throws DocumentException {
605                    Document doc = UnsecureSAXReaderUtil.read(xml);
606    
607                    Element root = doc.getRootElement();
608    
609                    int timeout = PropsValues.SESSION_TIMEOUT;
610    
611                    Element sessionConfig = root.element("session-config");
612    
613                    if (sessionConfig != null) {
614                            String sessionTimeout = sessionConfig.elementText(
615                                    "session-timeout");
616    
617                            timeout = GetterUtil.getInteger(sessionTimeout, timeout);
618                    }
619    
620                    PropsUtil.set(PropsKeys.SESSION_TIMEOUT, String.valueOf(timeout));
621    
622                    PropsValues.SESSION_TIMEOUT = timeout;
623    
624                    I18nServlet.setLanguageIds(root);
625                    I18nFilter.setLanguageIds(I18nServlet.getLanguageIds());
626            }
627    
628            protected void destroyCompanies() throws Exception {
629                    long[] companyIds = PortalInstances.getCompanyIds();
630    
631                    for (long companyId : companyIds) {
632                            destroyCompany(companyId);
633                    }
634            }
635    
636            protected void destroyCompany(long companyId) {
637                    if (_log.isDebugEnabled()) {
638                            _log.debug("Process shutdown events");
639                    }
640    
641                    try {
642                            EventsProcessorUtil.process(
643                                    PropsKeys.APPLICATION_SHUTDOWN_EVENTS,
644                                    PropsValues.APPLICATION_SHUTDOWN_EVENTS,
645                                    new String[] {String.valueOf(companyId)});
646                    }
647                    catch (Exception e) {
648                            _log.error(e, e);
649                    }
650            }
651    
652            protected void destroyPortlets(List<Portlet> portlets) throws Exception {
653                    for (Portlet portlet : portlets) {
654                            PortletInstanceFactoryUtil.destroy(portlet);
655                    }
656            }
657    
658            protected HttpServletRequest encryptRequest(
659                    HttpServletRequest request, long companyId) {
660    
661                    boolean encryptRequest = ParamUtil.getBoolean(request, WebKeys.ENCRYPT);
662    
663                    if (!encryptRequest) {
664                            return request;
665                    }
666    
667                    try {
668                            Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
669    
670                            request = new EncryptedServletRequest(request, company.getKeyObj());
671                    }
672                    catch (Exception e) {
673                    }
674    
675                    return request;
676            }
677    
678            protected long getCompanyId(HttpServletRequest request) {
679                    return PortalInstances.getCompanyId(request);
680            }
681    
682            protected String getRemoteUser(HttpServletRequest request, long userId) {
683                    String remoteUser = request.getRemoteUser();
684    
685                    if (!PropsValues.PORTAL_JAAS_ENABLE) {
686                            HttpSession session = request.getSession();
687    
688                            String jRemoteUser = (String)session.getAttribute("j_remoteuser");
689    
690                            if (jRemoteUser != null) {
691                                    remoteUser = jRemoteUser;
692    
693                                    session.removeAttribute("j_remoteuser");
694                            }
695                    }
696    
697                    if ((userId > 0) && (remoteUser == null)) {
698                            remoteUser = String.valueOf(userId);
699                    }
700    
701                    return remoteUser;
702            }
703    
704            @Override
705            protected synchronized RequestProcessor getRequestProcessor(
706                            ModuleConfig moduleConfig)
707                    throws ServletException {
708    
709                    ServletContext servletContext = getServletContext();
710    
711                    String key = Globals.REQUEST_PROCESSOR_KEY + moduleConfig.getPrefix();
712    
713                    RequestProcessor requestProcessor =
714                            (RequestProcessor)servletContext.getAttribute(key);
715    
716                    if (requestProcessor == null) {
717                            ControllerConfig controllerConfig =
718                                    moduleConfig.getControllerConfig();
719    
720                            try {
721                                    requestProcessor =
722                                            (RequestProcessor)InstanceFactory.newInstance(
723                                                    ClassLoaderUtil.getPortalClassLoader(),
724                                                    controllerConfig.getProcessorClass());
725                            }
726                            catch (Exception e) {
727                                    throw new ServletException(e);
728                            }
729    
730                            requestProcessor.init(this, moduleConfig);
731    
732                            servletContext.setAttribute(key, requestProcessor);
733                    }
734    
735                    return requestProcessor;
736            }
737    
738            protected long getUserId(HttpServletRequest request) {
739                    return PortalUtil.getUserId(request);
740            }
741    
742            protected boolean hasAbsoluteRedirect(HttpServletRequest request) {
743                    if (request.getAttribute(
744                                    AbsoluteRedirectsResponse.class.getName()) == null) {
745    
746                            return false;
747                    }
748                    else {
749                            return true;
750                    }
751            }
752    
753            protected boolean hasThemeDisplay(HttpServletRequest request) {
754                    if (request.getAttribute(WebKeys.THEME_DISPLAY) == null) {
755                            return false;
756                    }
757                    else {
758                            return true;
759                    }
760            }
761    
762            protected void initCompanies() throws Exception {
763                    ServletContext servletContext = getServletContext();
764    
765                    try {
766                            String[] webIds = PortalInstances.getWebIds();
767    
768                            for (String webId : webIds) {
769                                    PortalInstances.initCompany(servletContext, webId);
770                            }
771                    }
772                    finally {
773                            CompanyThreadLocal.setCompanyId(
774                                    PortalInstances.getDefaultCompanyId());
775    
776                            ShardDataSourceTargetSource shardDataSourceTargetSource =
777                                    (ShardDataSourceTargetSource)
778                                            InfrastructureUtil.getShardDataSourceTargetSource();
779    
780                            if (shardDataSourceTargetSource != null) {
781                                    shardDataSourceTargetSource.resetDataSource();
782                            }
783                    }
784            }
785    
786            protected void initExt() throws Exception {
787                    ServletContext servletContext = getServletContext();
788    
789                    ExtRegistry.registerPortal(servletContext);
790            }
791    
792            protected void initLayoutTemplates(
793                            PluginPackage pluginPackage, List<Portlet> portlets)
794                    throws Exception {
795    
796                    ServletContext servletContext = getServletContext();
797    
798                    String[] xmls = new String[] {
799                            HttpUtil.URLtoString(
800                                    servletContext.getResource(
801                                            "/WEB-INF/liferay-layout-templates.xml")),
802                            HttpUtil.URLtoString(
803                                    servletContext.getResource(
804                                            "/WEB-INF/liferay-layout-templates-ext.xml"))
805                    };
806    
807                    List<LayoutTemplate> layoutTemplates =
808                            LayoutTemplateLocalServiceUtil.init(
809                                    servletContext, xmls, pluginPackage);
810    
811                    servletContext.setAttribute(
812                            WebKeys.PLUGIN_LAYOUT_TEMPLATES, layoutTemplates);
813            }
814    
815            protected void initListeners() {
816                    SerializableSessionAttributeListener.initialize();
817            }
818    
819            protected PluginPackage initPluginPackage() throws Exception {
820                    ServletContext servletContext = getServletContext();
821    
822                    return PluginPackageUtil.readPluginPackageServletContext(
823                            servletContext);
824            }
825    
826            /**
827             * @see SetupWizardUtil#_initPlugins
828             */
829            protected void initPlugins() throws Exception {
830    
831                    // See LEP-2885. Don't flush hot deploy events until after the portal
832                    // has initialized.
833    
834                    if (SetupWizardUtil.isSetupFinished()) {
835                            HotDeployUtil.setCapturePrematureEvents(false);
836    
837                            PortalLifecycleUtil.flushInits();
838                    }
839            }
840    
841            protected void initPortletApp(
842                            Portlet portlet, ServletContext servletContext)
843                    throws PortletException {
844    
845                    PortletApp portletApp = portlet.getPortletApp();
846    
847                    PortletConfig portletConfig = PortletConfigFactoryUtil.create(
848                            portlet, servletContext);
849    
850                    PortletContext portletContext = portletConfig.getPortletContext();
851    
852                    Set<PortletFilter> portletFilters = portletApp.getPortletFilters();
853    
854                    for (PortletFilter portletFilter : portletFilters) {
855                            PortletFilterFactory.create(portletFilter, portletContext);
856                    }
857    
858                    Set<PortletURLListener> portletURLListeners =
859                            portletApp.getPortletURLListeners();
860    
861                    for (PortletURLListener portletURLListener : portletURLListeners) {
862                            PortletURLListenerFactory.create(portletURLListener);
863                    }
864            }
865    
866            protected List<Portlet> initPortlets(PluginPackage pluginPackage)
867                    throws Exception {
868    
869                    ServletContext servletContext = getServletContext();
870    
871                    String[] xmls = new String[] {
872                            HttpUtil.URLtoString(
873                                    servletContext.getResource(
874                                            "/WEB-INF/" + Portal.PORTLET_XML_FILE_NAME_CUSTOM)),
875                            HttpUtil.URLtoString(
876                                    servletContext.getResource("/WEB-INF/portlet-ext.xml")),
877                            HttpUtil.URLtoString(
878                                    servletContext.getResource("/WEB-INF/liferay-portlet.xml")),
879                            HttpUtil.URLtoString(
880                                    servletContext.getResource("/WEB-INF/liferay-portlet-ext.xml")),
881                            HttpUtil.URLtoString(
882                                    servletContext.getResource("/WEB-INF/web.xml"))
883                    };
884    
885                    PortletLocalServiceUtil.initEAR(servletContext, xmls, pluginPackage);
886    
887                    PortletBagFactory portletBagFactory = new PortletBagFactory();
888    
889                    portletBagFactory.setClassLoader(
890                            ClassLoaderUtil.getPortalClassLoader());
891                    portletBagFactory.setServletContext(servletContext);
892                    portletBagFactory.setWARFile(false);
893    
894                    List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();
895    
896                    for (int i = 0; i < portlets.size(); i++) {
897                            Portlet portlet = portlets.get(i);
898    
899                            portletBagFactory.create(portlet);
900    
901                            if (i == 0) {
902                                    initPortletApp(portlet, servletContext);
903                            }
904                    }
905    
906                    servletContext.setAttribute(WebKeys.PLUGIN_PORTLETS, portlets);
907    
908                    return portlets;
909            }
910    
911            protected void initResourceActions(List<Portlet> portlets)
912                    throws Exception {
913    
914                    for (Portlet portlet : portlets) {
915                            List<String> portletActions =
916                                    ResourceActionsUtil.getPortletResourceActions(portlet);
917    
918                            ResourceActionLocalServiceUtil.checkResourceActions(
919                                    portlet.getPortletId(), portletActions);
920    
921                            List<String> modelNames =
922                                    ResourceActionsUtil.getPortletModelResources(
923                                            portlet.getPortletId());
924    
925                            for (String modelName : modelNames) {
926                                    List<String> modelActions =
927                                            ResourceActionsUtil.getModelResourceActions(modelName);
928    
929                                    ResourceActionLocalServiceUtil.checkResourceActions(
930                                            modelName, modelActions);
931                            }
932                    }
933            }
934    
935            protected void initServerDetector() throws Exception {
936                    ServerCapabilitiesUtil.determineServerCapabilities(getServletContext());
937            }
938    
939            protected void initSocial(PluginPackage pluginPackage) throws Exception {
940                    ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader();
941    
942                    ServletContext servletContext = getServletContext();
943    
944                    String[] xmls = new String[] {
945                            HttpUtil.URLtoString(
946                                    servletContext.getResource("/WEB-INF/liferay-social.xml")),
947                            HttpUtil.URLtoString(
948                                    servletContext.getResource("/WEB-INF/liferay-social-ext.xml"))
949                    };
950    
951                    SocialConfigurationUtil.read(classLoader, xmls);
952            }
953    
954            protected void initThemes(
955                            PluginPackage pluginPackage, List<Portlet> portlets)
956                    throws Exception {
957    
958                    ServletContext servletContext = getServletContext();
959    
960                    String[] xmls = new String[] {
961                            HttpUtil.URLtoString(
962                                    servletContext.getResource(
963                                            "/WEB-INF/liferay-look-and-feel.xml")),
964                            HttpUtil.URLtoString(
965                                    servletContext.getResource(
966                                            "/WEB-INF/liferay-look-and-feel-ext.xml"))
967                    };
968    
969                    List<Theme> themes = ThemeLocalServiceUtil.init(
970                            servletContext, null, true, xmls, pluginPackage);
971    
972                    servletContext.setAttribute(WebKeys.PLUGIN_THEMES, themes);
973            }
974    
975            protected void initWebSettings() throws Exception {
976                    ServletContext servletContext = getServletContext();
977    
978                    String xml = HttpUtil.URLtoString(
979                            servletContext.getResource("/WEB-INF/web.xml"));
980    
981                    checkWebSettings(xml);
982            }
983    
984            protected long loginUser(
985                            HttpServletRequest request, HttpServletResponse response,
986                            long companyId, long userId, String remoteUser)
987                    throws PortalException, SystemException {
988    
989                    if ((userId > 0) || (remoteUser == null)) {
990                            return userId;
991                    }
992    
993                    userId = GetterUtil.getLong(remoteUser);
994    
995                    EventsProcessorUtil.process(
996                            PropsKeys.LOGIN_EVENTS_PRE, PropsValues.LOGIN_EVENTS_PRE, request,
997                            response);
998    
999                    User user = UserLocalServiceUtil.getUserById(userId);
1000    
1001                    if (PropsValues.USERS_UPDATE_LAST_LOGIN ||
1002                            (user.getLastLoginDate() == null)) {
1003    
1004                            UserLocalServiceUtil.updateLastLogin(
1005                                    userId, request.getRemoteAddr());
1006                    }
1007    
1008                    HttpSession session = request.getSession();
1009    
1010                    session.setAttribute(WebKeys.USER, user);
1011                    session.setAttribute(WebKeys.USER_ID, new Long(userId));
1012                    session.setAttribute(Globals.LOCALE_KEY, user.getLocale());
1013    
1014                    EventsProcessorUtil.process(
1015                            PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST, request,
1016                            response);
1017    
1018                    return userId;
1019            }
1020    
1021            protected boolean processCompanyInactiveRequest(
1022                            HttpServletRequest request, HttpServletResponse response,
1023                            long companyId)
1024                    throws IOException {
1025    
1026                    if (PortalInstances.isCompanyActive(companyId)) {
1027                            return false;
1028                    }
1029    
1030                    processInactiveRequest(
1031                            request, response,
1032                            "this-instance-is-inactive-please-contact-the-administrator");
1033    
1034                    return true;
1035            }
1036    
1037            protected void processGlobalShutdownEvents() throws Exception {
1038                    EventsProcessorUtil.process(
1039                            PropsKeys.GLOBAL_SHUTDOWN_EVENTS,
1040                            PropsValues.GLOBAL_SHUTDOWN_EVENTS);
1041    
1042                    super.destroy();
1043            }
1044    
1045            protected void processGlobalStartupEvents() throws Exception {
1046                    EventsProcessorUtil.process(
1047                            PropsKeys.GLOBAL_STARTUP_EVENTS, PropsValues.GLOBAL_STARTUP_EVENTS);
1048            }
1049    
1050            protected boolean processGroupInactiveRequest(
1051                            HttpServletRequest request, HttpServletResponse response)
1052                    throws IOException, PortalException, SystemException {
1053    
1054                    long plid = ParamUtil.getLong(request, "p_l_id");
1055    
1056                    if (plid <= 0) {
1057                            return false;
1058                    }
1059    
1060                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
1061    
1062                    Group group = layout.getGroup();
1063    
1064                    if (group.isActive()) {
1065                            return false;
1066                    }
1067    
1068                    processInactiveRequest(
1069                            request, response,
1070                            "this-site-is-inactive-please-contact-the-administrator");
1071    
1072                    return true;
1073            }
1074    
1075            protected void processInactiveRequest(
1076                            HttpServletRequest request, HttpServletResponse response,
1077                            String messageKey)
1078                    throws IOException {
1079    
1080                    response.setContentType(ContentTypes.TEXT_HTML_UTF8);
1081    
1082                    Locale locale = LocaleUtil.getDefault();
1083    
1084                    String message = LanguageUtil.get(locale, messageKey);
1085    
1086                    String html = ContentUtil.get(
1087                            "com/liferay/portal/dependencies/inactive.html");
1088    
1089                    html = StringUtil.replace(html, "[$MESSAGE$]", message);
1090    
1091                    PrintWriter printWriter = response.getWriter();
1092    
1093                    printWriter.print(html);
1094            }
1095    
1096            protected boolean processMaintenanceRequest(
1097                            HttpServletRequest request, HttpServletResponse response)
1098                    throws IOException, ServletException {
1099    
1100                    if (!MaintenanceUtil.isMaintaining()) {
1101                            return false;
1102                    }
1103    
1104                    RequestDispatcher requestDispatcher = request.getRequestDispatcher(
1105                            "/html/portal/maintenance.jsp");
1106    
1107                    requestDispatcher.include(request, response);
1108    
1109                    return true;
1110            }
1111    
1112            protected void processServicePost(
1113                    HttpServletRequest request, HttpServletResponse response) {
1114    
1115                    try {
1116                            EventsProcessorUtil.process(
1117                                    PropsKeys.SERVLET_SERVICE_EVENTS_POST,
1118                                    PropsValues.SERVLET_SERVICE_EVENTS_POST, request, response);
1119                    }
1120                    catch (Exception e) {
1121                            _log.error(e, e);
1122                    }
1123            }
1124    
1125            protected boolean processServicePre(
1126                            HttpServletRequest request, HttpServletResponse response,
1127                            long userId)
1128                    throws IOException, ServletException {
1129    
1130                    try {
1131                            EventsProcessorUtil.process(
1132                                    PropsKeys.SERVLET_SERVICE_EVENTS_PRE,
1133                                    PropsValues.SERVLET_SERVICE_EVENTS_PRE, request, response);
1134                    }
1135                    catch (Exception e) {
1136                            Throwable cause = e.getCause();
1137    
1138                            if (cause instanceof NoSuchLayoutException) {
1139                                    sendError(
1140                                            HttpServletResponse.SC_NOT_FOUND, cause, request, response);
1141    
1142                                    return true;
1143                            }
1144                            else if (cause instanceof PrincipalException) {
1145                                    processServicePrePrincipalException(
1146                                            cause, userId, request, response);
1147    
1148                                    return true;
1149                            }
1150    
1151                            _log.error(e, e);
1152    
1153                            request.setAttribute(PageContext.EXCEPTION, e);
1154    
1155                            ServletContext servletContext = getServletContext();
1156    
1157                            StrutsUtil.forward(
1158                                    PropsValues.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE,
1159                                    servletContext, request, response);
1160    
1161                            return true;
1162                    }
1163    
1164                    if (_HTTP_HEADER_VERSION_VERBOSITY_DEFAULT) {
1165                    }
1166                    else if (_HTTP_HEADER_VERSION_VERBOSITY_PARTIAL) {
1167                            response.addHeader(
1168                                    _LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getName());
1169                    }
1170                    else {
1171                            response.addHeader(
1172                                    _LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getReleaseInfo());
1173                    }
1174    
1175                    return false;
1176            }
1177    
1178            protected void processServicePrePrincipalException(
1179                            Throwable t, long userId, HttpServletRequest request,
1180                            HttpServletResponse response)
1181                    throws IOException, ServletException {
1182    
1183                    if (userId > 0) {
1184                            sendError(
1185                                    HttpServletResponse.SC_UNAUTHORIZED, t, request, response);
1186    
1187                            return;
1188                    }
1189    
1190                    String redirect = PortalUtil.getPathMain().concat("/portal/login");
1191    
1192                    String currentURL = PortalUtil.getCurrentURL(request);
1193    
1194                    redirect = HttpUtil.addParameter(redirect, "redirect", currentURL);
1195    
1196                    long plid = ParamUtil.getLong(request, "p_l_id");
1197    
1198                    if (plid > 0) {
1199                            try {
1200                                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
1201    
1202                                    Group group = layout.getGroup();
1203    
1204                                    plid = group.getDefaultPublicPlid();
1205    
1206                                    if ((plid == LayoutConstants.DEFAULT_PLID) ||
1207                                            group.isStagingGroup()) {
1208    
1209                                            Group guestGroup = GroupLocalServiceUtil.getGroup(
1210                                                    layout.getCompanyId(), GroupConstants.GUEST);
1211    
1212                                            plid = guestGroup.getDefaultPublicPlid();
1213                                    }
1214    
1215                                    redirect = HttpUtil.addParameter(redirect, "p_l_id", plid);
1216                            }
1217                            catch (Exception e) {
1218                            }
1219                    }
1220    
1221                    response.sendRedirect(redirect);
1222            }
1223    
1224            protected boolean processShutdownRequest(
1225                            HttpServletRequest request, HttpServletResponse response)
1226                    throws IOException {
1227    
1228                    if (!ShutdownUtil.isShutdown()) {
1229                            return false;
1230                    }
1231    
1232                    String messageKey = ShutdownUtil.getMessage();
1233    
1234                    if (Validator.isNull(messageKey)) {
1235                            messageKey = "the-system-is-shutdown-please-try-again-later";
1236                    }
1237    
1238                    processInactiveRequest(request, response, messageKey);
1239    
1240                    return true;
1241            }
1242    
1243            protected void processStartupEvents() throws Exception {
1244                    StartupAction startupAction = new StartupAction();
1245    
1246                    startupAction.run(null);
1247            }
1248    
1249            protected void sendError(
1250                            int status, Throwable t, HttpServletRequest request,
1251                            HttpServletResponse response)
1252                    throws IOException, ServletException {
1253    
1254                    DynamicServletRequest dynamicRequest = new DynamicServletRequest(
1255                            request);
1256    
1257                    // Reset layout params or there will be an infinite loop
1258    
1259                    dynamicRequest.setParameter("p_l_id", StringPool.BLANK);
1260    
1261                    dynamicRequest.setParameter("groupId", StringPool.BLANK);
1262                    dynamicRequest.setParameter("layoutId", StringPool.BLANK);
1263                    dynamicRequest.setParameter("privateLayout", StringPool.BLANK);
1264    
1265                    PortalUtil.sendError(status, (Exception)t, dynamicRequest, response);
1266            }
1267    
1268            protected void setPortalPort(HttpServletRequest request) {
1269                    PortalUtil.setPortalPort(request);
1270            }
1271    
1272            private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_DEFAULT =
1273                    StringUtil.equalsIgnoreCase(
1274                            PropsValues.HTTP_HEADER_VERSION_VERBOSITY, ReleaseInfo.getName());
1275    
1276            private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_PARTIAL =
1277                    StringUtil.equalsIgnoreCase(
1278                            PropsValues.HTTP_HEADER_VERSION_VERBOSITY, "partial");
1279    
1280            private static final String _LIFERAY_PORTAL_REQUEST_HEADER =
1281                    "Liferay-Portal";
1282    
1283            private static Log _log = LogFactoryUtil.getLog(MainServlet.class);
1284    
1285    }