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