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