View Javadoc

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