/*
 * Copyright (C) @year@ Vincent Massol
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package j2eeunit.ant;

import java.net.*;
import java.io.*;

import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;

/**
 * An Ant Task that does the following :
 * <ul>
 *   <li>create a java thread,</li>
 *   <li>start another Ant target in that thread. This target must be a
 *       blocking target that starts a web server/servlet engine,</li>
 *   <li>wait for that server to be started. This is done by continuously
 *       trying to call a URL.</li>
 * </ul>.
 */
public class StartServerTask extends Task implements Runnable
{
    /**
     * The URL that is continuously pinged to verify if the server is running.
     */
    private URL m_TestURL;

    /**
     * The Ant target name that will start the web server/servlet engine.
     */
    private String m_StartTarget;

    private String m_ThreadId;

    /**
     * Executes the task.
     */
    public void execute() throws BuildException
    {
        // Verify that a test URL has been specified
        if (m_TestURL == null) {
            throw new BuildException("A testURL attribute must be specified");
        }

        // Verify that a start target has been specified
        if (m_StartTarget == null) {
            throw new BuildException("A startTarget Ant target name must be specified");
        }

        // Call the target that starts the server, in another thread. The called
        // target must be blocking.
        Thread thread = new Thread(this);

        // Save the thread if we need to kill it later
        if (m_ThreadId == null) {
            // We assume there will be only one thread in use
            ThreadManager.getInstance().addThread("single", thread);
        } else {
            ThreadManager.getInstance().addThread(m_ThreadId, thread);
        }

        thread.start();

        // Continuously try calling the test URL until it succeeds
        while (true) {

            try {
                HttpURLConnection connection = (HttpURLConnection)m_TestURL.openConnection();
                connection.connect();
                connection.disconnect();
            } catch (IOException e) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ee) {
                    throw new BuildException("Interruption during sleep", ee);
                }
                continue;
            }

            break;
        }

        // Wait a few seconds more (just to be sure !)
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new BuildException("Interruption during sleep", e);
        }

        // We're done ... Ant will continue processing other tasks
    }

    /**
     * The thread that calls the Ant target that starts the web server/servlet
     * engine. Must be a blocking target.
     */
    public void run()
    {
        // Call the Ant target using the "antcall" task.
        CallTarget callee;
        callee = (CallTarget)project.createTask("antcall");
        callee.setOwningTarget(target);
        callee.setTaskName(getTaskName());
        callee.setLocation(location);

        callee.init();

        callee.setTarget(m_StartTarget);
        callee.execute();

        // Should never reach this point as the target is blocking, unless the
        // server is stopped.
    }

    /**
     * Ant will automatically call this method when the "testURL" attribute
     * of our task is used.
     *
     * @param theTestURL the test URL to ping
     */
    public void setTestURL(String theTestURL)
    {
        try {
            m_TestURL = new URL(theTestURL);
        } catch (MalformedURLException e) {
            throw new BuildException("Bad URL [" + theTestURL + "]", e);
        }
    }

    /**
     * Ant will automatically call this method when the "startTarget" attribute
     * of our task is used.
     *
     * @param theStartTarget the Ant target to call
     */
    public void setStartTarget(String theStartTarget)
    {
        m_StartTarget = theStartTarget;
    }

    public void setId(String theId)
    {
        m_ThreadId = theId;
    }

}