/* ======================================================================
The Bodington System Software License, Version 1.0
 
Copyright (c) 2001 The University of Leeds.  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 acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.
 
4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.
 
5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.
 
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
EVENT SHALL THE UNIVERSITY OF LEEDS 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 was originally created by the University of Leeds and may contain voluntary
contributions from others.  For more information on the Bodington Open Source Project, please
see http://bodington.org/
 
====================================================================== */

package org.bodington.ant;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.JDBCTask;
import org.bodington.installation.Installer;
import org.bodington.server.BuildingServer;

/**
 * An ANT task for creating an Bodington database.
 * <h3>Use</h3>
 * <p>
 * As this task is not a core ANT task, you will need to declare it in your
 * build file. You will need to add something such as the following (the nested
 * <code>classpath</code> element tells ANT where to find the task).
 * </p>
 * 
 * <pre>
 * 
 *   &lt;taskdef name=&quot;database-setup&quot; classname=&quot;org.bodington.ant.DatabaseSetupTask&quot;&gt;
 *     &lt;classpath&gt;
 *       &lt;pathelement location=&quot;${build}/bodserver.jar&quot;/&gt;
 *     &lt;/classpath&gt;
 *   &lt;/taskdef&gt;
 *   
 * </pre>
 * 
 * <h3>Parameters</h3>
 * <table cellspacing="0" border="1"> <thead>
 * <tr>
 * <th>Attribute</th>
 * <th>Description</th>
 * <th>Required</th>
 * </tr>
 * </thead> <tbody>
 * <tr>
 * <td>driver</td>
 * <td>The name of the JDBC driver.</td>
 * <td>Yes</td>
 * </tr>
 * <tr>
 * <td>url</td>
 * <td>The URL to connection to the database with.</td>
 * <td>Yes</td>
 * </tr>
 * <tr>
 * <td>userid</td>
 * <td>The userid to connect to the database as.</td>
 * <td>Yes</td>
 * </tr>
 * <tr>
 * <td>password</td>
 * <td>The password to use connecting to the database.</td>
 * <td>Yes</td>
 * </tr>
 * <tr>
 * <td>drop</td>
 * <td>If set to true then the all tables will be dropped before attempting to create replacements.</td>
 * <td>No[*]</td>
 * </tr>
 * <tr>
 * <td>create</td>
 * <td>If we should attempt to create new database tables.</td>
 * <td>No[*]</td>
 * </tr>
 * </tbody> </table>
 * [*] - One of these should be set or nothing will happen.
 * <h3>Examples</h3>
*
 * You can call the task (within a target) using the following entry:
 * 
 * <pre>
 * 
 *   &lt;database-setup driver=&quot;org.postgresql.Driver&quot;
 *   url=&quot;jdbc:postgresql://localhost/database&quot;
 *   userid=&quot;username&quot;
 *   password=&quot;password&quot;/&gt;
 *  
 * </pre>
 * @author buckett
 */

public class DatabaseSetupTask extends JDBCTask
{

    private String driver;
    private boolean drop;
    private boolean create;

    public void execute() throws BuildException
    {
        Connection conn = getConnection();
        try
        {
            if(isDrop())
            {
                Installer.deleteTables(conn);
            }
            if (isCreate())
            {
                Installer.createTables(conn, this.getClass(), null, Installer.getSQLSubstitutions(driver), false,
                    "", "");
            }
            conn.commit();
        }
        catch (SQLException e)
        {
            throw new BuildException(e);
        }
        catch (IOException ioe)
        {
            throw new BuildException(ioe);
        }
        finally
        {
            if (conn != null)
            {
                try
                {
                    conn.close();
                }
                catch (SQLException ingore)
                {
                }
            }
        }
      
        if (isCreate())
        {
            try
            {
                AntClassLoader loader = (AntClassLoader)getClass().getClassLoader();
                loader.setParent(getLoader());
                Installer.createMinimalData(getBodingtonProperties());
                BuildingServer.getInstance().shutdown();
            }
            catch (Exception e)
            {
                throw new BuildException(e);
            }
        }
    }

    /**
     * This gets a Properties object suitable for feeding to the BuildingServer.
     * It takes the options that were used to configure this ant task to
     * build the properties.
     * @return A Properties object.
     */
    private Properties getBodingtonProperties()
    {
        Properties props = new Properties();
        props.setProperty("buildingserver.job_scheduler.enabled", "no");
        props.put("sqldatabase.url", getUrl());
        props.put("sqldatabase.user_name", getUserId());
        props.put("sqldatabase.password", getPassword());
        props.put("sqldatabase.driver", getDriver());
        if (getDriver().equals("org.hsqldb.jdbcDriver"))
        {
            props.put("buildingserver.dbimplementation",
                "org.bodington.sqldatabase.EmbeddedHSqlDatabase");
        }
        return props;
    }

    /**
     * Gets the class that is used from the driver.
     * @return The name of the driver.
     */
    public String getDriver()
    {
        return this.driver;
    }
    
    /**
     * Sets the driver that will be used.
     * @param driver The driver to set.
     */
    public void setDriver(String driver)
    {
        this.driver = driver;
        super.setDriver(driver);
    }
    
    /**
     * Check if the old tables will be dropped first.
     * @return Returns true if the old tables should be dropped.
     */
    public boolean isDrop()
    {
        return drop;
    }
    
    /**
     * Set if the old tables should be dropped first.
     * @param drop If true is passed then the old tables will be dropped.
     */
    public void setDrop(boolean drop)
    {
        this.drop = drop;
    }

    /**
     * @return Returns the create.
     */
    public boolean isCreate()
    {
        return create;
    }

    /**
     * @param create The create to set.
     */
    public void setCreate(boolean create)
    {
        this.create = create;
    }
}
