com.icbc.Scheduler.DA.PoolingConnectionProvider.java Source code

Java tutorial

Introduction

Here is the source code for com.icbc.Scheduler.DA.PoolingConnectionProvider.java

Source

/* 
 * Copyright 2004-2005 OpenSymphony 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at 
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0 
 *   
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 * 
 */

/*
 * Previously Copyright (c) 2001-2004 James House
 */
package com.icbc.Scheduler.DA;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.icbc.Scheduler.Core.SchedulerEnviornment;
import com.icbc.Scheduler.Global.GlobalDefine;
import com.icbc.Scheduler.Log.LogProvider;
import com.icbc.Scheduler.Util.*;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * <p>
 * A <code>ConnectionProvider</code> implementation that creates it's own
 * pool of connections.
 * </p>
 * 
 * <p>
 * This class uses <a href="http://jakarta.apache.org/commons/index.html">DBCP
 * </a>, an Apache-Jakarta-Commons product.
 * </p>
 * 
 * @see DBConnectionManager
 * @see ConnectionProvider
 * 
 * @author Sharada Jambula
 * @author James House
 * @author Mohammad Rezaei
 */
public class PoolingConnectionProvider implements ConnectionProvider {

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * 
     * Constants.
     * 
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    // The JDBC database driver
    public static final String DB_DRIVER = "driver";

    // The JDBC database URL
    public static final String DB_URL = "URL";

    // The database user name
    public static final String DB_USER = "user";

    // The database user password
    public static final String DB_PASSWORD = "password";

    public static final String DB_MAX_CONNECTIONS = "maxConnections";

    public static final String DB_VALIDATION_QUERY = "validationQuery";

    //Count of connection
    public static int m_iUsingConnectionCount = 0;
    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * 
     * Data members.
     * 
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    private BasicDataSource datasource;

    //the status of Connection;when connection is abnormal,status will be -1
    private int m_iConnectionStatus = 0;

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * 
     * Constructors.
     * 
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    public PoolingConnectionProvider(String dbDriver, String dbURL, String dbUser, String dbPassword,
            int maxConnections, String dbValidationQuery) throws SQLException {

        initialize(dbDriver, dbURL, dbUser, dbPassword, maxConnections, dbValidationQuery);

    }

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * 
     * Interface.
     * 
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    private void initialize(String dbDriver, String dbURL, String dbUser, String dbPassword, int maxConnections,
            String dbValidationQuery) throws SQLException {
        if (dbDriver == null) {
            throw new SQLException("DB driver class name cannot be null!");
        }

        if (dbURL == null) {
            throw new SQLException("DB URL cannot be null!");
        }

        if (maxConnections < 0) {
            throw new SQLException("Max connections must be greater than zero!");
        }

        datasource = new BasicDataSource();
        datasource.setDriverClassName(dbDriver);
        datasource.setUrl(dbURL);
        datasource.setUsername(dbUser);
        datasource.setPassword(dbPassword);
        datasource.setMaxActive(maxConnections);
        datasource.setTestOnBorrow(true);
        //datasource.setLoginTimeout(5); 
        //        datasource.setLoginTimeout(-1);
        //        datasource.setMaxWait(-1);

        if (dbValidationQuery != null) {
            datasource.setValidationQuery(dbValidationQuery);
        } else {
            datasource.setValidationQuery("select SYSDATE FROM DUAL");
        }
    }

    /**
     * <p>
     * Create a connection pool using the given properties.
     * </p>
     * 
     * <p>
     * The properties passed should contain:
     * 
     * <UL>
     * <LI>{@link #DB_DRIVER}- The database driver class name
     * <LI>{@link #DB_URL}- The database URL
     * <LI>{@link #DB_USER}- The database user
     * <LI>{@link #DB_PASSWORD}- The database password
     * <LI>{@link #DB_MAX_CONNECTIONS}- The maximum # connections in the pool
     * </UL>
     * <P>
     * 
     * @param config
     *          configuration properties
     * @exception SQLException
     *              if an error occurs
     */
    public PoolingConnectionProvider(Properties config) throws Exception {
        PropertiesParser cfg = new PropertiesParser(config);
        String url = cfg.getStringProperty(DB_URL);

        try {
            initialize(cfg.getStringProperty(DB_DRIVER), url, cfg.getStringProperty(DB_USER),
                    cfg.getStringProperty(DB_PASSWORD), cfg.getIntProperty(DB_MAX_CONNECTIONS),
                    cfg.getStringProperty(DB_VALIDATION_QUERY));
        } catch (Exception e) {
            LogProvider.outException(e, "", PoolingConnectionProvider.class.getName());

            throw e;
        }
    }

