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