View Javadoc

1   /**
2    * This file Copyright (c) 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 info.magnolia.cms.core.Path;
37  import info.magnolia.init.properties.FileSystemPropertySource;
38  import info.magnolia.init.properties.ServletContextPropertySource;
39  import org.apache.commons.lang.StringUtils;
40  
41  import javax.inject.Inject;
42  import javax.inject.Singleton;
43  import javax.servlet.ServletContext;
44  import java.io.FileNotFoundException;
45  import java.io.IOException;
46  import java.util.ArrayList;
47  import java.util.List;
48  
49  import static info.magnolia.cms.beans.config.PropertiesInitializer.processPropertyFilesString;
50  
51  /**
52   * Resolves the paths of the properties files to load. The name of the file can be defined as a context parameter in 
53   * web.xml. Multiple paths, comma separated, are supported (the first existing file in the list will be used), and the
54   * following variables will be used:
55   *
56   * <ul>
57   * <li><b><code>${servername}</code></b>: name of the server where the webapp is running, lowercase</li>
58   * <li><b><code>${webapp}</code></b>: the last token in the webapp path (e.g. <code>magnoliaPublic</code> for a webapp
59   * deployed at <code>tomcat/webapps/magnoliaPublic</code>)</li>
60   * </ul>
61   * <p>
62   * If no <code>magnolia.initialization.file</code> context parameter is set, the following default is assumed:
63   * </p>
64   *
65   * <pre>
66   * &lt;context-param>
67   *   &lt;param-name>magnolia.initialization.file&lt;/param-name>
68   *   &lt;param-value>
69   *      WEB-INF/config/${servername}/${webapp}/magnolia.properties,
70   *      WEB-INF/config/${servername}/magnolia.properties,
71   *      WEB-INF/config/${webapp}/magnolia.properties,
72   *      WEB-INF/config/default/magnolia.properties,
73   *      WEB-INF/config/magnolia.properties
74   *   &lt;/param-value>
75   * &lt;/context-param>
76   * </pre>
77   *
78   * <h3>Advanced usage: deployment service</h3>
79   *
80   * <p>
81   * Using the <code>${servername}</code> and <code>${webapp}</code> properties you can easily bundle in the same webapp
82   * different set of configurations which are automatically applied dependending on the server name (useful for switching
83   * between development, test and production instances where the repository configuration need to be different) or the
84   * webapp name (useful to bundle both the public and admin log4j/jndi/bootstrap configuration in the same war). By
85   * default the initializer will try to search for the file in different location with different combination of
86   * <code>servername</code> and <code>webapp</code>: the <code>default</code> fallback directory will be used if no other
87   * environment-specific directory has been added.
88   * </p>
89   *
90   * <p>The variables are provided by {@link MagnoliaInitPaths}.</p>
91   * 
92   * @version $Id$
93   */
94  @Singleton
95  public class DefaultMagnoliaPropertiesResolver implements MagnoliaPropertiesResolver {
96      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DefaultMagnoliaPropertiesResolver.class);
97  
98      /**
99       * Context parameter name. Value should be a comma-separated list of paths to look for properties files.
100      * Defaults to {@value #DEFAULT_INITIALIZATION_PARAMETER}
101      */
102     protected static final String MAGNOLIA_INITIALIZATION_FILE = "magnolia.initialization.file";
103 
104     /**
105      * Default value for the MAGNOLIA_INITIALIZATION_FILE parameter.
106      */
107     protected static final String DEFAULT_INITIALIZATION_PARAMETER =
108                       "WEB-INF/config/${servername}/${contextPath}/magnolia.properties,"
109                     + "WEB-INF/config/${servername}/${webapp}/magnolia.properties,"
110                     + "WEB-INF/config/${servername}/magnolia.properties,"
111                     + "WEB-INF/config/${contextPath}/magnolia.properties,"
112                     + "WEB-INF/config/${webapp}/magnolia.properties,"
113                     + "WEB-INF/config/default/magnolia.properties,"
114                     + "WEB-INF/config/magnolia.properties";
115 
116     private final ServletContext context;
117     private final List<String> locations;
118 
119     @Inject
120     public DefaultMagnoliaPropertiesResolver(ServletContext context, MagnoliaInitPaths initPaths) {
121         this.context = context;
122         String propertiesFilesString = getInitParameter(context, MAGNOLIA_INITIALIZATION_FILE, DEFAULT_INITIALIZATION_PARAMETER);
123 
124         // Use ROOT for the default (root) context, otherwise trim the leading slash to prevent double slashes
125         String contextPath = initPaths.getContextPath();
126         if (contextPath.length() == 0) {
127             contextPath = "ROOT";
128         } else {
129             contextPath = contextPath.substring(1);
130         }
131 
132         final String propertiesLocationString = processPropertyFilesString(context, initPaths.getServerName(), initPaths.getWebappFolderName(), propertiesFilesString, contextPath);
133         final String[] propertiesLocation = propertiesLocationString.trim().split("[,]+",0);
134         this.locations = new ArrayList<String>(propertiesLocation.length);
135         // TODO - order ?
136         // trim all:
137         for (String loc : propertiesLocation) {
138             locations.add(loc.trim());
139         }
140     }
141 
142     protected String getInitParameter(ServletContext ctx, String name, String defaultValue) {
143         final String propertiesFilesString = ctx.getInitParameter(name);
144         if (StringUtils.isEmpty(propertiesFilesString)) {
145             log.debug("{} value in web.xml is undefined, falling back to default: {}", name, defaultValue);
146             return defaultValue;
147         }
148         log.debug("{} value in web.xml is :'{}'", name, propertiesFilesString);
149         return propertiesFilesString;
150     }
151 
152     /**
153      * Used in tests, potentially in subclasses.
154      */
155     protected List<String> getLocations() {
156         return locations;
157     }
158 
159     @Override
160     public List<PropertySource> getSources() {
161         final List<PropertySource> sources = new ArrayList<PropertySource>();
162         boolean foundFiles = false;
163         for (String location : getLocations()) {
164             try {
165                 if (Path.isAbsolute(location)) {
166                     sources.add(new FileSystemPropertySource(location));
167                 } else {
168                     sources.add(new ServletContextPropertySource(context, location));
169                 }
170                 foundFiles = true;
171             } catch (FileNotFoundException e) {
172                 log.debug("Configuration file not found with path [{}]", location);
173             } catch (IOException e) {
174                 throw new RuntimeException(e); // TODO
175             }
176         }
177         if (!foundFiles) {
178             log.warn("No configuration files found using location list {}.", getLocations());
179         }
180 
181         return sources;
182     }
183 }