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