View Javadoc

1   /*
2    * $Id: IsXmlFilter.java 12273 2008-07-10 13:25:32Z tcarlson $
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.module.xml.filters;
12  
13  import org.mule.api.MuleMessage;
14  import org.mule.api.routing.filter.Filter;
15  import org.mule.module.xml.util.XMLUtils;
16  
17  import javax.xml.stream.XMLInputFactory;
18  import javax.xml.stream.XMLStreamConstants;
19  import javax.xml.stream.XMLStreamException;
20  import javax.xml.stream.XMLStreamReader;
21  
22  /**
23   * <code>IsXmlFilter</code> accepts a String or byte[] if its contents are valid
24   * (well-formed) XML.
25   */
26  // @ThreadSafe
27  public class IsXmlFilter implements Filter
28  {
29      private final XMLInputFactory factory = XMLInputFactory.newInstance();
30  
31      // TODO: add validation against a DTD, see MULE-1055
32  
33      public IsXmlFilter()
34      {
35          super();
36      }
37  
38      public boolean accept(MuleMessage obj)
39      {
40          return accept(obj.getPayload());
41      }
42  
43      private boolean accept(Object obj)
44      {
45          XMLStreamReader parser = null;
46          try
47          {
48              parser = XMLUtils.toXMLStreamReader(factory, obj);
49              if (parser == null)
50              {
51                  return false;
52              }
53  
54              while (parser.next() != XMLStreamConstants.END_DOCUMENT)
55              {
56                  // meep meep!
57              }
58  
59              return true;
60          }
61          catch (XMLStreamException ex)
62          {
63              return false;
64          }
65          finally
66          {
67              if (parser != null)
68              {
69                  try
70                  {
71                      parser.close();
72                  }
73                  catch (XMLStreamException ignored)
74                  {
75                      // bummer
76                  }
77              }
78          }
79      }
80  
81  }