/*
 * $Header: /home/cvspublic/jakarta-slide/testsuite/testsuite/junit/src/org/apache/slide/testsuite/testtools/tutil/TProcessorTask.java,v 1.11 2005/01/10 18:26:40 luetzkendorf Exp $
 * $Revision: 1.11 $
 * $Date: 2005/01/10 18:26:40 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2002 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", "Slide", 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/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */

package org.apache.slide.testsuite.testtools.tutil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.slide.testsuite.testtools.tprocessor.TProcessors;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.jdom.JDOMException;

public class TProcessorTask extends Task {
    private File config;
    private File result;
    private String urlEncoding;
    private String tracingRequest;
    private final List filesets;
    private boolean printProperties = false;
    
    public TProcessorTask() {
        super();
        
        filesets = new ArrayList();
    }
    
    public void addFileset(FileSet set) {
        filesets.add(set);
    }
    
    public void setConfig(File config) {
        if (!config.isFile()) {
            throw new BuildException("no such file: " + config);
        }
        this.config = config;
    }
    
    public void setUrlEncoding(String urlEncoding) {
        this.urlEncoding = urlEncoding;
    }
    public void setTracingRequest(String tracingRequest) {
        this.tracingRequest = tracingRequest;
    }
    public void setResult(File result) {
        this.result = result;
    }
    public void setPrintProperties(boolean value) {
        this.printProperties = value;
    }
    
    private static void check(Object attr, String name) throws BuildException {
        if (attr == null) {
            throw new BuildException("'" + name + "' attribute not set");
        }
    }
    public void execute() throws BuildException {
        int i;
        PrintStream out;
        int okCount;
        String host;
        String port;
        String user;
        String password;
        FileSet fs;
        String[] files;
        File dir;
        int testCount;
        
        log("--------------------------------------------------------");
        log("Properties:");
        log("- Server URL...............: "+"http://"+getProperty("host")+":"+getProperty("port")+"/"+getProperty("globalVariableServerName"));
        log("- Root folder..............: "+getProperty("globalVariableCollection"));
        log("- User.....................: "+getProperty("globalVariableUserPath"));
        log("- Users (# of threads).....: "+getProperty("globalVariableUsers"));
        log("- Iterations (per thread)..: "+getProperty("globalVariableIterationCount"));
        log("--------------------------------------------------------");
                
        host = getProperty("host");
        port = getProperty("port");
        user = getProperty("user");
        password = getProperty("password");
        check(config, "config");
        check(result, "result");
        check(host, "host");
        check(port, "port");
        check(user, "user");
        check(password, "password");
        check(urlEncoding, "urlEncoding");
        check(tracingRequest, "tracingRequest");
        
        log("Writing results to " + result);
        
        try {
            out = new PrintStream(new FileOutputStream(result));
        } catch (IOException e) {
            throw new BuildException("cannot create result file " + result, e);
        }
        
        try {
            out.println("<test>");
            if (this.printProperties) {
                out.println("  <properties>");
                for(Iterator it = getProject().getProperties().entrySet().iterator(); it.hasNext();) {
                    Map.Entry e = (Map.Entry)it.next();
                    out.print("    <property name=\"");
                    out.print(e.getKey());
                    out.print("\" value=\"");
                    out.print(xmlEscape((String)e.getValue()));
                    out.println("\"/>");
                }
                out.println("  </properties>");
            }
            okCount = 0;
            testCount = 0;
            for (i = 0; i < filesets.size(); i++) {
                fs = (FileSet) filesets.get(i);
                dir = fs.getDir(getProject());
                log("Entering directory: " + dir);
                files = fs.getDirectoryScanner(getProject()).getIncludedFiles();
                testCount += files.length;
                okCount += execute(dir, files, out, host, port, user, password);
                log("Leaving directory: " + dir);
            }
            out.println("</test>");
        } finally {
            out.close();
        }
        log((testCount - okCount) + " failures, " + okCount + "/" + testCount + " ok");
    }
    
    private int execute(File dir, String[] files, PrintStream out, String host, String port, String user, String password) {
        int okCount;
        int i;
        String file;
        TProcessors tp;
        boolean ok;
        
        okCount = 0;
        for (i = 0; i < files.length; i++) {
            try {
                tp = new TProcessors(config, host, port, user, password, urlEncoding, tracingRequest, createProperties());
            } catch (JDOMException e) {
                throw new BuildException("initializing tprocessor failed", e);
            } catch (IOException e) {
                throw new BuildException("initializing tprocessor failed", e);
            }
            file = files[i];
            log((i + 1) + "/" + files.length + ": " + file);
            try {
                ok = tp.executeTestCase(new File(dir, file), out);
            } catch (Exception e) {
                throw new BuildException("execution failed: " + file, e);
            }
            if (ok) {
                okCount++;
            } else {
                log("    FAILED");
            }
        }
        return okCount;
    }
    
    private static final String PREFIX = "xdav.";
    
    private Properties createProperties() {
        Properties props;
        Iterator iter;
        Map.Entry entry;
        String key;
        
        props = new Properties();
        iter = getProject().getProperties().entrySet().iterator();
        while (iter.hasNext()) {
            entry = (Map.Entry) iter.next();
            key = (String) entry.getKey();
            if (key.startsWith(PREFIX)) {
                props.put(key, entry.getValue());
            }
        }
        return props;
    }
    
    private String getProperty(String name) throws BuildException {
        String value;
        String fullName;
        
        fullName = PREFIX + name;
        value = getProject().getProperty(fullName);
        if (value == null) {
            throw new BuildException("mandatory property not found: " + fullName);
        }
        return value;
    }
    
    private static String xmlEscape(String text) {
        StringBuffer b = new  StringBuffer(text.length() * 2);
        for(int i = 0, l = text.length(); i < l; i++) {
            char c = text.charAt(i);
            switch(c) {
                case '&':
                    b.append("&amp;");
                    break;
                case '"':
                    b.append("&quot;");
                    break;
                case '<':
                    b.append("&lt;");
                    break;
                default:
                    b.append(c);
            }
        }
        return b.toString();
    }
}


