/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
package org.apache.tools.ant.taskdefs.optional.xpath;

import java.util.Vector;
import java.util.Enumeration;

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.File;

import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.traversal.NodeIterator;

import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;

import org.apache.xpath.XPathAPI;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.Project;

/**
 * Very basic XPath Ant task that does a simple replace on a XML file
 * based on a XPath expression.<p>
 * Based on the idea expressed by Scott Sanders and Jeff Martin on
 * alexandria-dev@jakarta.apache.org
 * 
 * <pre>
 * &lt;xpath file=&quot;input.xml&quot; tofile&quot;output.xml&quot;&gt;
 *   &lt;apply select=&quot;/some/thing/@here&quot; value=&quot;replace-value&quot;/&gt;
 * &lt;/xpath&gt;
 * </pre>
 * Will replace the content of the attribute
 *
 * @author <a href="sbailliez@imediation.com">Stephane Bailliez</a>
 */
public class XPath extends Task {
    
    /** the xml file to be processed */
    protected File file;
    
    /** the XPath expression */
    protected String select;
    
    /** the value that will replace the content of the XPath expression */
    protected String value;

    /** the XML file to write the results to */
    protected File toFile;

    protected Vector xpaths = new Vector();
    
    /**
     * set the XML file to process
     */
    public void setFile(File file){
        this.file = file;
    }
    
    /**
     * set the XML file to write the results to.
     */
    public void setToFile(File file){
        this.toFile = file;
    }
    
    /**
     * set the XPath expression to evaluate.
     * Shortcut to avoid an apply element
     */
    public void setSelect(String value){
        this.select = value;
    }
    
    /**
     * set the value to replace node values selected by the XPath expression
     * This is a shortcut to avoid an apply element
     */
    public void setValue(String value){
        this.value = value;
    }

    /**
     * Add an apply element to process.
     */
    public void addApply(Apply apply){
        xpaths.add(apply);
    }

    /** little check for invalid configuration */
    protected void setup() throws BuildException {
        if (file == null) {
            throw new BuildException("Missing XML file to process ('file' attribute)");
        }
        if (select == null && value != null){
            throw new BuildException("Missing XPath expression ('expr' attribute)");
        }
        if (value == null && select != null){
            throw new BuildException("Missing replace value ('value' attribute)");
        }
        // identity transformation
        if (toFile == null){
            log("No destination file given. Modification will be done on source file", Project.MSG_VERBOSE);
            toFile = file;
        }
        
        // as a convenience we give a select and value attribute when there
        // is only a single replace. Set it in first position.
        if (select != null && value != null){
            Apply apply = new Apply();
            apply.setSelect(select);
            apply.setValue(value);
            xpaths.insertElementAt(apply, 0);
        }
    }

    // do the whole stuff    
    public void execute() throws BuildException {
        setup();
        try {
            // parse the XML file as a DOM
            FileInputStream fis = new FileInputStream(file);
            InputSource in = new InputSource(fis);
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            Document doc = dfactory.newDocumentBuilder().parse(in);
            fis.close();
            
            Enumeration enum = xpaths.elements();
            while(enum.hasMoreElements()){
                Apply apply = (Apply)enum.nextElement();
                NodeIterator nl = XPathAPI.selectNodeIterator(doc, apply.getSelect());
                Node n;
                while ((n = nl.nextNode())!= null) {
                    n.setNodeValue(apply.getValue());
                }
            }
            
            // Set up an identity transformer to use as serializer.
            Transformer serializer = TransformerFactory.newInstance().newTransformer();
            //serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            FileOutputStream fos = new FileOutputStream( toFile );
            StreamResult sresult = new StreamResult( fos );
            sresult.setSystemId( toFile );
            serializer.transform( new DOMSource(doc), sresult );
            fos.close();
        } catch (Exception e){
            throw new BuildException(e);
        }
    }
    
    public static class Apply {
        protected String select;
        
        protected String value;
        
        public Apply(){}
        
        public void setSelect(String select){
            this.select = select;
        }
        public void setValue(String value){
            this.value = value;
        }
        public String getSelect(){
            return this.select;
        }
        public String getValue(){
            return this.value;
        }
    }
}