/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 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", "Ant", 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;

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

import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.Vector;

/**
 * Wait for an external event to occur.
 *
 * Wait for an external process to start or to complete some task. This is useful with the
 * <code>parallel</code> task to syncronize the execution of tests with server startup.
 *
 * Note that if multiple events are specified, the task will wait until <b>all</b> of the specified
 * events occur. Once an individual event has passed, it will not be tested again.
 *
 * The following attributes can be specified on a waitfor task:
 * <li>maxwait - maximum length of time to wait before giving up</li>
 * <li>checkevery - amount of time to sleep between each check</li>
 * The time value can include a suffix of "ms", "s", "m", "h" to indicate that the value
 * is in milliseconds, seconds, minutes or hours. The default is milliseconds.
 *
 * The sub-elements of this task describe what events should terminate the waiting period.
 * Possible sub-elements are:
 * <li>file - wait until the specified file exists</li>
 * <li>http - wait until the specified url is available</li>
 * <li>socket - wait until something listens on specified server and port</li>
 *
 * @author <a href="mailto:denis@network365.com">Denis Hennessy</a>
 */

public class WaitFor extends org.apache.tools.ant.Task {
    private long maxWaitMillis = 1000 * 60 * 3;     // default max wait time
    private long checkEveryMillis = 500;
    private Vector events = new Vector();

    protected interface WaitForEvent {
        public boolean isReady() throws BuildException;
    }

    /**
     * Event to wait for the existance of a file. Its attribute(s) are:
     *   path - the pathname of the file.
     */
    protected class WaitForFile implements WaitForEvent {
        boolean hasPassed = false;
        String path = null;

        public void setPath(String path) {
            this.path = path;
        }

        public boolean isReady() {
            if (hasPassed) {
                return true;
            }
            if (path == null) {
                throw new BuildException("No path specified in File task");
            }
            log("Checking for file at " + path, Project.MSG_VERBOSE);

            File file = new File(path);
            if (file.exists()) {
                hasPassed = true;
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * Event to wait for a HTTP request to succeed. Its attribute(s) are:
     *   url - the URL of the request.
     */
    protected class WaitForHttp implements WaitForEvent {
        boolean hasPassed = false;
        String spec = null;

        public void setUrl(String url) {
            spec = url;
        }

        public boolean isReady() throws BuildException {
            if (hasPassed) {
                return true;
            }
            if (spec == null) {
                throw new BuildException("No url specified in HTTP task");
            }
            log("Checking for " + spec, Project.MSG_VERBOSE);
            try {
                URL url = new URL(spec);
                try {
                    URLConnection conn = url.openConnection();
                    if (conn instanceof HttpURLConnection) {
                        HttpURLConnection http = (HttpURLConnection) conn;
                        int code = http.getResponseCode();
                        log("Result code for " + spec + " was " + code, Project.MSG_VERBOSE);
                        if (code > 0 && code < 500) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                } catch (java.io.IOException e) {
                    return false;
                }
            } catch (MalformedURLException e) {
                throw new BuildException("Badly formed URL: " + spec, e);
            }
            hasPassed = true;
            return true;
        }
    }

    /**
     * Event to wait for a TCP/IP socket to have a listener. Its attribute(s) are:
     *   server - the name of the server.
     *   port - the port number of the socket.
     */
    protected class WaitForSocket implements WaitForEvent {
        boolean hasPassed = false;
        String server = null;
        int port = 0;

        public void setServer(String server) {
            this.server = server;
        }

        public void setPort(int port) {
            this.port = port;
        }

        public boolean isReady() throws BuildException {
            if (hasPassed) {
                return true;
            }
            if (server == null) {
                throw new BuildException("No server specified in Socket task");
            }
            if (port == 0) {
                throw new BuildException("No port specified in Socket task");
            }
            log("Checking for listener at " + server + ":" + port, Project.MSG_VERBOSE);
            try {
                Socket socket = new Socket(server, port);
            } catch (IOException e) {
                return false;
            }
            hasPassed = true;
            return true;
        }
    }

    /**
     * Set the maximum length of time to wait
     */
    public void setMaxWait(String time) {
        maxWaitMillis = parseTime(time);
    }

    /**
     * Set the time between each check
     */
    public void setCheckEvery(String time) {
        checkEveryMillis = parseTime(time);
    }

    /**
     * Create a File event to wait on.
     */
    public WaitForFile createFile() {
        WaitForFile ev = new WaitForFile();
        events.add(ev);
        return ev;
    }

    /**
     * Create a HTTP event to wait on.
     */
    public WaitForHttp createHttp() {
        WaitForHttp ev = new WaitForHttp();
        events.add(ev);
        return ev;
    }

    /**
     * Create a Socket event to wait on.
     */
    public WaitForSocket createSocket() {
        WaitForSocket ev = new WaitForSocket();
        events.add(ev);
        return ev;
    }

    /**
     * Check repeatedly for te specified conditions until they all become true or the timeout expires.
     */
    public void execute() throws BuildException {
        // An empty list is not an error - nothing to wait for
        if (events.isEmpty()) {
            log("No events specified to wait for.");
            return;
        }

        long start = System.currentTimeMillis();
        long end = start + maxWaitMillis;

        while (System.currentTimeMillis() < end) {
            boolean allPassed = true;
            for (int i = 0; i < events.size(); i++) {
                WaitForEvent ev = (WaitForEvent) events.elementAt(i);
                if (!ev.isReady()) {
                    allPassed = false;
                }
            }
            if (allPassed) {
                return;
            }
            try {
                Thread.sleep(checkEveryMillis);
            } catch (InterruptedException e) {
            }
        }
        throw new BuildException("Task did not complete in time");
    }

    /**
     * Parse a time in the format nnnnnxx where xx is a common time multiplier suffix.
     */
    protected long parseTime(String value) {
        int i = 0;
        for (i = 0; i < value.length(); i++) {
            char ch = value.charAt(i);
            if (ch < '0' || ch > '9') {
                break;
            }
        }
        if (i == 0) {
            throw new NumberFormatException();
        }
        String digits = value.substring(0, i);
        return Long.parseLong(digits) * getMultiplier(value.substring(i));
    }

    /**
     * Look for and decipher a multiplier suffix in the string.
     * @param value - a string with a series of digits followed by the scale suffix.
     */
    protected long getMultiplier(String value) {
        String lowercaseValue = value.toLowerCase();
        if (lowercaseValue.startsWith("ms")) {
            return 1;
        }
        if (lowercaseValue.startsWith("s")) {
            return 1000;
        }
        if (lowercaseValue.startsWith("m")) {
            return 1000 * 60;
        }
        if (lowercaseValue.startsWith("h")) {
            return 1000 * 60 * 60;
        }
        return 1;
    }
}

