View Javadoc

1   /*
2    * $Id: IsXmlFilter.java 7976 2007-08-21 14:26:13Z dirk.olmes $
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 CPAL v1.0
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 org.mule.umo.UMOFilter;
14  import org.mule.umo.UMOMessage;
15  
16  import java.io.ByteArrayInputStream;
17  import java.io.StringReader;
18  
19  import javax.xml.stream.XMLInputFactory;
20  import javax.xml.stream.XMLStreamConstants;
21  import javax.xml.stream.XMLStreamException;
22  import javax.xml.stream.XMLStreamReader;
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 obj)
46      {
47          XMLStreamReader parser = null;
48  
49          try
50          {
51              if (obj instanceof String)
52              {
53                  parser = factory.createXMLStreamReader(new StringReader((String)obj));
54              }
55              else if (obj instanceof byte[])
56              {
57                  parser = factory.createXMLStreamReader(new ByteArrayInputStream((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  }