KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > XmlPropertyTask


1 /*****************************************************************************
2  * Copyright (C) The Krysalis project. All rights reserved. *
3  * ------------------------------------------------------------------------- *
4  * This software is published under the terms of the Krysalis Patchy *
5  * Software License version 1.1_01, a copy of which has been included *
6  * at the bottom of this file. *
7  *****************************************************************************/

8
9 import java.io.InputStream JavaDoc;
10 import java.io.FileInputStream JavaDoc;
11 import java.io.BufferedInputStream JavaDoc;
12 import java.io.OutputStream JavaDoc;
13 import java.io.FileOutputStream JavaDoc;
14 import java.io.Writer JavaDoc;
15 import java.io.PrintWriter JavaDoc;
16 import java.io.FileWriter JavaDoc;
17 import java.io.BufferedWriter JavaDoc;
18 import java.io.FileWriter JavaDoc;
19 import java.io.IOException JavaDoc;
20
21 import java.util.ArrayList JavaDoc;
22
23 import org.w3c.dom.NodeList JavaDoc;
24 import org.w3c.dom.Node JavaDoc;
25 import org.w3c.dom.Element JavaDoc;
26 import org.w3c.dom.Attr JavaDoc;
27 import org.w3c.dom.Document JavaDoc;
28 import org.w3c.dom.DOMException JavaDoc;
29 import org.w3c.dom.NamedNodeMap JavaDoc;
30
31 import javax.xml.parsers.DocumentBuilder JavaDoc;
32 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
33 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
34 import javax.xml.parsers.ParserConfigurationException JavaDoc;
35
36 import org.xml.sax.SAXException JavaDoc;
37 import org.xml.sax.SAXParseException JavaDoc;
38
39 import org.apache.tools.ant.BuildException;
40 import org.apache.tools.ant.taskdefs.Property;
41
42 import org.apache.tools.ant.BuildException;
43 import org.apache.tools.ant.taskdefs.Property;
44
45 import org.apache.tools.ant.Task;
46 import org.apache.tools.ant.Project;
47 import org.apache.tools.ant.AntClassLoader;
48 import org.apache.tools.ant.ProjectHelper;
49 import org.apache.tools.ant.types.Path;
50 import org.apache.tools.ant.types.Reference;
51
52 /**
53  * Task get property values from a valid xml file.
54  * Example:
55  * <root-tag myattr="true">
56  * <inner-tag>Text</inner-tag>
57  * <2><3><4>false</4></3></2>
58  * </root-tag>
59  *
60  * xml.root-tag.myattr=true
61  * xml.root-tag.inner-tag=Text
62  * xml.root-tag.2.3.4=false
63  *
64  * @author <a HREF="mailto:barozzi@nicolaken.com">Nicola Ken Barozzi</a>
65  * @created 14 January 2002
66  */

