org.jxstar.dao.pool.PooledConnection.java Source code

Java tutorial

Introduction

Here is the source code for org.jxstar.dao.pool.PooledConnection.java

Source

/*
 * PooledConnection.java 2009-5-28
 * 
 * Copyright 2010 Guangzhou Donghong Software Technology Inc.
 * Licensed under the www.jxstar.org
 */
package org.jxstar.dao.pool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.jxstar.util.factory.FactoryUtil;
import org.jxstar.util.log.Log;

/**
 * DHSDP??Connection
 * 
 * ???????
 * DataSourceConfig.setDataSourceName????
 * ????"default"
 * 
 * ?????
 * DataSourceConfig.setTranLevel
 * 
 * @author TonyTan
 * @version 1.0, 2009-5-28
 */
public class PooledConnection {
    private static PooledConnection _pooledConnection = null;
    //??
    private static Context _context = null;
    //??
    private static Map<String, Object> _myDataSourceMap = null;
    //
    private static Log _log = Log.getInstance();

    private PooledConnection() {
        try {
            _context = new InitialContext();
            _myDataSourceMap = FactoryUtil.newMap();
        } catch (NamingException e) {
            _log.showError(e);
        }
    }

    /**
     * ??
     * @return
     */
    public static synchronized PooledConnection getInstance() {
        if (_pooledConnection == null) {
            _pooledConnection = new PooledConnection();
        }

        return _pooledConnection;
    }

    /**
     * ????????deault
     * ?null?
     * @return 
     */
    public Connection getConnection() {
        return getConnection(DataSourceConfig.getDefaultName());
    }

    /**
     * ??????null?
     * synchronized???
     * ????????
     * 
     * @param dsName -- ????
     * @return
     */
    public Connection getConnection(String dsName) {
        //????default??????
        if (dsName == null || dsName.length() == 0 || dsName.equals("default")) {
            dsName = DataSourceConfig.getDefaultName();
        }

        Connection conn = null;
        DataSourceConfig dsConfig = DataSourceConfigManager.getInstance().getDataSourceConfig(dsName);
        if (dsConfig == null) {
            _log.showWarn("DataSourceConfig is null! ");
            return conn;
        }
        //long sTime = System.currentTimeMillis();

        //???Context?
        if (dsConfig.getDataSourceType().equals(DataSourceConfig.DSTYPE_APPLICATION)) {
            conn = getConnectionFromContext(dsConfig);
        } else {
            //??Apache?
            conn = getConnectionFromSelf(dsConfig);
        }
        //long eTime = System.currentTimeMillis();
        //_log.showDebug("getConnection() use time:" + (eTime - sTime));

        return conn;
    }

    /**
     * ??????????
     * @param dsName
     */
    public synchronized void delConnection(String dsName) {
        if (_myDataSourceMap.containsKey(dsName)) {
            _myDataSourceMap.remove(dsName);
        }
    }

    /**
     * ?
     * ?queueConnect?????5
     * ?1???5???
     * ?validTest?validQuery?validIdle
     * 
     * @param DataSourceConfig   -- ???
     * @return
     */
    private Connection getConnectionFromSelf(DataSourceConfig dsConfig) {
        Connection conn = null;
        DataSource ds = createSelfDataSource(dsConfig);
        boolean catchError = dsConfig.isCatchError();

        try {
            conn = ds.getConnection();
            //_log.showDebug("get connection is:" + conn);

            if (conn == null || conn.isClosed()) {
                String dsName = dsConfig.getDataSourceName();
                _log.showError("datasource [{0}] get connection is null!", dsName);
                return null;
            }

            int iTranLevel = getTranLevelConstant(dsConfig.getTranLevel());
            conn.setAutoCommit(false);
            conn.setTransactionIsolation(iTranLevel);
        } catch (SQLException e) {
            if (catchError) {
                _log.showError(e);
            }
        }

        return conn;
    }

