KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > kernel > management > DefaultServiceWriter


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.kernel.management;
66
67 import com.jcorporate.expresso.kernel.ComponentBase;
68 import com.jcorporate.expresso.kernel.ComponentLifecycle;
69 import com.jcorporate.expresso.kernel.Configuration;
70 import com.jcorporate.expresso.kernel.RootContainerInterface;
71 import com.jcorporate.expresso.kernel.digester.ComponentConfig;
72 import com.jcorporate.expresso.kernel.digester.ExpressoServicesConfig;
73 import com.jcorporate.expresso.kernel.exception.ConfigurationException;
74 import com.jcorporate.expresso.kernel.exception.ExpressoRuntimeException;
75 import com.jcorporate.expresso.kernel.util.ClassLocator;
76 import org.w3c.dom.Document JavaDoc;
77 import org.w3c.dom.Element JavaDoc;
78
79 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
80 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
81 import javax.xml.parsers.ParserConfigurationException JavaDoc;
82 import java.io.BufferedOutputStream JavaDoc;
83 import java.io.File JavaDoc;
84 import java.io.FileOutputStream JavaDoc;
85 import java.io.IOException JavaDoc;
86 import java.io.OutputStream JavaDoc;
87 import java.util.Iterator JavaDoc;
88 import java.util.Map JavaDoc;
89
90
91 /**
92  * Default Implementation of the class used to write the ExpressoServices
93  * configuration file to a file or stream. This class is an ExpressoComponent
94  * that receives various configuration items from the system.
95  * <p>This class also keeps keeps intact an instance of a DOM Writer. The particular
96  * implementation class for the <code>DOMWriter</code> depends on the contents
97  * of the Expresso Configuration file.</p>
98  *
99  * @author Michael Rimov
100  * @version $Revision: 1.5 $ on $Date: 2004/11/17 20:48:17 $
101  */

102
103 public class DefaultServiceWriter extends ComponentBase implements ServiceWriter, ComponentLifecycle {
104     DOMWriter domWriter = null;
105     String JavaDoc domWriterClass = null;
106
107     /**
108      * Default Constructor
109      */

110     public DefaultServiceWriter() {
111         super();
112     }
113
114     /**
115      * Retrieves the DOMWriter isntantiated class. May be null if the component
116      * was unable to load the specified system.
117      *
118      * @return an instantiated DOMWRiter for file writing.
119      */

120     public DOMWriter getDOMWriter() {
121         return domWriter;
122     }
123
124     /**
125      * Write the services file to a particular file location.
126      *
127      * @param rootContainer The RootContainer interface that will contain base
128      * information about the system state we are about to save.
129      * @param location The location to save the services file. (File name should be included
130      * in this parameter).
131      * @throws ExpressoRuntimeException upon error.
132      */

133     public void writeServicesFile(RootContainerInterface rootContainer, String JavaDoc location) throws ExpressoRuntimeException {
134         try {
135             File JavaDoc f = new File JavaDoc(location);
136             if (f == null) {
137                 throw new ExpressoRuntimeException("Unable to open file " + location + " for writing");
138             }
139
140             f.createNewFile();
141             OutputStream JavaDoc os = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(f));
142             this.writeServicesFile(rootContainer, os);
143             os.flush();
144             os.close();
145         } catch (IOException JavaDoc ex) {
146             throw new ExpressoRuntimeException("I/O error writing config file", ex);
147         }
148     }
149
150     /**
151      * Write the services file to a particular output stream
152      *
153      * @param rootContainer The RootContainer interface that will contain base
154      * information about the system state we are about to save.
155      * @param os The output stream to save the services file to.
156      * @throws ExpressoRuntimeException upon error.
157      */

