com.tera.common.database.factory.AbstractDatabaseFactory.java Source code

Java tutorial

Introduction

Here is the source code for com.tera.common.database.factory.AbstractDatabaseFactory.java

Source

/**
 * This file is part of tera-api.
 * 
 * tera-api 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 3 of the License, or
 * (at your option) any later version.
 * 
 * tera-api 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 tera-api.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.tera.common.database.factory;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tera.common.database.DatabaseConfiguration;
import com.tera.common.database.DatabaseFactory;
import com.tera.common.database.dbcp.CPoolableConnectionFactory;

/**
 * @author ATracer
 */
public abstract class AbstractDatabaseFactory implements DatabaseFactory {

    private static final Logger log = LoggerFactory.getLogger(AbstractDatabaseFactory.class);

    private DataSource dataSource;

    private GenericObjectPool connectionPool;

    private String databaseName;

    private int databaseMajorVersion;

    private int databaseMinorVersion;

    /**
     * Initializes database factory using specific configuration
     * 
     * @param dbConfig
     */
    @Override
    public void start(DatabaseConfiguration dbConfig) {
        loadDatabaseDriver(dbConfig);
        createConnectionPool(dbConfig);
    }

    /**
     * @param dbConfig
     */
    void loadDatabaseDriver(DatabaseConfiguration dbConfig) {
        log.info("Loading DB driver");
        try {
            dbConfig.getDatabaseDriver().newInstance();
        } catch (Exception e) {
            log.error("Exception during initialization of the driver", e);
        }
    }

    /**
     * @param dbConfig
     * @throws Error
     */
    void createConnectionPool(DatabaseConfiguration dbConfig) throws Error {
        log.info("Creating DB pool");
        connectionPool = new GenericObjectPool();
        connectionPool.setMaxIdle(dbConfig.getConnectionsIdelMax());
        connectionPool.setMinIdle(dbConfig.getConnectionsIdleMin());
        connectionPool.setMaxActive(dbConfig.getConnectionsActiveMax());
        connectionPool.setTestOnBorrow(true);

        try {
            dataSource = setupDataSource(dbConfig);
            Connection c = getConnection();
            DatabaseMetaData dmd = c.getMetaData();
            databaseName = dmd.getDatabaseProductName();
            databaseMajorVersion = dmd.getDatabaseMajorVersion();
            databaseMinorVersion = dmd.getDatabaseMinorVersion();
            c.close();
        } catch (Exception e) {
            log.error("Error with connection string: {}", dbConfig, e);
            throw new Error("DatabaseFactory not initialized!");
        }
        log.info("Successfully connected to the database");
    }

    /**
     * @param dbConfig
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    private DataSource setupDataSource(DatabaseConfiguration dbConfig) throws Exception {
        // Create Connection Factory
        ConnectionFactory conFactory = new DriverManagerConnectionFactory(dbConfig.getDatabaseUrl(),
                dbConfig.getUser(), dbConfig.getPassword());

        new CPoolableConnectionFactory(conFactory, connectionPool, null, 1, false, true);

        // Create data source to utilize Factory and Pool
        return new PoolingDataSource(connectionPool);
    }

    @Override
    public void stop() {
        try {
            connectionPool.close();
        } catch (Exception e) {
            log.error("Failed to shutdown DatabaseFactory", e);
        }
        connectionPool = null;
        dataSource = null;
    }

    @Override
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    @Override
    public String getDatabaseName() {
        return databaseName;
    }

    @Override
    public int getDatabaseMajorVersion() {
        return databaseMajorVersion;
    }

    @Override
    public int getDatabaseMinorVersion() {
        return databaseMinorVersion;
    }

    /**
     * @return object pool that backs connection factory
     */
    protected ObjectPool getPool() {
        return connectionPool;
    }

}