View Javadoc
1   /**
2    * This file Copyright (c) 2003-2016 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             // Set up init-phase MagnoliaConfigurationProperties simply for the module registry
149             MagnoliaConfigurationProperties configurationProperties = platform.getComponent(MagnoliaConfigurationProperties.class);
150             configurationProperties.init();
151 
152             // Connect legacy properties to the MagnoliaConfigurationProperties object
153             SystemProperty.setMagnoliaConfigurationProperties(configurationProperties);
154 
155             // Load module definitions
156             moduleManager = platform.getComponent(ModuleManager.class);
157             moduleManager.loadDefinitions();
158 
159             // Initialize logging now that properties are available
160             Log4jConfigurer.initLogging();
161 
162             // Start 'system' ComponentProvider
163             builder = new GuiceComponentProviderBuilder();
164             builder.withConfiguration(getSystemComponents());
165             builder.withParent(platform);
166             builder.exposeGlobally();
167             system = builder.build();
168 
169             // Now initialize module-aware MagnoliaConfigurationProperties
170             configurationProperties = system.getComponent(MagnoliaConfigurationProperties.class);
171             configurationProperties.init();
172             log.info("Property sources loaded: {}", configurationProperties.describe());
173 
174             // Re-connect legacy properties to the new MagnoliaConfigurationProperties object
175             SystemProperty.setMagnoliaConfigurationProperties(configurationProperties);
176 
177             // Delegate to ConfigLoader to complete initialization
178             loader = system.getComponent(ConfigLoader.class);
179             if (startServer) {
180                 startServer();
181             }
182 
183         } catch (Throwable t) {
184             log.error("Oops, Magnolia could not be started", t);
185             t.printStackTrace();
186             if (t instanceof Error) {
187                 throw (Error) t;
188             }
189             if (t instanceof RuntimeException) {
190                 throw (RuntimeException) t;
191             }
192             throw new RuntimeException(t);
193         }
194     }
195 
196     @Override
197     public void contextDestroyed(final ServletContextEvent sce) {
198 
199         // avoid disturbing NPEs if the context has never been started (classpath problems, etc)
200         if (moduleManager != null) {
201             moduleManager.stopModules();
202         }
203 
204         stopServer();
205 
206         // We set the global ComponentProvider to its parent here, then we destroy it, components in it that expects the
207         // global ComponentProvider to be the one it lives in and the one that was there when the component was created
208         // might fail because of this. Maybe we can solve it by using the ThreadLocal override we already have and call
209         // scopes.
210 
211         if (system != null) {
212             Components.setComponentProvider(system.getParent());
213             system.destroy();
214         }
215 
216         if (platform != null) {
217             Components.setComponentProvider(platform.getParent());
218             platform.destroy();
219         }
220 
221         Log4jConfigurer.shutdownLogging();
222     }
223 
224     protected ComponentProviderConfiguration getPlatformComponents() {
225         ComponentProviderConfigurationBuilder configurationBuilder = new ComponentProviderConfigurationBuilder();
226         List<String> resources = getPlatformComponentsResources();
227         ComponentProviderConfiguration platformComponents = configurationBuilder.readConfiguration(resources, "platform");
228         platformComponents.registerInstance(ServletContext.class, servletContext);
229         // This is needed by DefaultMagnoliaInitPaths for backwards compatibility
230         platformComponents.registerInstance(MagnoliaServletContextListener.class, this);
231         return platformComponents;
232     }
233 
234     /**
235      * Returns a list of resources that contain platform components. Definitions for the same type will override giving
236      * preference to the last read definition. Checks for an init parameter in web.xml for an overridden location
237      * Subclasses can override this method to provide alternative strategies. The returned locations are used to find
238      * the resource on the class path.
239      */
240     protected List<String> getPlatformComponentsResources() {
241         String configLocation = servletContext.getInitParameter(PLATFORM_COMPONENTS_CONFIG_LOCATION_NAME);
242         if (StringUtils.isNotBlank(configLocation)) {
243             return Arrays.asList(StringUtils.split(configLocation, ", \n"));
244         }
245         return Collections.singletonList(DEFAULT_PLATFORM_COMPONENTS_CONFIG_LOCATION);
246     }
247 
248     protected ComponentProviderConfiguration getSystemComponents() {
249         ComponentProviderConfigurationBuilder configurationBuilder = new ComponentProviderConfigurationBuilder();
250         return configurationBuilder.getComponentsFromModules("system", platform.getComponent(ModuleRegistry.class).getModuleDefinitions());
251     }
252 
253     protected void startServer() {
254         MgnlContext.doInSystemContext(new MgnlContext.VoidOp() {
255             @Override
256             public void doExec() {
257                 loader.load();
258             }
259         }, true);
260     }
261 
262     protected void stopServer() {
263         if (loader != null) {
264             MgnlContext.doInSystemContext(new MgnlContext.VoidOp() {
265                 @Override
266                 public void doExec() {
267                     loader.unload();
268                 }
269             }, true);
270         }
271     }
272 
273     /**
274      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
275      */
276     protected String initWebappName(String rootPath) {
277         return null;
278     }
279 
280     /**
281      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
282      */
283     protected String initRootPath(final ServletContext context) {
284         return null;
285     }
286 
287     /**
288      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
289      */
290     protected String initServername(boolean unqualified) {
291         return null;
292     }
293 
294 }