    /**
     * ???
     * @param dsName
     * @return
     */
    private DataSource createSelfDataSource(DataSourceConfig dsConfig) {
        String dsName = dsConfig.getDataSourceName();
        BasicDataSource ds = (BasicDataSource) _myDataSourceMap.get(dsName);
        if (ds != null)
            return ds;

        ds = new BasicDataSource();
        //???
        int iTranLevel = getTranLevelConstant(dsConfig.getTranLevel());
        int maxnum = Integer.parseInt(dsConfig.getMaxConNum());

        ds.setDriverClassName(dsConfig.getDriverClass());
        ds.setUrl(dsConfig.getJdbcUrl());
        ds.setUsername(dsConfig.getUserName());
        ds.setPassword(dsConfig.getPassWord());

        ds.setMaxIdle(maxnum);
        ds.setMaxActive(maxnum);
        ds.setMaxWait(Long.parseLong(dsConfig.getMaxWaitTime()));
        ds.setDefaultAutoCommit(false);
        ds.setDefaultTransactionIsolation(iTranLevel);

        //????SystemVarserver.xml?
        String validTest = dsConfig.getValidTest();
        String validQuery = dsConfig.getValidQuery();
        if (validTest.equalsIgnoreCase("true") && validQuery.length() > 0) {
            _log.showDebug("pool test use query...");
            ds.setTestOnBorrow(true);
            ds.setValidationQuery(validQuery);
            ds.setValidationQueryTimeout(3);
        }

        //?mysql???
        //?????
        if (dsConfig.getValidIdle().equalsIgnoreCase("true")) {
            _log.showDebug("pool idle valid thread started...");
            ds.setMinIdle(5);
            ds.setTestWhileIdle(true);

            //1030?5
            ds.setMinEvictableIdleTimeMillis(30 * 60 * 1000);//30 minus
            ds.setTimeBetweenEvictionRunsMillis(10 * 60 * 1000);//10 minus
        }

        //???
        _myDataSourceMap.put(dsName, ds);

        return ds;
    }

    /**
     * ????
     * 
     * @param dsName   -- ????
     * @param iTranLevel      -- 
     * @return
     */
    private Connection getConnectionFromContext(DataSourceConfig dsConfig) {
        Connection conn = null;
        String jndiName = dsConfig.getJndiName();
        boolean catchError = dsConfig.isCatchError();

        try {
            DataSource ds = (DataSource) _context.lookup(dsConfig.getJndiName());

            conn = ds.getConnection();
            //_log.showDebug("getConnection: " + conn);

            if (conn == null || conn.isClosed()) {
                String dsName = dsConfig.getDataSourceName();
                _log.showError("datasource [{0}] get connection is null!", dsName);
                return null;
            }

            int iTranLevel = getTranLevelConstant(dsConfig.getTranLevel());
            conn.setAutoCommit(false);
            conn.setTransactionIsolation(iTranLevel);
        } catch (NamingException e) {
            if (catchError) {
                _log.showError("error get jndi name is: " + jndiName);
                _log.showError(e);
            }
        } catch (SQLException e) {
            if (catchError) {
                _log.showError("error get jndi name is: " + jndiName);
                _log.showError(e);
            }
        }

        return conn;
    }

    /**
     * ???JDBC
     * Connection.TRANSACTION_NONE
     *       ????
     * Connection.TRANSACTION_READ_UNCOMMITTED
     *       ?????????
     * Connection.TRANSACTION_READ_COMMITTED(?)
     *       ????????? 
     * Connection.TRANSACTION_REPEATABLE_READ
     *       ?????????
     * Connection.TRANSACTION_SERIALIZABLE
     *       ????????
     * 
     * @param sTranLevel
     * @return
     */
    private int getTranLevelConstant(String sTranLevel) {
        if (sTranLevel == null || sTranLevel.length() == 0) {
            return Connection.TRANSACTION_READ_COMMITTED;
        }

        String sTmpLevel = sTranLevel.toUpperCase();
        if (sTmpLevel.equals("TRANSACTION_NONE")) {
            return Connection.TRANSACTION_NONE;
        } else if (sTmpLevel.equals("TRANSACTION_READ_UNCOMMITTED")) {
            return Connection.TRANSACTION_READ_UNCOMMITTED;
        } else if (sTmpLevel.equals("TRANSACTION_READ_COMMITTED")) {
            return Connection.TRANSACTION_READ_COMMITTED;
        } else if (sTmpLevel.equals("TRANSACTION_REPEATABLE_READ")) {
            return Connection.TRANSACTION_REPEATABLE_READ;
        } else if (sTmpLevel.equals("TRANSACTION_SERIALIZABLE")) {
            return Connection.TRANSACTION_SERIALIZABLE;
        }

        return Connection.TRANSACTION_READ_COMMITTED;
    }
}