/*
 * Created on 2005. 6. 17.
 */
package net.javajigi.security.dao.springjdbc;

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

import org.apache.log4j.Logger;

import javax.sql.DataSource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

/**
 * @author Administrator
 */
public class DataSourcePopulator implements InitializingBean {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger
            .getLogger(DataSourcePopulator.class);
    
    private DataSource dataSource = null;
    
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public DataSource getDataSource() {
        return dataSource;
    }
    
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(dataSource, "dataSource required");
        
        if( !isExistedTable() ) {
    		StringBuffer sb = new StringBuffer();
    		sb.append("CREATE TABLE USERINFO ( ");
    		sb.append("UserID		VARCHAR(20) primary key,");
    		sb.append("Password 	VARCHAR(10),");
    		sb.append("Name 		VARCHAR(10),");
    		sb.append("Email 		VARCHAR(20) )");
    		
            JdbcTemplate template = new JdbcTemplate(dataSource);
            template.execute(sb.toString());       
            
            logger.info("Created USERINFO Table!!");
        }
    }    
    
    private boolean isExistedTable() {
		DatabaseMetaData metaData = null;
		try {
			Connection con = dataSource.getConnection();
			metaData = con.getMetaData();
			
			return metaData.getTables(null, null, "USERINFO", null).next();
		} catch (SQLException e) {
			logger.error("Connection을 생성하는 중 에러 발생", e);
			
			throw new CannotGetJdbcConnectionException("Connection을 생성하는 중 에러 발생", e);
		}        
    }
}
