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