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