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