KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > columba > core > xml > XmlIO


1 //The contents of this file are subject to the Mozilla Public License Version 1.1
2
//(the "License"); you may not use this file except in compliance with the
3
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
4
//
5
//Software distributed under the License is distributed on an "AS IS" basis,
6
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
7
//for the specific language governing rights and
8
//limitations under the License.
9
//
10
//The Original Code is "The Columba Project"
11
//
12
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
13
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
14
//
15
//All Rights Reserved.
16
package org.columba.core.xml;
17
18 import java.io.BufferedWriter JavaDoc;
19 import java.io.CharArrayWriter JavaDoc;
20 import java.io.FileOutputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.InputStream JavaDoc;
23 import java.io.OutputStream JavaDoc;
24 import java.io.OutputStreamWriter JavaDoc;
25 import java.io.Writer JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.logging.Logger JavaDoc;
31
32 import javax.swing.JOptionPane JavaDoc;
33 import javax.xml.parsers.SAXParser JavaDoc;
34 import javax.xml.parsers.SAXParserFactory JavaDoc;
35
36 import org.columba.core.logging.Logging;
37 import org.xml.sax.Attributes JavaDoc;
38 import org.xml.sax.SAXException JavaDoc;
39 import org.xml.sax.helpers.DefaultHandler JavaDoc;
40
41 public class XmlIO extends DefaultHandler JavaDoc {
42
43     private static final Logger JavaDoc LOG = Logger.getLogger("org.columba.core.xml");
44
45     private static final String JavaDoc ROOT_XML_ELEMENT_NAME = "__COLUMBA_XML_TREE_TOP__";
46
47     // Top level element (Used to hold everything else)
48
private XmlElement rootElement;
49
50     // The current element you are working on
51
private XmlElement currentElement;
52
53     // For writing out the data
54
// Indent for each level
55
private int writeIndent = 2;
56
57     // Maximum data to put on a "one liner"
58
private int maxOneLineData = 20;
59
60     // Buffer for collecting data from
61
// the "characters" SAX event.
62
private CharArrayWriter JavaDoc contents = new CharArrayWriter JavaDoc();
63
64     private URL JavaDoc url = null;
65
66     /*
67      * // Default constructor public XmlIO() { }
68      */

69     /*
70      * // setup and load constructor public XmlIO(String FilePath) {
71      * currentElement = null;
72      * }
73      */

74     public XmlIO(URL JavaDoc url) {
75         super();
76         this.url = url;
77     }
78
79     // setup and load constructor
80
public XmlIO() {
81         currentElement = null;
82     }
83
84     // setup and load constructor
85

86     /**
87      * Creates a XmlIO object with the specified element at the top.
88      *
89      * @param element
90      * the element at the top.
91      */

92     public XmlIO(XmlElement element) {
93         rootElement = new XmlElement(ROOT_XML_ELEMENT_NAME);
94         rootElement.addElement(element);
95     }
96
97     public void setURL(URL JavaDoc url) {
98         this.url = url;
99     }
100
101     public boolean load() {
102         // this.file = F;
103
return load(url);
104     }
105
106     // Load a file. This is what starts things off.
107

108     /**
109      * Loads from the InputStream into the root Xml Element.
110      *
111      * @param input
112      * the input stream to load from.
113      */

114     public boolean load(InputStream JavaDoc input) {
115
116         rootElement = new XmlElement(ROOT_XML_ELEMENT_NAME);
117         currentElement = rootElement;
118
119         try {
120             // Create the XML reader...
121
// xr = XMLReaderFactory.createXMLReader();
122
SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
123
124             // Set the ContentHandler...
125
// xr.setContentHandler( this );
126
SAXParser JavaDoc saxParser = factory.newSAXParser();
127
128             saxParser.parse(input, this);
129         } catch (javax.xml.parsers.ParserConfigurationException JavaDoc ex) {
130             LOG
131                     .severe("XML config error while attempting to read from the input stream \n'"
132                             + input + "'");
133             LOG.severe(ex.toString());
134             ex.printStackTrace();
135
136             return (false);
137         } catch (SAXException JavaDoc ex) {
138             // Error
139
LOG
140                     .severe("XML parse error while attempting to read from the input stream \n'"
141                             + input + "'");
142             LOG.severe(ex.toString());
143             ex.printStackTrace();
144
145             return (false);
146         } catch (IOException JavaDoc ex) {
147             LOG
148                     .severe("I/O error while attempting to read from the input stream \n'"
149                             + input + "'");
150             LOG.severe(ex.toString());
151             ex.printStackTrace();
152
153             return (false);
154         }
155
156         // XmlElement.printNode( getRoot(), "");
157
return (true);
158     }
159
160     /**
161      * Load a file. This is what starts things off.
162      *
163      * @param inputURL
164      * the URL to load XML from.
165      */

166     public boolean load(URL JavaDoc inputURL) {
167
168         rootElement = new XmlElement(ROOT_XML_ELEMENT_NAME);
169         currentElement = rootElement;
170
171         try {
172             // Create the XML reader...
173
// xr = XMLReaderFactory.createXMLReader();
174
SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
175
176             // Set the ContentHandler...
177
// xr.setContentHandler( this );
178
SAXParser JavaDoc saxParser = factory.newSAXParser();
179
180             saxParser.parse(inputURL.toString(), this);
181         } catch (javax.xml.parsers.ParserConfigurationException JavaDoc ex) {
182             LOG.severe("XML config error while attempting to read XML file \n'"
183                     + inputURL + "'");
184             LOG.severe(ex.toString());
185             if ( Logging.DEBUG)
186                 ex.printStackTrace();
187
188             return (false);
189         } catch (SAXException JavaDoc ex) {
190             // Error
191
LOG.severe("XML parse error while attempting to read XML file \n'"
192                     + inputURL + "'");
193             LOG.severe(ex.toString());
194             if ( Logging.DEBUG)
195             ex.printStackTrace();
196
197             return (false);
198         } catch (IOException JavaDoc ex) {
199             LOG.severe("I/O error while attempting to read XML file \n'"
200                     + inputURL + "'");
201             LOG.severe(ex.toString());
202             if ( Logging.DEBUG)
203             ex.printStackTrace();
204
205             return (false);
206         }
207
208         // XmlElement.printNode( getRoot(), "");
209
return (true);
210     }
211
212     // Implement the content hander methods that
213
// will delegate SAX events to the tag tracker network.
214
public void startElement(String JavaDoc namespaceURI, String JavaDoc localName,
215             String JavaDoc qName, Attributes JavaDoc attrs) throws SAXException JavaDoc {
216         // Resetting contents buffer.
217
// Assuming that tags either tag content or children, not both.
218
// This is usually the case with XML that is representing
219
// data strucutures in a programming language independant way.
220
// This assumption is not typically valid where XML is being
221
// used in the classical text mark up style where tagging
222
// is used to style content and several styles may overlap
223
// at once.
224
try {
225             contents.reset();
226
227             String JavaDoc name = localName; // element name
228

229             if (name.equals("")) {
230                 name = qName; // namespaceAware = false
231
}
232
233             XmlElement p = currentElement;
234
235             currentElement = currentElement.addSubElement(name);
236             currentElement.setParent(p);
237
238             if (attrs != null) {
239                 for (int i = 0; i < attrs.getLength(); i++) {
240                     String JavaDoc aName = attrs.getLocalName(i); // Attr name
241

242                     if (aName.equals("")) {
243                         aName = attrs.getQName(i);
244                     }
245
246                     currentElement.addAttribute(aName, attrs.getValue(i));
247                 }
248             }
249         } catch (java.lang.NullPointerException JavaDoc ex) {
250             LOG.severe("Null!!!");
251             LOG.severe(ex.toString());
252             ex.printStackTrace();
253         }
254     }
255
256     public void endElement(String JavaDoc namespaceURI, String JavaDoc localName, String JavaDoc qName)
257             throws SAXException JavaDoc {
258         currentElement.setData(contents.toString().trim());
259         contents.reset();
260
261         currentElement = currentElement.getParent();
262     }
263
264     public void characters(char[] ch, int start, int length)
265             throws SAXException JavaDoc {
266         // accumulate the contents into a buffer.
267
contents.write(ch, start, length);
268     }
269
270     /**
271      * Returns the root for the XmlElement hiearchy. Note that this Xml Element
272      * will always have the name <code>__COLUMBA_XML_TREE_TOP__</code>.
273      * <p>
274      * Methods that want to retrieve elements from this root should use the
275      * {@link XmlElement#getElement(String)} in order to get the wanted element.
276      *
277      * @return a XmlElement if it has been loaded or initialized with it; null
278      * otherwise.
279      */

280     public XmlElement getRoot() {
281         return (rootElement);
282     }
283
284     public void errorDialog(String JavaDoc Msg) {
285         JOptionPane.showMessageDialog(null, "Error: " + Msg);
286     }
287
288     public void warningDialog(String JavaDoc Msg) {
289         JOptionPane.showMessageDialog(null, "Warning: " + Msg);
290     }
291
292     public void infoDialog(String JavaDoc Msg) {
293         JOptionPane.showMessageDialog(null, "Info: " + Msg);
294     }
295
296     public void save() throws Exception JavaDoc {
297         write(new FileOutputStream JavaDoc(url.getPath()));
298     }
299
300     //
301
// Writer interface
302
//
303
public void write(OutputStream JavaDoc out) throws IOException JavaDoc {
304         BufferedWriter JavaDoc PW = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(out,
305                 "UTF-8"));
306         PW.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
307
308         if (rootElement.subElements.size() > 0) {
309             for (int i = 0; i < rootElement.subElements.size(); i++) {
310                 _writeSubNode(PW, (XmlElement) rootElement.subElements.get(i),
311                         0);
312             }
313         }
314
315         PW.flush();
316     }
317
318     private void _writeSubNode(Writer JavaDoc out, XmlElement element, int indent)
319             throws IOException JavaDoc {
320         _writeSpace(out, indent);
321         out.write("<");
322         out.write(element.getName());
323
324         for (Enumeration JavaDoc e = element.getAttributeNames(); e.hasMoreElements();) {
325             String JavaDoc K = (String JavaDoc) e.nextElement();
326             out.write(" " + K + "=\""
327                     + TextUtils.escapeText(element.getAttribute(K)) + "\"");
328         }
329
330         out.write(">");
331
332         String JavaDoc data = element.getData();
333
334         if ((data != null) && !data.equals("")) {
335             if (data.length() > maxOneLineData) {
336                 out.write("\n");
337                 _writeSpace(out, indent + writeIndent);
338             }
339
340             out.write(TextUtils.escapeText(data));
341         }
342
343         List JavaDoc subElements = element.getElements();
344
345         if (subElements.size() > 0) {
346             out.write("\n");
347
348             for (Iterator JavaDoc it = subElements.iterator(); it.hasNext();) {
349                 _writeSubNode(out, (XmlElement) it.next(), indent + writeIndent);
350
351                 // for (int i = 0; i < subElements.size(); i++) {
352
// _writeSubNode(
353
// out,
354
// (XmlElement) subElements.get(i),
355
// indent + writeIndent);
356
}
357
358             _writeSpace(out, indent);
359         }
360
361         if (data.length() > maxOneLineData) {
362             out.write("\n");
363             _writeSpace(out, indent);
364         }
365
366         out.write("</" + TextUtils.escapeText(element.getName()) + ">\n");
367     }
368
369     private void _writeSpace(Writer JavaDoc out, int numSpaces) throws IOException JavaDoc {
370         for (int i = 0; i < numSpaces; i++) {
371             out.write(" ");
372         }
373     }
374 }
375
376 // End class XmlIO
377
Popular Tags