View Javadoc

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