package cn.freemud.core.db;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * All rights Reserved, Designed By www.freemud.com
 *
 * @version V1.0
 * @Title: DataSourceBuildUtil
 * @Package: com.freemud.core.data.source.config
 * @Descripttion:
 * @author: yaoming.qian
 * @date: 2018/6/20 17:33
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目.
 */
public class DataSourceBuildUtil {
    public static DataSource init(DruidProperties dataSourcesProperties) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dataSourcesProperties.getUrl());
        dataSource.setUsername(dataSourcesProperties.getUsername());
        dataSource.setPassword(dataSourcesProperties.getPassword());
        dataSource.setDriverClassName(dataSourcesProperties.getDriverClass());
        if (dataSourcesProperties.getInitialSize() > 0) {
            dataSource.setInitialSize(dataSourcesProperties.getInitialSize());
        }
        if (dataSourcesProperties.getMinIdle() > 0) {
            dataSource.setMinIdle(dataSourcesProperties.getMinIdle());
        }
        if (dataSourcesProperties.getMaxActive() > 0) {
            dataSource.setMaxActive(dataSourcesProperties.getMaxActive());
        }
        //配置druid相关的保持心跳参数
        if (dataSourcesProperties.getTimeBetweenEvictionRunsMillis() > 0)
            dataSource.setTimeBetweenEvictionRunsMillis(dataSourcesProperties.getTimeBetweenEvictionRunsMillis());
        if (dataSourcesProperties.getMinEvictableIdleTimeMillis() > 0)
            dataSource.setMinEvictableIdleTimeMillis(dataSourcesProperties.getMinEvictableIdleTimeMillis());
        dataSource.setValidationQuery(dataSourcesProperties.getValidationQuery());
        dataSource.setTestOnBorrow(dataSourcesProperties.isTestOnBorrow());
        dataSource.setTestOnReturn(dataSourcesProperties.isTestOnReturn());
        dataSource.setTestWhileIdle(dataSourcesProperties.isTestWhileIdle());
        //end
        try {
            dataSource.init();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return dataSource;
    }
}