67
68 public class XmlPropertyTask extends org.apache.tools.ant.Task
69 {
70     private String JavaDoc src;
71     private org.w3c.dom.Document JavaDoc document;
72     
73     /**
74      * Constructor.
75      */

76     public XmlPropertyTask()
77     {
78         super();
79     }
80
81     /**
82      * Initializes the task.
83      */

84
85     public void init()
86     {
87         super.init();
88     }
89
90     /**
91      * Run the task.
92      * @exception org.apache.tools.ant.BuildException The exception raised during task execution.
93      */

94     public void execute()
95         throws org.apache.tools.ant.BuildException
96     {
97         BufferedInputStream JavaDoc configurationStream = null;
98       
99         try
100         {
101             configurationStream =
102                 new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(src));
103                 
104             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
105             
106             factory.setValidating(false);
107             factory.setNamespaceAware(false);
108     
109             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
110             document = builder.parse( configurationStream );
111
112             addNodeRecursively(document.getDocumentElement(),"xml");
113             
114         } catch (SAXException JavaDoc sxe) {
115            // Error generated during parsing
116
Exception JavaDoc x = sxe;
117            if (sxe.getException() != null)
118                x = sxe.getException();
119            throw new BuildException(x);
120     
121         } catch (ParserConfigurationException JavaDoc pce) {
122            // Parser with specified options can't be built
123
throw new BuildException(pce);
124         } catch (IOException JavaDoc ioe) {
125            // I/O error
126
throw new BuildException(ioe);
127         }
128         finally
129         {
130           if(configurationStream!=null){
131             try{configurationStream.close();}catch(Exception JavaDoc e){}}
132         }
133     }
134
135     
136     void addNodeRecursively(org.w3c.dom.Node JavaDoc node, String JavaDoc text) {
137
138         if (node.hasAttributes()) {
139             org.w3c.dom.NamedNodeMap JavaDoc nodeAttributes = node.getAttributes();
140             for (int i = 0; i < nodeAttributes.getLength(); i++) {
141                Node JavaDoc attributeNode = nodeAttributes.item(i);
142                String JavaDoc attributeName = text+"."+node.getNodeName()+"."+attributeNode.getNodeName();
143                String JavaDoc attributeValue = attributeNode.getNodeValue();
144                log(attributeName+":"+attributeValue, Project.MSG_VERBOSE);
145                project.setUserProperty(attributeName,attributeValue);
146             }
147         }
148        
149         if(node.getNodeType()==Node.TEXT_NODE){
150           String JavaDoc nodeText = node.getNodeValue();
151           if(nodeText.trim().length()!=0)
152           {
153              log(text+":"+nodeText, Project.MSG_VERBOSE);
154              project.setUserProperty(text,nodeText);
155           }
156         }
157                
158           if (node.hasChildNodes()) {
159              text+=("."+node.getNodeName());
160              org.w3c.dom.NodeList JavaDoc nodeChildren = node.getChildNodes();
161              for (int i = 0; i < nodeChildren.getLength(); i++) {
162                  addNodeRecursively(nodeChildren.item(i), text);
163              }
164          }
165     }
166     
167     public void setFile(String JavaDoc src)
168     {
169         this.src = src;
170     }
171 }
172
173
174 /*
175 The Krysalis Patchy Software License, Version 1.1_01
176 Copyright (c) 2002 Nicola Ken Barozzi. All rights reserved.
177
178 This Licence is compatible with the BSD licence as described and
179 approved by http://www.opensource.org/, and is based on the
180 Apache Software Licence Version 1.1.
181
182 Redistribution and use in source and binary forms, with or without
183 modification, are permitted provided that the following conditions
184 are met:
185
186  1. Redistributions of source code must retain the above copyright
187     notice, this list of conditions and the following disclaimer.
188
189 2. Redistributions in binary form must reproduce the above copyright
190    notice, this list of conditions and the following disclaimer in
191    the documentation and/or other materials provided with the
192    distribution.
193
194 3. The end-user documentation included with the redistribution,
195    if any, must include the following acknowledgment:
196       "This product includes software developed for project
197        Krysalis (http://www.krysalis.org/)."
198    Alternately, this acknowledgment may appear in the software itself,
199    if and wherever such third-party acknowledgments normally appear.
200
201 4. The names "Krysalis" and "Nicola Ken Barozzi" and
202    "Krysalis Centipede" must not be used to endorse or promote products
203    derived from this software without prior written permission. For
204    written permission, please contact krysalis@nicolaken.org.
205    
206 5. Products derived from this software may not be called "Krysalis",
207    "Krysalis Centipede", nor may "Krysalis" appear in their name,
208    without prior written permission of Nicola Ken Barozzi.
209
210 6. This software may contain voluntary contributions made by many
211    individuals, who decided to donate the code to this project in
212    respect of this licence.
213
214 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
215 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
216 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
217 DISCLAIMED. IN NO EVENT SHALL THE KRYSALIS PROJECT OR
218 ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
219 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
220 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
221 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
222 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
223 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
224 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
225 SUCH DAMAGE.
226 ====================================================================*/

227
Popular Tags