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