/* ======================================================================
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.sqldatabase;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.bodington.database.ConnectionPoolException;
import org.bodington.pool.ObjectPoolException;

/**
 * Class to be used when using an in process HSQLDB connection.
 * This is so that we can load the database from within the context
 * and also so that we shut it down correctly after finishing.
 * @author buckett
 */
public class EmbeddedHSqlDatabase extends SqlDatabase
{
    private static final String HSQLDB_JDBC_DRIVER = "org.hsqldb.jdbcDriver";
    private static Logger log = Logger.getLogger(EmbeddedHSqlDatabase.class);

    /**
     * @throws Exception
     */
    public EmbeddedHSqlDatabase() throws Exception
    {
        super();
    }
    
    /**
     * Allows HSQLDB JDBC urls to include a webapp section.
     * The webapp URLs are mapped across to file URLs inside the WEB-INF
     * folder of the webapp. This depends on having the property 
     * <code>buildingservlet.context.root</code> defined.
     * @param props The BuildingServer properties that are passed across.
     */
    public void init(Properties props) throws Exception
    {
        String contextRoot = props.getProperty("buildingservlet.context.root");
        
        String driver = props.getProperty("sqldatabase.driver", HSQLDB_JDBC_DRIVER);
        String url = props.getProperty("sqldatabase.url", "jdbc:hsqldb:webapp:/database/quickstart");
        String username = props.getProperty("sqldatabase.username", "sa");
        String password = props.getProperty("sqldatabase.password", "");
        
        if (!driver.equals(HSQLDB_JDBC_DRIVER))
            log.warn("You are using the Embedded HSQLDB driver but "
                + "your property 'sqldatabase.driver' isn't set to: "
                + HSQLDB_JDBC_DRIVER);

        url = addContextIfWebApp(url, contextRoot);
        props.setProperty("sqldatabase.driver", driver);
        props.setProperty("sqldatabase.url", url);
        props.setProperty("sqldatabase.username", username);
        props.setProperty("sqldatabase.password", password);
        log.info("Using HSQLDB URL: "+ url);

        super.init(props);
    }
    
    /**
     * Attempts to destroy the database connections.
     * We need a custom HSQLDB version for this so that when a servlet context is
     * reloaded the old database gets shutdown so the new one can be started up.
     * This is because each upon context reload a new classloader is created.
     */
    public void destroy()
    {
        try
        {
            Connection connection = (Connection)connection_pool.getConnection(this);
            Statement statement = connection.createStatement();
            statement.execute("SHUTDOWN");
        }
        catch (ConnectionPoolException ope)
        {
            log.error("Could not get connection from pool. Database might not have been shutdown.");
        }
        catch (SQLException sqle)
        {
            log.error("Error sending the SHUTDOWN command to the database.");
        }
        super.destroy();
    }
    
    /**
     * Attempt to change our special webapp HSQLDB URLs to file ones.
     * @param url The database URL.
     * @param context The servlet context in which we are running.
     * @return The changed JDBC URL.
     */
    private String addContextIfWebApp(String url, String context)
    {
        if (url.startsWith("jdbc:hsqldb:webapp:"))
        {
            return "jdbc:hsqldb:file:" + context + "/WEB-INF/"
                + url.substring("jdbc:hsqldb:webapp:".length());
        }
        return url;
    }

}