    /**
     * <p>Get a connection from DBCP</p>
     * @exception SQLException
     *             if any error occurs
     * */
    public Connection getConnection() throws SQLException {
        return this.datasource.getConnection();
    }

    /**
     * <p>Shutdown DBCP</p>
     * @exception SQLException
     *             if any error occurs
     * */
    public void shutdown() throws SQLException {
        this.datasource.close();
    }

    /**
     * <p>Short ping PoolingConnectionProvider</p>
     * @return int: 
     *          1: Ping successfully.
     *          0: Ping unsuccessfully.
     */
    public int pings() {
        int t_iPingResult = GlobalDefine.PING_SUCCESS;
        String t_sSql = "";
        Connection t_Conn = null;
        ResultSet t_rsResult = null;
        PreparedStatement t_PStat = null;

        try {
            /*Get connection*/
            t_Conn = getConnection();

            /*Get ping SQL*/
            t_sSql = DBConstantsProvider.getInstance().getPingsSQL();

            /*Execute ping SQL*/
            t_PStat = t_Conn.prepareStatement(t_sSql);
            t_rsResult = t_PStat.executeQuery();

            /*Execute successfully*/
            t_iPingResult = GlobalDefine.PING_SUCCESS;

            if (m_iConnectionStatus == -1) {
                LogProvider.outLog("INFO", "Error Connection turns normal", GlobalDefine.LOG_LOGGER_DB,
                        SchedulerEnviornment.class.getName());
            }

            m_iConnectionStatus = 0;
        } catch (Exception e) {
            t_iPingResult = GlobalDefine.PING_ERROR_GENERAL;
            if (m_iConnectionStatus == 0) {
                LogProvider.outException(e, "t_sSql:" + t_sSql, SchedulerEnviornment.class.getName());
            }
            m_iConnectionStatus = -1;
            return t_iPingResult;
        } finally {
            if (t_rsResult != null) {
                try {
                    t_rsResult.close();
                } catch (Exception e) {
                    LogProvider.outException(e, "t_rsResult.close() error in pings",
                            StdSchedulerDA.class.getName());
                }
            }
            if (t_Conn != null) {
                try {
                    t_Conn.close();
                } catch (Exception e) {
                    LogProvider.outException(e, "Conn.close() error in pings", StdSchedulerDA.class.getName());
                }
            }
        }

        return t_iPingResult;
    }

    /**
     * <p>Long ping PoolingConnectionProvider</p>
     * @return String: Ping msg
     */
    public String pingl() {
        String t_sPingResult = "";
        String t_sSql = "";
        String t_sFormatStr = "";
        IFConfigFileParser t_INIFile = null;
        Connection t_Conn = null;
        ResultSet t_rsResult = null;
        PreparedStatement t_PStat = null;

        try {
            /*Get connection*/
            t_Conn = getConnection();

            /*Get ping SQL*/
            t_sSql = DBConstantsProvider.getInstance().getPinglSQL();

            /*Execute ping SQL*/
            t_PStat = t_Conn.prepareStatement(t_sSql);
            t_rsResult = t_PStat.executeQuery();

            /*Get ping result*/
            t_INIFile = ConfigFileManager.getInstance().getConfigFilePaser(GlobalDefine.INIMAIN);
            t_sFormatStr = t_INIFile.getStringProperty("PING_FORMAT_DB");
            t_sPingResult = t_sFormatStr;

            t_INIFile = ConfigFileManager.getInstance().getConfigFilePaser(GlobalDefine.INICTLTABLE);
            while (t_rsResult.next()) {
                t_sPingResult = t_sPingResult.replaceAll(GlobalDefine.PING_FORMAT_DB_MSG,
                        t_rsResult.getString(t_INIFile.getStringProperty("T_PING_PING_MSG").trim()));
            }
        } catch (Exception e) {
            LogProvider.outException(e, "", "ping");
            t_sPingResult = GlobalDefine.PING_ERROR;
            return t_sPingResult;
        } finally {
            if (t_rsResult != null) {
                try {
                    t_rsResult.close();
                } catch (Exception e) {
                }
            }
            if (t_Conn != null) {
                try {
                    t_Conn.close();
                } catch (Exception e) {
                }
            }
        }

        return t_sPingResult;
    }
}