View Javadoc
1   /**
2    * This file Copyright (c) 2003-2015 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.init;
35  
36  import info.magnolia.cms.beans.config.ConfigLoader;
37  import info.magnolia.cms.core.SystemProperty;
38  import info.magnolia.context.MgnlContext;
39  import info.magnolia.logging.Log4jConfigurer;
40  import info.magnolia.module.ModuleManager;
41  import info.magnolia.module.ModuleRegistry;
42  import info.magnolia.objectfactory.Components;
43  import info.magnolia.objectfactory.configuration.ComponentProviderConfiguration;
44  import info.magnolia.objectfactory.configuration.ComponentProviderConfigurationBuilder;
45  import info.magnolia.objectfactory.guice.GuiceComponentProvider;
46  import info.magnolia.objectfactory.guice.GuiceComponentProviderBuilder;
47  
48  import java.util.Arrays;
49  import java.util.Collections;
50  import java.util.List;
51  
52  import javax.inject.Singleton;
53  import javax.servlet.ServletContext;
54  import javax.servlet.ServletContextEvent;
55  import javax.servlet.ServletContextListener;
56  
57  import org.apache.commons.lang3.StringUtils;
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  import com.google.inject.Stage;
62  
63  /**
64   * Point of entry for Magnolia CMS, initializes the component providers, starts logging, triggers loading of
65   * properties and finally delegates to {@link ConfigLoader} for completing initialization.
66   *
67   * <h3>Component providers</h3>
68   * <p>
69   * When Magnolia starts up the first thing that happens is the creation of the <i>platform</i> component provider. It
70   * contains the essential singletons that constitutes the platform on which the rest of the system builds. These
71   * components are defined in a file called <code>platform-components.xml</code>, it's on the classpath in package
72   * /info/magnolia/init.
73   * </p>
74   * <p>
75   * The location can be customized using a servlet context parameter called
76   * <code>magnolia.platform.components.config.location</code>. It's specified as a list of comma-separated files on the
77   * classpath. The files are loaded in the specified order allowing definitions to override definitions from earlier
78   * files.
79   * </p>
80   * <pre>
81   * &lt;context-param&gt;
82   *   &lt;param-name&gt;magnolia.platform.components.config.location&lt;/param-name&gt;
83   *   &lt;param-value&gt;/info/magnolia/init/platform-components.xml,/com/mycompany/custom-platform-components.xml&lt;/param-value&gt;
84   * &lt;/context-param&gt;
85   * </pre>
86   * <p>
87   * The platform components include the {@link ModuleManager} which is called by this listener to load the descriptors of
88   * all the modules present. Modules define additional components that are loaded into a second component provider called
89   * <i>system</i>.
90   * </p>
91   * <p>
92   * When {@link ConfigLoader} takes over the initialization procedure it will create a third component provider called
93   * <i>main</i> which contain components defined in modules as belonging to the main component provider.
94   * </p>
95   * <h3>Property loading</h3>
96   * <p>
97   * Properties are loaded by an implementation of {@link MagnoliaConfigurationProperties}. It's configured as a platform
98   * component and is called by this class to do initialization. See {@link DefaultMagnoliaPropertiesResolver} and
99   * {@link DefaultMagnoliaInitPaths} for details on how to customize the default behavior.
100  * </p>
101  *
102  * @see ModuleManager
103  * @see MagnoliaInitPaths
104  * @see MagnoliaPropertiesResolver
105  * @see DefaultMagnoliaPropertiesResolver
106  * @see DefaultMagnoliaConfigurationProperties
107  * @see DefaultMagnoliaInitPaths
108  * @see ConfigLoader
109  * @see Log4jConfigurer
110  */
111 @Singleton
112 public class MagnoliaServletContextListener implements ServletContextListener {
113 
114     public static final String PLATFORM_COMPONENTS_CONFIG_LOCATION_NAME = "magnolia.platform.components.config.location";
115     public static final String DEFAULT_PLATFORM_COMPONENTS_CONFIG_LOCATION = "/info/magnolia/init/platform-components.xml";
116 
117     private static final Logger log = LoggerFactory.getLogger(MagnoliaServletContextListener.class);
118 
119     private ServletContext servletContext;
120     private GuiceComponentProvider platform;
121     private GuiceComponentProvider system;
122     private ModuleManager moduleManager;
123     private ConfigLoader loader;
124 
125     @Override
126     public void contextInitialized(final ServletContextEvent sce) {
127         contextInitialized(sce, true);
128     }
129 
130     public void contextInitialized(final ServletContextEvent sce, boolean startServer) {
131         try {
132             servletContext = sce.getServletContext();
133 
134             // Start 'platform' ComponentProvider
135             GuiceComponentProviderBuilder builder = new GuiceComponentProviderBuilder();
136             builder.withConfiguration(getPlatformComponents());
137             builder.inStage(Stage.PRODUCTION);
138             builder.exposeGlobally();
139             platform = builder.build();
140 
141             // Expose server name as a system property, so it can be used in log4j configurations
142             // rootPath and webapp are not exposed since there can be different webapps running in the same jvm
143 
144             String serverName = platform.getComponent(MagnoliaInitPaths.class).getServerName();
145 
146             System.setProperty("server", serverName);
147 
148             // Load module definitions
149             moduleManager = platform.getComponent(ModuleManager.class);
150             moduleManager.loadDefinitions();
151 
152             // Initialize MagnoliaConfigurationProperties
153             MagnoliaConfigurationProperties configurationProperties = platform.getComponent(MagnoliaConfigurationProperties.class);
154             configurationProperties.init();
155             log.info("Property sources loaded: {}", configurationProperties.describe());
156 
157             // Connect legacy properties to the MagnoliaConfigurationProperties object
158             SystemProperty.setMagnoliaConfigurationProperties(configurationProperties);
159 
160             // Initialize logging now that properties are available
161             Log4jConfigurer.initLogging();
162 
163             // Start 'system' ComponentProvider
164             builder = new GuiceComponentProviderBuilder();
165             builder.withConfiguration(getSystemComponents());
166             builder.withParent(platform);
167             builder.exposeGlobally();
168             system = builder.build();
169 
170             // Delegate to ConfigLoader to complete initialization
171             loader = system.getComponent(ConfigLoader.class);
172             if (startServer) {
173                 startServer();
174             }
175 
176         } catch (Throwable t) {
177             log.error("Oops, Magnolia could not be started", t);
178             t.printStackTrace();
179             if (t instanceof Error) {
180                 throw (Error) t;
181             }
182             if (t instanceof RuntimeException) {
183                 throw (RuntimeException) t;
184             }
185             throw new RuntimeException(t);
186         }
187     }
188 
189     @Override
190     public void contextDestroyed(final ServletContextEvent sce) {
191 
192         // avoid disturbing NPEs if the context has never been started (classpath problems, etc)
193         if (moduleManager != null) {
194             moduleManager.stopModules();
195         }
196 
197         stopServer();
198 
199         // We set the global ComponentProvider to its parent here, then we destroy it, components in it that expects the
200         // global ComponentProvider to be the one it lives in and the one that was there when the component was created
201         // might fail because of this. Maybe we can solve it by using the ThreadLocal override we already have and call
202         // scopes.
203 
204         if (system != null) {
205             Components.setComponentProvider(system.getParent());
206             system.destroy();
207         }
208 
209         if (platform != null) {
210             Components.setComponentProvider(platform.getParent());
211             platform.destroy();
212         }
213 
214         Log4jConfigurer.shutdownLogging();
215     }
216 
217     protected ComponentProviderConfiguration getPlatformComponents() {
218         ComponentProviderConfigurationBuilder configurationBuilder = new ComponentProviderConfigurationBuilder();
219         List<String> resources = getPlatformComponentsResources();
220         ComponentProviderConfiguration platformComponents = configurationBuilder.readConfiguration(resources, "platform");
221         platformComponents.registerInstance(ServletContext.class, servletContext);
222         // This is needed by DefaultMagnoliaInitPaths for backwards compatibility
223         platformComponents.registerInstance(MagnoliaServletContextListener.class, this);
224         return platformComponents;
225     }
226 
227     /**
228      * Returns a list of resources that contain platform components. Definitions for the same type will override giving
229      * preference to the last read definition. Checks for an init parameter in web.xml for an overridden location
230      * Subclasses can override this method to provide alternative strategies. The returned locations are used to find
231      * the resource on the class path.
232      */
233     protected List<String> getPlatformComponentsResources() {
234         String configLocation = servletContext.getInitParameter(PLATFORM_COMPONENTS_CONFIG_LOCATION_NAME);
235         if (StringUtils.isNotBlank(configLocation)) {
236             return Arrays.asList(StringUtils.split(configLocation, ", \n"));
237         }
238         return Collections.singletonList(DEFAULT_PLATFORM_COMPONENTS_CONFIG_LOCATION);
239     }
240 
241     protected ComponentProviderConfiguration getSystemComponents() {
242         ComponentProviderConfigurationBuilder configurationBuilder = new ComponentProviderConfigurationBuilder();
243         return configurationBuilder.getComponentsFromModules("system", platform.getComponent(ModuleRegistry.class).getModuleDefinitions());
244     }
245 
246     protected void startServer() {
247         MgnlContext.doInSystemContext(new MgnlContext.VoidOp() {
248             @Override
249             public void doExec() {
250                 loader.load();
251             }
252         }, true);
253     }
254 
255     protected void stopServer() {
256         if (loader != null) {
257             MgnlContext.doInSystemContext(new MgnlContext.VoidOp() {
258                 @Override
259                 public void doExec() {
260                     loader.unload();
261                 }
262             }, true);
263         }
264     }
265 
266     /**
267      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
268      */
269     protected String initWebappName(String rootPath) {
270         return null;
271     }
272 
273     /**
274      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
275      */
276     protected String initRootPath(final ServletContext context) {
277         return null;
278     }
279 
280     /**
281      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
282      */
283     protected String initServername(boolean unqualified) {
284         return null;
285     }
286 
287 }