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