158     public void writeServicesFile(RootContainerInterface rootContainer, OutputStream JavaDoc os) throws ExpressoRuntimeException {
159         Document JavaDoc d = buildDOMTree(rootContainer.getExpressoServicesConfig());
160         this.getDOMWriter().saveDocument(os, d);
161     }
162
163
164     /**
165      * Convert the ExpressoServicesConfig bean to a DOM document that's compatible
166      * with what is expected in the expresso-services.xml file.
167      *
168      * @param configRoot the root of the configuration tree.
169      * @return a DOM document representing the entire tree.
170      * @throws ExpressoRuntimeException if there is an error building the DOM tree
171      */

172     protected Document JavaDoc buildDOMTree(ExpressoServicesConfig configRoot) throws ExpressoRuntimeException {
173         try {
174             Document JavaDoc d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
175             Element JavaDoc root = d.createElement("expresso-services");
176             ComponentConfig c = configRoot.getRootConfig();
177             d.appendChild(root);
178             processComponentProperties(c, root, d);
179
180             for (Iterator JavaDoc i = c.getChildComponents().iterator(); i.hasNext();) {
181                 ComponentConfig oneChild = (ComponentConfig) i.next();
182                 processComponent(oneChild, root, d);
183             }
184
185             return d;
186         } catch (ParserConfigurationException JavaDoc ex) {
187             throw new ExpressoRuntimeException("DOM Parser Configuration Error saving file", ex);
188         } catch (FactoryConfigurationError JavaDoc ex) {
189             throw new ExpressoRuntimeException("DOM Document Factory Configuration Error saving file", ex);
190         }
191     }
192
193     /**
194      * Recursively go through the Expresso-services.config and convert all the various
195      * components into the DOM tree.
196      *
197      * @param config the current config bean in the tree
198      * @param parent the Parent DOM Element to append items to
199      * @param dom the DOM tree, used for building the various elements in the DOM tree.
200      */

201     protected void processComponent(ComponentConfig config, Element JavaDoc parent, Document JavaDoc dom) {
202         Element JavaDoc thisComponent = dom.createElement("component");
203         thisComponent.setAttribute("name", config.getName());
204         thisComponent.setAttribute("class-name", config.getClassName());
205         processComponentProperties(config, thisComponent, dom);
206         parent.appendChild(thisComponent);
207
208         for (Iterator JavaDoc i = config.getChildComponents().iterator(); i.hasNext();) {
209             ComponentConfig oneChild = (ComponentConfig) i.next();
210             processComponent(oneChild, thisComponent, dom);
211         }
212     }
213
214     /**
215      * Write the current component's configuration to the current DOM element.
216      *
217      * @param config the current config to glean the properties from
218      * @param parent the parent element to append properties to as children.
219      * @param dom the DOM tree to use for Element factores
220      */

