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 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.lang3.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  * @see ModuleManager
101  * @see MagnoliaInitPaths
102  * @see MagnoliaPropertiesResolver
103  * @see DefaultMagnoliaPropertiesResolver
104  * @see DefaultMagnoliaConfigurationProperties
105  * @see DefaultMagnoliaInitPaths
106  * @see ConfigLoader
107  * @see Log4jConfigurer
108  */
109 @Singleton
110 public class MagnoliaServletContextListener implements ServletContextListener {
111 
112     public static final String PLATFORM_COMPONENTS_CONFIG_LOCATION_NAME = "magnolia.platform.components.config.location";
113     public static final String DEFAULT_PLATFORM_COMPONENTS_CONFIG_LOCATION = "/info/magnolia/init/platform-components.xml";
114 
115     private static final Logger log = LoggerFactory.getLogger(MagnoliaServletContextListener.class);
116 
117     private ServletContext servletContext;
118     private GuiceComponentProvider platform;
119     private GuiceComponentProvider system;
120     private ModuleManager moduleManager;
121     private ConfigLoader loader;
122 
123     @Override
124     public void contextInitialized(final ServletContextEvent sce) {
125         contextInitialized(sce, true);
126     }
127 
128     public void contextInitialized(final ServletContextEvent sce, boolean startServer) {
129         try {
130             servletContext = sce.getServletContext();
131 
132             // Start 'platform' ComponentProvider
133             GuiceComponentProviderBuilder builder = new GuiceComponentProviderBuilder();
134             builder.withConfiguration(getPlatformComponents());
135             builder.inStage(Stage.PRODUCTION);
136             builder.exposeGlobally();
137             platform = builder.build();
138 
139             // Expose server name as a system property, so it can be used in log4j configurations
140             // rootPath and webapp are not exposed since there can be different webapps running in the same jvm
141 
142             String serverName = platform.getComponent(MagnoliaInitPaths.class).getServerName();
143 
144             System.setProperty("server", serverName);
145 
146             // Load module definitions
147             moduleManager = platform.getComponent(ModuleManager.class);
148             moduleManager.loadDefinitions();
149 
150             // Initialize MagnoliaConfigurationProperties
151             MagnoliaConfigurationProperties configurationProperties = platform.getComponent(MagnoliaConfigurationProperties.class);
152             configurationProperties.init();
153             log.info("Property sources loaded: {}", configurationProperties.describe());
154 
155             // Connect legacy properties to the MagnoliaConfigurationProperties object
156             SystemProperty.setMagnoliaConfigurationProperties(configurationProperties);
157 
158             // Initialize logging now that properties are available
159             Log4jConfigurer.initLogging();
160 
161             // Start 'system' ComponentProvider
162             builder = new GuiceComponentProviderBuilder();
163             builder.withConfiguration(getSystemComponents());
164             builder.withParent(platform);
165             builder.exposeGlobally();
166             system = builder.build();
167 
168             // Delegate to ConfigLoader to complete initialization
169             loader = system.getComponent(ConfigLoader.class);
170             if (startServer) {
171                 startServer();
172             }
173 
174         } catch (Throwable t) {
175             log.error("Oops, Magnolia could not be started", t);
176             t.printStackTrace();
177             if (t instanceof Error) {
178                 throw (Error) t;
179             }
180             if (t instanceof RuntimeException) {
181                 throw (RuntimeException) t;
182             }
183             throw new RuntimeException(t);
184         }
185     }
186 
187     @Override
188     public void contextDestroyed(final ServletContextEvent sce) {
189 
190         // avoid disturbing NPEs if the context has never been started (classpath problems, etc)
191         if (moduleManager != null) {
192             moduleManager.stopModules();
193         }
194 
195         stopServer();
196 
197         // We set the global ComponentProvider to its parent here, then we destroy it, components in it that expects the
198         // global ComponentProvider to be the one it lives in and the one that was there when the component was created
199         // might fail because of this. Maybe we can solve it by using the ThreadLocal override we already have and call
200         // scopes.
201 
202         if (system != null) {
203             Components.setComponentProvider(system.getParent());
204             system.destroy();
205         }
206 
207         if (platform != null) {
208             Components.setComponentProvider(platform.getParent());
209             platform.destroy();
210         }
211 
212         Log4jConfigurer.shutdownLogging();
213     }
214 
215     protected ComponentProviderConfiguration getPlatformComponents() {
216         ComponentProviderConfigurationBuilder configurationBuilder = new ComponentProviderConfigurationBuilder();
217         List<String> resources = getPlatformComponentsResources();
218         ComponentProviderConfiguration platformComponents = configurationBuilder.readConfiguration(resources, "platform");
219         platformComponents.registerInstance(ServletContext.class, servletContext);
220         // This is needed by DefaultMagnoliaInitPaths for backwards compatibility
221         platformComponents.registerInstance(MagnoliaServletContextListener.class, this);
222         return platformComponents;
223     }
224 
225     /**
226      * Returns a list of resources that contain platform components. Definitions for the same type will override giving
227      * preference to the last read definition. Checks for an init parameter in web.xml for an overridden location
228      * Subclasses can override this method to provide alternative strategies. The returned locations are used to find
229      * the resource on the class path.
230      */
231     protected List<String> getPlatformComponentsResources() {
232         String configLocation = servletContext.getInitParameter(PLATFORM_COMPONENTS_CONFIG_LOCATION_NAME);
233         if (StringUtils.isNotBlank(configLocation)) {
234             return Arrays.asList(StringUtils.split(configLocation, ", \n"));
235         }
236         return Collections.singletonList(DEFAULT_PLATFORM_COMPONENTS_CONFIG_LOCATION);
237     }
238 
239     protected ComponentProviderConfiguration getSystemComponents() {
240         ComponentProviderConfigurationBuilder configurationBuilder = new ComponentProviderConfigurationBuilder();
241         return configurationBuilder.getComponentsFromModules("system", platform.getComponent(ModuleRegistry.class).getModuleDefinitions());
242     }
243 
244     protected void startServer() {
245         MgnlContext.doInSystemContext(new MgnlContext.VoidOp() {
246             @Override
247             public void doExec() {
248                 loader.load();
249             }
250         }, true);
251     }
252 
253     protected void stopServer() {
254         if (loader != null) {
255             MgnlContext.doInSystemContext(new MgnlContext.VoidOp() {
256                 @Override
257                 public void doExec() {
258                     loader.unload();
259                 }
260             }, true);
261         }
262     }
263 
264     /**
265      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
266      */
267     protected String initWebappName(String rootPath) {
268         return null;
269     }
270 
271     /**
272      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
273      */
274     protected String initRootPath(final ServletContext context) {
275         return null;
276     }
277 
278     /**
279      * @deprecated since 4.5, use or subclass {@link MagnoliaInitPaths}.
280      */
281     protected String initServername(boolean unqualified) {
282         return null;
283     }
284 
285 }