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