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