View Javadoc

1   /** ------------------------------------
2    * SweetDEV RIA library
3    * Copyright [2006 - 2010] [Ideo Technologies]
4    * ------------------------------------
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   * 		http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   *
18   *
19   * For more information, please contact us at:
20   *         Ideo Technologies S.A
21   *        124 rue de Verdun
22   *        92800 Puteaux - France
23   *
24   *      France & Europe Phone : +33 1.46.25.09.60
25   *
26   *
27   *        web : http://www.ideotechnologies.com
28   *        email : SweetDEV-RIA@ideotechnologies.com
29   *
30   *
31   * @version ${pom.version}
32   * @author Ideo Technologies
33   */
34  package com.ideo.sweetdevria.config;
35  
36  import java.io.IOException;
37  import java.io.InputStream;
38  import java.net.MalformedURLException;
39  import java.net.URL;
40  import java.util.Enumeration;
41  
42  import javax.servlet.UnavailableException;
43  
44  import org.apache.commons.digester.Digester;
45  import org.apache.commons.logging.Log;
46  import org.apache.commons.logging.LogFactory;
47  import org.xml.sax.SAXException;
48  
49  import com.ideo.sweetdevria.config.elements.MessageResourcesConfig;
50  import com.ideo.sweetdevria.config.elements.PlugInConfig;
51  import com.ideo.sweetdevria.controller.RIAController;
52  import com.ideo.sweetdevria.tag.pluginAPI.PluginManager;
53  import com.ideo.sweetdevria.util.ClassUtils;
54  import com.ideo.sweetdevria.util.MessageResources;
55  import com.ideo.sweetdevria.util.MessageResourcesFactory;
56  
57  /**
58   * Configurator.
59   *
60   */
61  public class Configurator {
62  
63      /**
64       * Default config file.
65       */
66      public static final String DEFAULT_CONFIG = "ria-config.xml";
67  
68      /**
69       * The Digester used to produce RIAConfig object from a configuration files.
70       */
71      protected Digester configDigester = null;
72  
73      /**
74       * Commons Logging instance.
75       */
76      protected static Log log = LogFactory.getLog(Configurator.class);
77  
78      private boolean validating = false;
79  
80      /**
81       * Get the validating.
82       * @return  Returns the validating.
83       */
84      public boolean isValidating() {
85          return validating;
86      }
87  
88      /**
89       * Set the validating.
90       * @param validating  The validating to set.
91       */
92      public void setValidating(final boolean validating) {
93          this.validating = validating;
94      }
95  
96      /**
97       * 
98       * @param paths
99       * @return A RIAConfig object containing all the information contained by the ria config file (default: ria-config.xml)
100      * @throws Exception
101      */
102     public IRIAConfig init(final String paths) throws Exception {
103         IRIAConfig moduleConfig = initModuleConfig(paths);
104 
105         initModuleMessageResources(moduleConfig);
106         
107         // Register the configuration
108         RIAController.getInstance().setConfig(moduleConfig);
109         return moduleConfig;
110     }
111 
112 
113     /**
114      * <p>Initialize the application MessageResources.</p>
115      *
116      * @param config RIAConfig information
117      *
118      * @exception Exception if initialization cannot be performed
119      */
120     protected void initModuleMessageResources(final IRIAConfig config) throws Exception {
121 
122         MessageResourcesConfig[] mrcs = config.findMessageResourcesConfigs();
123         for (int i = 0; i < mrcs.length; i++) {
124             if ((mrcs[i].getFactory() == null) || (mrcs[i].getParameter() == null)) {
125                 continue;
126             }
127             if (log.isDebugEnabled()) {
128                 log.debug("Initializing module path message resources from '" + mrcs[i].getParameter() + "'");
129             }
130 
131             String factory = mrcs[i].getFactory();
132             MessageResourcesFactory.setFactoryClass(factory);
133             MessageResourcesFactory factoryObject = MessageResourcesFactory.createFactory();
134 
135             MessageResources resources = factoryObject.createResources(mrcs[i].getParameter());
136             resources.setReturnNull(mrcs[i].getNull());
137 
138             RIAController.getInstance().addResource(mrcs[i].getKey(), resources);
139         }
140 
141         PlugInConfig[] plugins = config.findPlugInConfigs();
142         for (int i = 0; i < plugins.length; i++) {
143             if ((plugins[i] == null) || (plugins[i].getClassName() == null)) {
144                 continue;
145             }
146             if (log.isDebugEnabled()) {
147                 log.debug("Loading plugin [" + plugins[i].getClassName() + "'");
148             }
149             PluginManager.getPluginManager().loadPlugin(plugins[i].getClassName());
150         }
151     }
152 
153     /**
154      * Initialize the application configuration information.
155      *
156      * @param paths Comma-separated list of resource path(s)
157      * @throws Exception On problem during configuration initialisation.
158      */
159     protected IRIAConfig initModuleConfig(String paths) throws Exception {
160 
161         if (log.isDebugEnabled()) {
162             log.debug("Initializing configuration from '" + paths + "'");
163         }
164 
165         // Configure the Digester instance we will use
166         Digester digester = initConfigDigester();
167         IRIAConfig config = new RIAConfigImpl();
168 
169         // Process each specified resource path
170         int count = 0;
171         String[] pathsSplit = paths.split(",");
172         while (count<pathsSplit.length) {
173             String path = pathsSplit[count].trim();            
174             this.parseModuleConfigFile(config, digester, path);
175             count++;
176         }
177         config.freeze();
178         return (config);
179 
180     }
181 
182     /**
183      * Parses one module config file.
184      * @param prefix
185      * @param paths
186      * @param config
187      * @param digester Digester instance that does the parsing
188      * @param path The path to the config file to parse.
189      * @throws UnavailableException
190      */
191     private void parseModuleConfigFile(final IRIAConfig config, final Digester digester, final String path) throws UnavailableException {
192 
193         InputStream input = null;
194         try {
195         	Enumeration resources = ClassUtils.getClassLoader().getResources(path);
196         	
197         	while (resources.hasMoreElements()) {
198 				URL elem = (URL) resources.nextElement();
199 				input = elem.openStream();
200 				
201 				digester.clear();
202 				digester.push(config);
203 				digester.parse(input);
204 				
205 				input.close();
206 			}
207         } catch (MalformedURLException e) {
208             handleConfigException(e);
209         } catch (IOException e) {
210             handleConfigException(e);
211         } catch (SAXException e) {
212             handleConfigException(e);
213         } finally {
214             if (input != null) {
215                 try {
216                     input.close();
217                 } catch (IOException e) {
218                     handleConfigException(e);
219                 }
220             }
221         }
222     }
223 
224     /**
225      * Simplifies exception handling in the parseModuleConfigFile() method.
226      * @param paths
227      * @param e
228      * @throws UnavailableException
229      */
230     private void handleConfigException(final Exception e) throws UnavailableException {
231         log.error(e.getMessage(), e);
232         throw new UnavailableException(e.getMessage());
233     }
234 
235     protected Digester initConfigDigester() throws Exception {
236         // Do we have an existing instance?
237         if (configDigester != null) {
238             return (configDigester);
239         }
240 
241         // Create a new Digester instance with standard capabilities
242         configDigester = new Digester();
243         configDigester.setNamespaceAware(true);
244         configDigester.setValidating(validating);
245         configDigester.setUseContextClassLoader(true);
246         configDigester.addRuleSet(new ConfigRuleSet());
247 
248         return (configDigester);
249     }
250 
251 }