package com;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.w3c.dom.Document;

public class XPathProcessor extends Task {

	private String xPath = null;

	private File xmlFile = null;

	private String valuePropertyName = null;
	
	
	public String getXPath() {
		return xPath;
	}


	public void setXPath(String path) {
		xPath = path;
	}


	public File getXmlFile() {
		return xmlFile;
	}


	public void setXmlFile(File xmlFile) {
		this.xmlFile = xmlFile;
	}


	public String getValuePropertyName() {
		return valuePropertyName;
	}


	public void setValuePropertyName(String valuePropertyName) {
		this.valuePropertyName = valuePropertyName;
	}


	public void execute() {

		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(this.xmlFile);
			doc.getDocumentElement().normalize();
			//log("Root element "	+ doc.getDocumentElement().getNodeName());
			XPath xpath = XPathFactory.newInstance().newXPath();
			String value = (String) xpath.evaluate(this.xPath, doc, XPathConstants.STRING);
			this.getProject().setProperty(this.valuePropertyName, value != null ? value : "");
			
		} catch (Exception e) {
			log(e.getMessage());
			throw new BuildException(e);
		}
	}
}