/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: DatasourceBean.java 21469 2011-06-21 11:39:42Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.tests.applications.osgi.datasources;

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

import javax.ejb.Stateless;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.XADataSource;

import org.osgi.service.jdbc.DataSourceFactory;
import org.ow2.easybeans.osgi.annotation.OSGiResource;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * This EJB3 Bean will interact with database through a DataSourceFactory.
 * @author Florent Benoit
 */
@Stateless(mappedName="DatasourceBean")
public class DatasourceBean implements IDataSource {

    /**
     * Logger.
     */
    private static Log LOGGER = LogFactory.getLog(DatasourceBean.class);

    /**
     * H2 Driver classname.
     */
    private static final String H2_DRIVER_CLASSNAME = "org.h2.Driver";

    /**
     * Filter in order to get a H2 datasource factory.
     */
    private static final String FILTER = "(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)("
            + DataSourceFactory.OSGI_JDBC_DRIVER_CLASS + "=" + H2_DRIVER_CLASSNAME + "))";

    /**
     * Bundle context.
     */
    @OSGiResource(filter=FILTER)
    private DataSourceFactory dataSourceFactory = null;

    /**
     * Check Datasource Factory has been created.
     * @return true if DSF is not null
     */
    public boolean checkFactory() {
        return dataSourceFactory != null;
    }


    /**
     * Test if driver can be retrieved.
     * @return true if test is ok
     * @throws SQLException if test fails
     */
    public boolean testDriver() throws SQLException {
       Driver driver = dataSourceFactory.createDriver(null);
       if (driver == null) {
           throw new IllegalStateException("Driver is null");
       }
       return H2_DRIVER_CLASSNAME.equals(driver.getClass().getName());
    }

    /**
     * Init the properties used to connect to H2 database.
     * @return a properties object
     */
    protected Properties initProperties() {
        Properties properties = new Properties();
        properties.put(DataSourceFactory.JDBC_USER, "jonas");
        properties.put(DataSourceFactory.JDBC_PASSWORD, "jonas");

        // Get port
        String dbPort = System.getProperty("db.port");
        if (dbPort == null) {
            throw new IllegalStateException("Unable to find 'db.port' system property. Check the configuration");
        }

        properties.put(DataSourceFactory.JDBC_URL, "jdbc:h2:tcp://localhost:" + dbPort + "/db_jonas");

        return properties;
    }


    /**
     * Test execution of a datasource.
     * @return true if test is ok
     * @throws SQLException if test fails
     */
    public boolean testDatasource() throws SQLException {
        DataSource datasource = dataSourceFactory.createDataSource(initProperties());

        // try connection
        return tryConnection(datasource.getConnection());
    }

    /**
     * Test execution of a XA datasource.
     * @return true if test is ok
     * @throws SQLException if test fails
     */
    public boolean testXADatasource() throws SQLException {
        XADataSource xaDatasource = dataSourceFactory.createXADataSource(initProperties());

        // try connection
        return tryConnection(xaDatasource.getXAConnection().getConnection());
    }

    /**
     * Test execution of a Pooled datasource.
     * @return true if test is ok
     * @throws SQLException if test fails
     */
    public boolean testConnectionPoolDataSourceDatasource() throws SQLException {
        ConnectionPoolDataSource connectionPoolDataSource = dataSourceFactory.createConnectionPoolDataSource(initProperties());

        // try connection
        return tryConnection(connectionPoolDataSource.getPooledConnection().getConnection());
    }

    /**
     * Try to connect and send operations on the given JDBC connection.
     * @param connection the JDBC connection
     * @return true if all operations have been successful
     * @throws SQLException if operations fails.
     */
    protected boolean tryConnection(final Connection connection) throws SQLException {
        Statement statement = null;
        try {

            // Get statement
            statement = connection.createStatement();


            // Try to drop table if exists
            String query = "DROP TABLE datasource_factory_test";
            try {
                statement.executeUpdate(query);
            } catch (Exception e) {
                // Table may not exist
                LOGGER.debug("Table doesn't exist yet", e);
            }

            query = "create table datasource_factory_test " + "(NAME varchar(50), " + "LASTNAME varchar(50))";
            statement = connection.createStatement();
            statement.executeUpdate(query);

            String insertTest = "INSERT INTO datasource_factory_test (NAME, LASTNAME) VALUES ('FLORENT', 'BENOIT')";
            statement.executeUpdate(insertTest);
            return true;
        } finally {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }

    }

}
