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