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