221     protected void processComponentProperties(ComponentConfig config, Element JavaDoc parent, Document JavaDoc dom) {
222         //
223
//Write Simple Properties
224
//
225
for (Iterator JavaDoc i = config.getProperties().keySet().iterator(); i.hasNext();) {
226             String JavaDoc propName = (String JavaDoc) i.next();
227             String JavaDoc propValue = config.getProperty(propName);
228             Element JavaDoc property = dom.createElement("property");
229             property.setAttribute("name", propName);
230             property.setAttribute("value", propValue);
231             parent.appendChild(property);
232         }
233
234         //
235
//Write Mapped Properties
236
//
237
Map JavaDoc allMappedProperties = (Map JavaDoc) config.getAllMappedProperties();
238         for (Iterator JavaDoc i = allMappedProperties.keySet().iterator(); i.hasNext();) {
239             String JavaDoc propertyName = (String JavaDoc) i.next();
240             Map JavaDoc subMap = (Map JavaDoc) allMappedProperties.get(propertyName);
241             for (Iterator JavaDoc j = subMap.keySet().iterator(); j.hasNext();) {
242                 String JavaDoc propertyKey = (String JavaDoc) j.next();
243                 String JavaDoc propertyValue = (String JavaDoc) subMap.get(propertyKey);
244                 Element JavaDoc property = dom.createElement("mapped-property");
245                 property.setAttribute("name", propertyName);
246                 property.setAttribute("key", propertyKey);
247                 property.setAttribute("value", propertyValue);
248                 parent.appendChild(property);
249             }
250         }
251
252         //
253
//Write Indexed Properties
254
//
255
Map JavaDoc allIndexedProperties = (Map JavaDoc) config.getAllIndexedProperties();
256         for (Iterator JavaDoc i = allIndexedProperties.keySet().iterator(); i.hasNext();) {
257             String JavaDoc propertyName = (String JavaDoc) i.next();
258             Map JavaDoc subMap = (Map JavaDoc) allMappedProperties.get(propertyName);
259             for (Iterator JavaDoc j = subMap.keySet().iterator(); j.hasNext();) {
260                 Integer JavaDoc propertyIndex = (Integer JavaDoc) j.next();
261                 String JavaDoc propertyValue = (String JavaDoc) subMap.get(propertyIndex);
262                 Element JavaDoc property = dom.createElement("indexed-property");
263                 property.setAttribute("name", propertyName);
264                 property.setAttribute("index", propertyIndex.toString());
265                 property.setAttribute("value", propertyValue);
266                 parent.appendChild(property);
267             }
268         }
269     }
270
271     public void initialize() {
272
273     }
274
275     /**
276      * Configure the DefaultServiceWriter. The chief configuration value is
277      * the domWriter class, which describes which implementation to use for
278      * writing out DOM documents.
279      *
280      * @param newConfig the Configuration object to load items from.
281      * @throws ConfigurationException if the domWriterClass cannot be instantiated
282      */

283     public void configure(Configuration newConfig) throws ConfigurationException {
284         String JavaDoc temp = (String JavaDoc) newConfig.get("domWriterClass");
285         try {
286             setDomWriterClass(temp);
287         } catch (ExpressoRuntimeException ex) {
288             throw new ConfigurationException("Invalid paramter 'serviceWriterClass'="
289                     + temp, ex.getNested());
290         }
291     }
292
293     /**
294      * Reconfigure lifecycle event for this component. It attempts to load a new
295      * DOMWriter class, however, if unable to do so, it will rollback the configuration
296      * internally and throw a ConfigurationException.
297      *
298      * @param newConfig the Configuration object to load items from.
299      * @throws ConfigurationException if the system is unable to load the new DOMWriter
300      * class specified.
301      */

302     public void reconfigure(Configuration newConfig) throws ConfigurationException {
303         String JavaDoc rollBackClass = this.getDomWriterClass();
304         try {
305             configure(newConfig);
306         } catch (ConfigurationException ex) {
307             try {
308                 this.setDomWriterClass(rollBackClass);
309             } catch (ExpressoRuntimeException ex1) {
310                 throw new ConfigurationException("Error rolling back configuration", ex1);
311             }
312
313             throw new ConfigurationException("Error setting configuration", ex);
314         }
315     }
316
317     /**
318      * Implementation of the Destroy() lifecycle event. nulls out all member
319      * properties.
320      */

321     public void destroy() {
322         domWriter = null;
323         domWriterClass = null;
324     }
325
326     /**
327      * Retrieves the previously set classname of the Dom Writer
328      *
329      * @return java.lang.String
330      */

331     public String JavaDoc getDomWriterClass() {
332         return domWriterClass;
333     }
334
335     /**
336      * Sets and loads the specified domWriter class.
337      *
338      * @param domWriterClass The classname of the DOMWriter to load
339      */

340     public void setDomWriterClass(String JavaDoc domWriterClass) throws ExpressoRuntimeException {
341         try {
342             DOMWriter tmp = (DOMWriter) (ClassLocator.loadClass(domWriterClass).newInstance());
343             this.domWriterClass = domWriterClass;
344             domWriter = tmp;
345         } catch (Exception JavaDoc ex) {
346             throw new ExpressoRuntimeException("Error setting DOM Writer Class", ex);
347         }
348     }
349 }
Popular Tags