KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > micronova > util > XMLUtil


1 /*
2
3 Copyright 2003-2007 MicroNova (R)
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or
7 without modification, are permitted provided that the following
8 conditions are met:
9
10     * Redistributions of source code must retain the above copyright
11     notice, this list of conditions and the following disclaimer.
12
13     * Redistributions in binary form must reproduce the above copyright
14     notice, this list of conditions and the following disclaimer in the
15     documentation and/or other materials provided with the distribution.
16
17     * Neither the name of MicroNova nor the names of its contributors
18     may be used to endorse or promote products derived from this
19     software without specific prior written permission.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 POSSIBILITY OF SUCH DAMAGE.
32
33 */

34
35
36 package com.micronova.util;
37
38 import java.util.*;
39 import java.io.*;
40 import java.text.*;
41 import java.util.regex.*;
42
43 import javax.xml.parsers.*;
44 import javax.xml.transform.*;
45 import javax.xml.transform.dom.*;
46 import javax.xml.transform.stream.*;
47 import javax.xml.transform.sax.*;
48 import org.w3c.dom.*;
49 import org.xml.sax.*;
50 import java.net.*;
51
52 /** XML utilities */
53
54 public class XMLUtil
55 {
56     /** tag encoding/decoding maps */
57
58     private static final Pattern patternEncode;
59     private static final Map replacementMapEncode;
60
61     private static final Pattern patternDecode;
62     private static final Map replacementMapDecode;
63
64     static
65     {
66         patternDecode = Pattern.compile("(&|"|<|>|'|"|'|{|})");
67
68         replacementMapDecode = new HashMap();
69
70         replacementMapDecode.put("&", "&");
71         replacementMapDecode.put(""", "\"");
72         replacementMapDecode.put(""", "\"");
73         replacementMapDecode.put("'", "'");
74         replacementMapDecode.put("'", "'");
75         replacementMapDecode.put("&lt;", "<");
76         replacementMapDecode.put("&gt;", ">");
77         replacementMapDecode.put("&#123;", "{");
78         replacementMapDecode.put("&#125;", "}");
79
80         patternEncode = Pattern.compile("[&\"'<>{}]");
81
82         replacementMapEncode = new HashMap();
83
84         replacementMapEncode.put("&", "&amp;");
85         replacementMapEncode.put("\"", "&quot;");
86         replacementMapEncode.put("'", "&#039;");
87         replacementMapEncode.put("<", "&lt;");
88         replacementMapEncode.put(">", "&gt;");
89         replacementMapEncode.put("{", "&#123;");
90         replacementMapEncode.put("}", "&#125;");
91     }
92
93     /** decode tag escapes */
94
95     public static String JavaDoc decode(String JavaDoc string)
96     {
97         return StringUtil.applyPattern(string, patternDecode, replacementMapDecode);
98     }
99
100     /** encode tag characters */
101
102     public static String JavaDoc encode(String JavaDoc string)
103     {
104         return encode(string, null);
105     }
106
107     /** encode tag characters, with specified pattern */
108
109     public static String JavaDoc encode(String JavaDoc string, Pattern pattern)
110     {
111         if (pattern == null)
112         {
113             pattern = patternEncode;
114         }
115
116         return StringUtil.applyPattern(string, pattern, replacementMapEncode);
117     }
118
119     /** create a Source from an Object */
120
121     public static final Source createSource(Object JavaDoc object) throws Exception JavaDoc
122     {
123         Source source = null;
124
125         if (object instanceof Node)
126         {
127             source = new DOMSource((Node)object);
128         }
129         else if (object instanceof String JavaDoc)
130         {
131             source = new StreamSource(new StringReader(object.toString()));
132         }
133         else if (object instanceof InputSource)
134         {
135             source = new SAXSource((InputSource)object);
136         }
137         else if (object instanceof InputStream)
138         {
139             source = new StreamSource((InputStream)object);
140         }
141         else if (object instanceof Reader)
142         {
143             source = new StreamSource((Reader)object);
144         }
145         else if (object instanceof URL)
146         {
147             source = new StreamSource(((URL)object).toString());
148         }
149         
150         return source;
151     }
152
153     /** outputs Source */
154
155     public static final String JavaDoc output(Source source, NestedMap controlMap) throws Exception JavaDoc
156     {
157         if (source != null)
158         {
159             Transformer transformer = TransformerFactory.newInstance().newTransformer();
160         
161             if (controlMap != null)
162             {
163                 Iterator iterator = controlMap.entrySet().iterator();
164
165                 while (iterator.hasNext())
166                 {
167                     Map.Entry entry = (Map.Entry)iterator.next();
168
169                     transformer.setOutputProperty(entry.getKey().toString(), entry.getValue().toString());
170                 }
171             }
172             
173             StringWriter writer = new StringWriter();
174             Result result = new StreamResult(writer);
175             
176             transformer.transform(source, result);
177
178             return writer.toString();
179         }
180         else
181         {
182             return null;
183         }
184     }
185
186     /** parses document according to control map */
187
188     public static final Document parse(Object JavaDoc object, Map controlMap) throws Exception JavaDoc
189     {
190         Document document = null;
191
192         if (object != null)
193         {
194             DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
195
196             if (controlMap != null)
197             {
198                 BeanUtil.fill(documentBuilderFactory, controlMap);
199             }
200             else
201             {
202                 documentBuilderFactory.setNamespaceAware(true);
203                 documentBuilderFactory.setIgnoringComments(true);
204                 documentBuilderFactory.setIgnoringElementContentWhitespace(true);
205                 documentBuilderFactory.setExpandEntityReferences(true);
206                 documentBuilderFactory.setCoalescing(true);
207                 documentBuilderFactory.setValidating(false);
208             }
209
210             DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
211                 
212             Reader reader;
213
214             if (object instanceof Reader)
215             {
216                 reader = (Reader)object;
217             }
218             else
219             {
220                 reader = new StringReader(object.toString());
221             }
222
223             document = documentBuilder.parse(new InputSource(reader));
224         }
225
226         return document;
227     }
228
229     private static Map getParseHtmlMap(Object JavaDoc object)
230     {
231         Map map = null;
232
233         if (object != null)
234         {
235             if (object instanceof Map)
236             {
237                 map = (Map)object;
238             }
239             else
240             {
241                 List list = TypeUtil.isStringList(object, ',', '\\');
242
243                 if ((list != null) && (list.size() > 0))
244                 {
245                     map = new HashMap();
246                     
247                     Iterator iterator = list.iterator();
248                     
249                     while (iterator.hasNext())
250                     {
251                         map.put(iterator.next().toString().toLowerCase(), Boolean.TRUE);
252                     }
253                 }
254             }
255         }
256
257         return map;
258     }
259
260     private static int getParseHtmlStrategy(String JavaDoc strategyName)
261     {
262         int strategy = com.micronova.util.cc.html.Parser.STRATEGY_SINGLE;
263
264         if ("data".equals(strategyName))
265         {
266             strategy = com.micronova.util.cc.html.Parser.STRATEGY_DATA;
267         }
268         else if ("none".equals(strategyName))
269         {
270             strategy = com.micronova.util.cc.html.Parser.STRATEGY_NONE;
271         }
272         else if ("single".equals(strategyName))
273         {
274             strategy = com.micronova.util.cc.html.Parser.STRATEGY_SINGLE;
275         }
276
277         return strategy;
278     }
279
280     public static Document parseHtml(Object JavaDoc object, NestedMap controlMap) throws Exception JavaDoc
281     {
282         Document document = null;
283         Reader reader = null;
284
285         try
286         {
287             String JavaDoc prefix = controlMap.getString("prefix", "");
288             int strategy = getParseHtmlStrategy(controlMap.getString("strategy"));
289             String JavaDoc rootName = controlMap.getString("rootName", "root");
290             Map exclude = getParseHtmlMap(controlMap.get("exclude"));
291             Map include = getParseHtmlMap(controlMap.get("include"));
292
293             if (object instanceof Reader)
294             {
295                 reader = (Reader)object;
296             }
297             else
298             {
299                 reader = new StringReader(object.toString());
300             }
301
302             com.micronova.util.cc.html.Parser parser = new com.micronova.util.cc.html.Parser(reader);
303           
304             document = parser.buildDocument(prefix, strategy, rootName, exclude, include);
305         }
306         catch (Exception JavaDoc e)
307         {
308             try
309             {
310                 reader.close();
311             }
312             catch (Exception JavaDoc ee)
313             {
314             }
315
316             throw e;
317         }
318
319         return document;
320     }
321
322     public static final String JavaDoc[] NODETYPE =
323     {
324         null,
325         "Element",
326         "Attr",
327         "Text",
328         "CDATASection",
329         "EntityReference",
330         "Entity",
331         "ProcessingInstruction",
332         "Comment",
333         "Document",
334         "DocumentType",
335         "DocumentFragment",
336         "Notation"
337     };
338
339     public static final Object JavaDoc encodeNodeMap(Node node)
340     {
341         if (node != null)
342         {
343             short type = node.getNodeType();
344            
345             if (type == Node.TEXT_NODE)
346             {
347                 return node.getNodeValue();
348             }
349             else
350             {
351                 NestedMap map = new NestedMap();
352                 map.put("type", NODETYPE[node.getNodeType()]);
353                 map.put("name", node.getNodeName());
354                 map.put("value", node.getNodeValue());
355
356                 if (node.hasAttributes())
357                 {
358                     NamedNodeMap attributes = node.getAttributes();
359
360                     NestedMap attributeMap = new NestedMap();
361
362                     int length = attributes.getLength();
363                     
364                     for (int i = 0; i < length; i ++)
365                     {
366                         Attr attr = (Attr)attributes.item(i);
367
368                         attributeMap.put(attr.getName(), attr.getValue());
369                     }
370                     
371                     map.put("attributes", attributeMap);
372                 }
373
374                 if (node.hasChildNodes())
375                 {
376                     NodeList children = node.getChildNodes();
377                     int length = children.getLength();
378                 
379                     List list = map.getSubList();
380                     
381                     for (int i = 0; i < length; i ++)
382                     {
383                         Object JavaDoc child = encodeNodeMap(children.item(i));
384                         list.add(child);
385                     }
386                 }
387
388                 return map;
389             }
390         }
391
392         return null;
393     }
394
395     protected static final Node _decodeNodeMap(Document document, Object JavaDoc object)
396     {
397         Node node = null;
398
399         if (object != null)
400         {
401             if (object instanceof Node)
402             {
403                 node = (Node)object;
404             }
405             else if (object instanceof String JavaDoc)
406             {
407                 node = document.createTextNode(object.toString());
408             }
409             else if (object instanceof Map)
410             {
411                 NestedMap map = TypeUtil.isNestedMap(object);
412
413                 String JavaDoc type = map.getString("type", "Element");
414
415                 if ("Element".equals(type))
416                 {
417                     Element element = document.createElement(map.getString("name"));
418                     Map attributes = map.getSubMap("attributes");
419                     
420                     Iterator iterator = attributes.entrySet().iterator();
421                     
422                     while (iterator.hasNext())
423                     {
424                         Map.Entry entry = (Map.Entry)iterator.next();
425                         element.setAttribute(entry.getKey().toString(), entry.getValue().toString());
426                     }
427
428                     node = element;
429                 }
430                 else if ("Text".equals(type))
431                 {
432                     node = document.createTextNode(map.getString("value"));
433                 }
434                 else if ("CDATASection".equals(type))
435                 {
436                     node = document.createCDATASection(map.getString("value"));
437                 }
438                 else if ("Comment".equals(type))
439                 {
440                     node = document.createComment(map.getString("value"));
441                 }
442                 else if ("Document".equals(type))
443                 {
444                     node = document;
445                 }
446                 else if ("DocumentFragment".equals(type))
447                 {
448                     node = document.createDocumentFragment();
449                 }
450                 else if ("EntityReference".equals(type))
451                 {
452                     node = document.createEntityReference(map.getString("name"));
453                 }
454                 else if ("ProcessingInstruction".equals(type))
455                 {
456                     node = document.createProcessingInstruction(map.getString("name"), map.getString("value"));
457                 }
458                 else if ("Attr".equals(type))
459                 {
460                     Attr attr = document.createAttribute(map.getString("name"));
461                     attr.setValue(map.getString("value"));
462
463                     node = attr;
464                 }
465
466                 if (node != null)
467                 {
468                     List children = map.getSubList();
469                 
470                     Iterator iterator = children.iterator();
471                     
472                     while (iterator.hasNext())
473                     {
474                         node.appendChild(_decodeNodeMap(document, iterator.next()));
475                     }
476                 }
477             }
478         }
479
480         return node;
481     }
482
483     public static final Node decodeNodeMap(Object JavaDoc object, Object JavaDoc controlSpec) throws Exception JavaDoc
484     {
485         Document document = null;
486
487         if (controlSpec instanceof Document)
488         {
489             document = (Document)controlSpec;
490         }
491         else
492         {
493             DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
494
495             if (controlSpec != null)
496             {
497                 BeanUtil.fill(documentBuilderFactory, TypeUtil.isNestedMap(controlSpec));
498             }
499
500             DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
501             document = documentBuilder.newDocument();
502         }
503
504         return _decodeNodeMap(document, object);
505     }
506
507     public static final Node decodeNodeMap(Object JavaDoc object) throws Exception JavaDoc
508     {
509         return decodeNodeMap(object, null);
510     }
511
512     /** encode NestedMap into XML attribute list */
513
514     public static final StringBuffer JavaDoc encodeAttrList(StringBuffer JavaDoc buffer, NestedMap map)
515     {
516         Map params = (Map)map.get("__param");
517         
518         Iterator iterator = params.entrySet().iterator();
519         String JavaDoc separator = "";
520         
521         while (iterator.hasNext())
522         {
523             Map.Entry entry = (Map.Entry)iterator.next();
524
525             buffer.append(separator);
526             buffer.append(XMLMap.encodeName(entry.getKey().toString()));
527             buffer.append("=\"");
528             buffer.append(encode(entry.getValue().toString()));
529             buffer.append("\"");
530             separator = " ";
531         }
532
533         return buffer;
534     }
535
536     public static final String JavaDoc encodeAttrList(NestedMap map)
537     {
538         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
539         buffer = encodeAttrList(buffer, map);
540         return buffer.toString();
541     }
542 }
543
Popular Tags