KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > routing > filters > xml > IsXmlFilter


1 /*
2  * $Id: IsXmlFilter.java 3937 2006-11-20 16:04:25Z lajos $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.routing.filters.xml;
12
13 import java.io.ByteArrayInputStream JavaDoc;
14 import java.io.StringReader JavaDoc;
15
16 import javax.xml.stream.XMLInputFactory;
17 import javax.xml.stream.XMLStreamConstants;
18 import javax.xml.stream.XMLStreamException;
19 import javax.xml.stream.XMLStreamReader;
20
21 import org.mule.umo.UMOFilter;
22 import org.mule.umo.UMOMessage;
23
24 /**
25  * <code>IsXmlFilter</code> accepts a String or byte[] if its contents are valid
26  * (well-formed) XML.
27  */

28 // @ThreadSafe
29
public class IsXmlFilter implements UMOFilter
30 {
31     private final XMLInputFactory factory = XMLInputFactory.newInstance();
32
33     // TODO: add validation against a DTD, see MULE-1055
34

35     public IsXmlFilter()
36     {
37         super();
38     }
39
40     public boolean accept(UMOMessage obj)
41     {
42         return accept(obj.getPayload());
43     }
44
45     private boolean accept(Object JavaDoc obj)
46     {
47         XMLStreamReader parser = null;
48
49         try
50         {
51             if (obj instanceof String JavaDoc)
52             {
53                 parser = factory.createXMLStreamReader(new StringReader JavaDoc((String JavaDoc)obj));
54             }
55             else if (obj instanceof byte[])
56             {
57                 parser = factory.createXMLStreamReader(new ByteArrayInputStream JavaDoc((byte[])obj));
58             }
59             else
60             {
61                 // neither String nor byte[]
62
return false;
63             }
64
65             while (parser.next() != XMLStreamConstants.END_DOCUMENT)
66             {
67                 // meep meep!
68
}
69
70             return true;
71         }
72         catch (XMLStreamException ex)
73         {
74             return false;
75         }
76         finally
77         {
78             if (parser != null)
79             {
80                 try
81                 {
82                     parser.close();
83                 }
84                 catch (XMLStreamException ignored)
85                 {
86                     // bummer
87
}
88             }
89         }
90     }
91
92 }
93
Popular Tags