package org.activemq.filter;

import java.io.ByteArrayInputStream;
import java.io.StringReader;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

public class JAXPXPathEvaluator implements XPathExpression.XPathEvaluator {
    
    private static final XPathFactory factory = XPathFactory.newInstance();
    private javax.xml.xpath.XPathExpression expression;
    
    public JAXPXPathEvaluator(String xpathExpression) {
        try {
            XPath xpath = factory.newXPath();
            expression = xpath.compile(xpathExpression);            
        } catch (XPathExpressionException e) {
            throw new RuntimeException("Invalid XPath expression: "+xpathExpression);
        }
    }
    
    public boolean evaluate(Message message) throws JMSException {
        if( message instanceof TextMessage ) {
            String text = ((TextMessage)message).getText();
            return evaluate(text);                
        } else if ( message instanceof BytesMessage ) {
            BytesMessage bm = (BytesMessage) message;
            byte data[] = new byte[(int) bm.getBodyLength()];
            bm.readBytes(data);
            return evaluate(data);
        }            
        return false;
    }

    private boolean evaluate(byte[] data) {
        try {
            InputSource inputSource = new InputSource(new ByteArrayInputStream(data));
            return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue();
        } catch (XPathExpressionException e) {
            return false;
        }
    }

    private boolean evaluate(String text) {
        try {
            InputSource inputSource = new InputSource(new StringReader(text));
            return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue();
        } catch (XPathExpressionException e) {
            return false;
        }
    }
}
