View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.xml.filters;
8   
9   import org.mule.api.MuleMessage;
10  import org.mule.api.routing.filter.Filter;
11  import org.mule.module.xml.util.XMLUtils;
12  
13  import javax.xml.stream.XMLInputFactory;
14  import javax.xml.stream.XMLStreamConstants;
15  import javax.xml.stream.XMLStreamException;
16  import javax.xml.stream.XMLStreamReader;
17  
18  /**
19   * <code>IsXmlFilter</code> accepts a String or byte[] if its contents are valid
20   * (well-formed) XML.
21   */
22  // @ThreadSafe
23  public class IsXmlFilter implements Filter
24  {
25      private final XMLInputFactory factory = XMLInputFactory.newInstance();
26  
27      // TODO: add validation against a DTD, see MULE-1055
28  
29      public IsXmlFilter()
30      {
31          super();
32      }
33  
34      public boolean accept(MuleMessage obj)
35      {
36          return accept(obj.getPayload());
37      }
38  
39      private boolean accept(Object obj)
40      {
41          XMLStreamReader parser = null;
42          try
43          {
44              parser = XMLUtils.toXMLStreamReader(factory, obj);
45              if (parser == null)
46              {
47                  return false;
48              }
49  
50              while (parser.next() != XMLStreamConstants.END_DOCUMENT)
51              {
52                  // meep meep!
53              }
54  
55              return true;
56          }
57          catch (XMLStreamException ex)
58          {
59              return false;
60          }
61          finally
62          {
63              if (parser != null)
64              {
65                  try
66                  {
67                      parser.close();
68                  }
69                  catch (XMLStreamException ignored)
70                  {
71                      // bummer
72                  }
73              }
74          }
75      }
76  
77  }