KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > cms > util > dom > DOMBuilder


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23
24 package org.infoglue.cms.util.dom;
25
26 import java.io.ByteArrayInputStream JavaDoc;
27 import java.io.ByteArrayOutputStream JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.FileWriter JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.StringWriter JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.Map JavaDoc;
34
35 import org.apache.log4j.Logger;
36 import org.apache.xerces.parsers.DOMParser;
37 import org.dom4j.Document;
38 import org.dom4j.DocumentHelper;
39 import org.dom4j.Element;
40 import org.dom4j.Node;
41 import org.dom4j.io.DOMReader;
42 import org.dom4j.io.OutputFormat;
43 import org.dom4j.io.XMLWriter;
44 import org.infoglue.cms.exception.SystemException;
45 import org.infoglue.cms.io.FileHelper;
46 import org.xml.sax.InputSource JavaDoc;
47
48 /**
49  * This class is a utility-class for handling DOM-objects.
50  *
51  * @author Mattias Bogeblad
52  */

53
54 public class DOMBuilder
55 {
56     private final static Logger logger = Logger.getLogger(DOMBuilder.class.getName());
57
58     /**
59      * This method creates a new Document.
60      */

61     
62     public Document createDocument()
63     {
64         return DocumentHelper.createDocument();
65     }
66     
67     /**
68      * This method creates a new Document from an xml-string.
69      */

70     
71     public Document getDocument(String JavaDoc xml) throws Exception JavaDoc
72     {
73         if(xml == null)
74             return null;
75                     
76         try
77         {
78             InputSource JavaDoc xmlSource = new InputSource JavaDoc(new ByteArrayInputStream JavaDoc(xml.getBytes("UTF-8")));
79             DOMParser parser = new DOMParser();
80             parser.parse(xmlSource);
81             return buildDocment(parser.getDocument());
82         }
83         catch(Exception JavaDoc e)
84         {
85             e.printStackTrace();
86             throw new SystemException(e);
87         }
88     }
89     
90     
91     /** converts a W3C DOM document into a dom4j document */
92     public Document buildDocment(org.w3c.dom.Document JavaDoc domDocument)
93     {
94       DOMReader xmlReader = new DOMReader();
95       return xmlReader.read(domDocument);
96     }
97
98     
99     /**
100      * This method creates a new Document from a file.
101      */

102     
103     public Document getDocument(File JavaDoc file) throws Exception JavaDoc
104     {
105         if(file == null)
106             return null;
107             
108         Document document = null;
109         
110         try
111         {
112             String JavaDoc xml = FileHelper.readUTF8FromFile(file);
113             document = getDocument(xml);
114             
115             /*
116             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
117             DocumentBuilder builder = factory.newDocumentBuilder();
118             org.w3c.dom.Document documentW3C = builder.parse(new InputSource(new StringReader(xml)));
119             String modifiedXML = XMLHelper.serializeDom(documentW3C, new StringBuffer()).toString();
120             
121             FileHelper.writeUTF8ToFile(new File("c:/temp/treeXMLDocument.xml"), modifiedXML, false);
122             
123             FileHelper.writeUTF8ToFile(new File("c:/temp/treeXML.xml"), xml, false);
124             */

125             //SAXReader xmlReader = new SAXReader();
126
//document = xmlReader.read(file);
127
}
128         catch(Exception JavaDoc e)
129         {
130             e.printStackTrace();
131         }
132         
133         return document;
134     }
135     
136     /**
137      * A helper method to get nodes that has a namespace.
138      */

139
140     public Node selectSingleNode(Node contextNode, String JavaDoc xpathExpression, String JavaDoc namespaceName, String JavaDoc namespaceValue)
141     {
142         Map JavaDoc namespaces = new HashMap JavaDoc();
143         namespaces.put(namespaceName, namespaceValue);
144         org.dom4j.XPath xpath = contextNode.createXPath( xpathExpression );
145         xpath.setNamespaceURIs(namespaces);
146         return xpath.selectSingleNode(contextNode);
147     }
148
149     
150     /**
151      * This method adds an element with a given name to a given document.
152      */

153     
154     public Element addElement(Document document, String JavaDoc elementName)
155     {
156         Element newElement = document.addElement(elementName);
157         return newElement;
158     }
159
160     /**
161      * This method adds an element with a given name to a given parent element.
162      */

163     
164     public Element addElement(Element element, String JavaDoc elementName)
165     {
166         Element newElement = element.addElement(elementName);
167         return newElement;
168     }
169
170     /**
171      * This method adds an element to a given parent element.
172      */

173     
174     public void insertElement(Element element, Element childElement)
175     {
176         element.content().add(childElement);
177     }
178
179     /**
180      * This method adds a text-element with a given name to a given parent element.
181      */

182     
183     public Element addTextElement(Element element, String JavaDoc text)
184     {
185         Element newElement = element.addText(text);
186         return newElement;
187     }
188     
189
190     /**
191      * This method adds a cdata-element with a given name to a given parent element.
192      */

193     
194     public Element addCDATAElement(Element element, String JavaDoc text)
195     {
196         Element newElement = element.addCDATA(text);
197         return newElement;
198     }
199
200     /**
201      * This method adds an attribute with a given name and value to a given element.
202      */

203     
204     public void addAttribute(Element element, String JavaDoc attributeName, String JavaDoc attributeValue)
205     {
206         element.addAttribute(attributeName, attributeValue);
207     }
208
209     /**
210      * This method writes a document to file.
211      */

212     
213     public void write(Document document, String JavaDoc fileName) throws Exception JavaDoc
214     {
215         OutputFormat format = OutputFormat.createCompactFormat();
216         format.setEncoding("UTF-8");
217         XMLWriter writer = new XMLWriter(new FileWriter JavaDoc(fileName), format);
218         writer.write(document);
219         writer.close();
220         
221         /*
222         FileHelper.writeToFile(new File(fileName + "2"), document.asXML(), false);
223         FileHelper.writeUTF8ToFileSpecial(new File(fileName + "3"), document.asXML(), false);
224         FileHelper.writeUTF8(new File(fileName + "4"), document.asXML(), false);
225         FileHelper.writeUTF8ToFile(new File(fileName + "5"), document.asXML(), false);
226         */

227     }
228
229     /**
230      * This method writes a document to file nicely.
231      */

232     
233     public void writePretty(Document document, String JavaDoc fileName) throws IOException JavaDoc
234     {
235         OutputFormat format = OutputFormat.createPrettyPrint();
236         XMLWriter writer = new XMLWriter(new FileWriter JavaDoc(fileName), format);
237         writer.write(document);
238         writer.close();
239     }
240     
241     /**
242      * This method writes a document to System.out.
243      */

244
245     public void writeDebug(Document document) throws Exception JavaDoc
246     {
247         OutputFormat format = OutputFormat.createPrettyPrint();
248         XMLWriter writer = new XMLWriter( System.out, format );
249         writer.write( document );
250     }
251
252     public String JavaDoc encodeString(String JavaDoc value, String JavaDoc encoding) throws Exception JavaDoc
253     {
254         String JavaDoc encodedValue = new String JavaDoc(value.getBytes("UTF-8"), "ISO-8859-1");
255         return encodedValue;
256     }
257
258     /**
259      * This method writes a element to System.out.
260      */

261     
262     public void writeDebug(Element element) throws Exception JavaDoc
263     {
264         OutputFormat format = OutputFormat.createPrettyPrint();
265         XMLWriter writer = new XMLWriter( System.out, format );
266         writer.write( element );
267     }
268
269     /**
270      * This method gets the xml as a string with the correct encoding.
271      */

272     
273     private String JavaDoc getEncodedString(Element element) throws Exception JavaDoc
274     {
275         OutputFormat outFormat = OutputFormat.createCompactFormat();
276         outFormat.setEncoding("UTF-8");
277         ByteArrayOutputStream JavaDoc bao = new ByteArrayOutputStream JavaDoc();
278         XMLWriter out = new XMLWriter(bao, outFormat);
279         out.write(element);
280         out.flush();
281         String JavaDoc s = bao.toString();
282         logger.info("OUT: " + s);
283         return s;
284     }
285     
286     public String JavaDoc getFormattedDocument(Document doc, String JavaDoc encoding)
287     {
288         return getFormattedDocument(doc, true, false, encoding);
289     }
290     
291     public String JavaDoc getFormattedDocument(Document doc, boolean compact, boolean supressDecl, String JavaDoc encoding)
292     {
293         OutputFormat format = compact ? OutputFormat.createCompactFormat() : OutputFormat.createPrettyPrint();
294         format.setSuppressDeclaration(supressDecl);
295         format.setEncoding(encoding);
296         format.setExpandEmptyElements(false);
297         StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
298         XMLWriter writer = new XMLWriter(stringWriter, format);
299         try
300         {
301             writer.write(doc);
302         }
303         catch (IOException JavaDoc e)
304         {
305             e.printStackTrace();
306         }
307         return stringWriter.toString();
308     }
309
310 }
Popular Tags