001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.activemq.filter; 018 019 import java.io.StringReader; 020 021 import javax.jms.BytesMessage; 022 import javax.jms.JMSException; 023 import javax.jms.TextMessage; 024 import javax.xml.xpath.XPath; 025 import javax.xml.xpath.XPathConstants; 026 import javax.xml.xpath.XPathExpressionException; 027 import javax.xml.xpath.XPathFactory; 028 029 import org.xml.sax.InputSource; 030 031 import org.apache.activemq.command.Message; 032 import org.apache.activemq.util.ByteArrayInputStream; 033 034 public class JAXPXPathEvaluator implements XPathExpression.XPathEvaluator { 035 036 private static final XPathFactory FACTORY = XPathFactory.newInstance(); 037 private javax.xml.xpath.XPathExpression expression; 038 039 public JAXPXPathEvaluator(String xpathExpression) { 040 try { 041 XPath xpath = FACTORY.newXPath(); 042 expression = xpath.compile(xpathExpression); 043 } catch (XPathExpressionException e) { 044 throw new RuntimeException("Invalid XPath expression: " + xpathExpression); 045 } 046 } 047 048 public boolean evaluate(Message message) throws JMSException { 049 if (message instanceof TextMessage) { 050 String text = ((TextMessage)message).getText(); 051 return evaluate(text); 052 } else if (message instanceof BytesMessage) { 053 BytesMessage bm = (BytesMessage)message; 054 byte data[] = new byte[(int)bm.getBodyLength()]; 055 bm.readBytes(data); 056 return evaluate(data); 057 } 058 return false; 059 } 060 061 private boolean evaluate(byte[] data) { 062 try { 063 InputSource inputSource = new InputSource(new ByteArrayInputStream(data)); 064 return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); 065 } catch (XPathExpressionException e) { 066 return false; 067 } 068 } 069 070 private boolean evaluate(String text) { 071 try { 072 InputSource inputSource = new InputSource(new StringReader(text)); 073 return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); 074 } catch (XPathExpressionException e) { 075 return false; 076 } 077 } 078 }