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