1 18 19 package org.apache.activemq.filter; 20 21 import java.io.StringReader ; 22 23 import javax.jms.BytesMessage ; 24 import javax.jms.JMSException ; 25 import javax.jms.TextMessage ; 26 import javax.xml.parsers.DocumentBuilder ; 27 import javax.xml.parsers.DocumentBuilderFactory ; 28 29 import org.apache.activemq.command.Message; 30 import org.apache.activemq.util.ByteArrayInputStream; 31 import org.apache.xpath.CachedXPathAPI; 32 import org.w3c.dom.Document ; 33 import org.w3c.dom.traversal.NodeIterator; 34 import org.xml.sax.InputSource ; 35 36 public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { 37 38 private final String xpath; 39 40 public XalanXPathEvaluator(String xpath) { 41 this.xpath = xpath; 42 } 43 44 public boolean evaluate(Message m) throws JMSException { 45 if( m instanceof TextMessage ) { 46 String text = ((TextMessage )m).getText(); 47 return evaluate(text); 48 } else if ( m instanceof BytesMessage ) { 49 BytesMessage bm = (BytesMessage ) m; 50 byte data[] = new byte[(int) bm.getBodyLength()]; 51 bm.readBytes(data); 52 return evaluate(data); 53 } 54 return false; 55 } 56 57 private boolean evaluate(byte[] data) { 58 try { 59 60 InputSource inputSource = new InputSource (new ByteArrayInputStream(data)); 61 62 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 63 factory.setNamespaceAware(true); 64 DocumentBuilder dbuilder = factory.newDocumentBuilder(); 65 Document doc = dbuilder.parse(inputSource); 66 67 CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); 68 NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); 69 return iterator.nextNode()!=null; 70 71 } catch (Throwable e) { 72 return false; 73 } 74 } 75 76 private boolean evaluate(String text) { 77 try { 78 InputSource inputSource = new InputSource (new StringReader (text)); 79 80 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 81 factory.setNamespaceAware(true); 82 DocumentBuilder dbuilder = factory.newDocumentBuilder(); 83 Document doc = dbuilder.parse(inputSource); 84 85 CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); 88 NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); 89 return iterator.nextNode()!=null; 90 } catch (Throwable e) { 91 return false; 92 } 93 } 94 } 95 | Popular Tags |