package kr.co.kihyun.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;

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

import kr.co.kihyun.moumi.MoumiConfig;

public class DBPool {
        //50.public static을 통한 선언 오류(CWE-500) Delete by YOUNGJUN,CHO
	//public static int conCount = 0;
        //------------------------------------------------
	private static DataSource ds = null;
	private static Context ctx;

	static {
		try {
			ctx = new InitialContext();
			ctx.addToEnvironment("SetBigStringTryClob", "true");
			ctx.addToEnvironment("oracle.jdbc.V8Compatible", "true");
			ctx.addToEnvironment("oracle.jdbc.mapDateToTimeStamp", "false");
			ds = (DataSource) ctx
					.lookup(MoumiConfig.getPMFProperties().getProperty("javax.jdo.option.ConnectionFactoryName"));
		} catch (NamingException ne) {
			ne.printStackTrace();
		} catch (NullPointerException npe) {
			try {
				ds = (DataSource) ctx.lookup(MoumiConfig.getPMFProperties().getProperty("moumi.jndi.name"));
			} catch (NamingException e) {
				e.printStackTrace();
			}
		}
	}

	public Connection getConnection() throws SQLException {
		if (ds == null) {
			try {
				ds = (DataSource) ctx.lookup(MoumiConfig.getPMFProperties().getProperty("moumi.jndi.name"));
			} catch (NamingException e) {
				e.printStackTrace();
			}
		}
		Connection con = ds.getConnection();
		con.setAutoCommit(true);
		return con;
	}

	protected void close(Connection con) {
		try {
			if (con != null)
				con.close();
		} catch (SQLException ex) {
                    //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                    ex.printStackTrace();
                    //++++++++++++++++++++++++++++++++++++++++++++++++
		}
	}

	protected void close(Statement stmt) {
		try {
			if (stmt != null)
				stmt.close();
		} catch (SQLException ex) {
                    //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                    ex.printStackTrace();
                    //++++++++++++++++++++++++++++++++++++++++++++++++
		}
	}

	protected void close(PreparedStatement pstmt) {
		try {
			if (pstmt != null)
				pstmt.close();
		} catch (SQLException ex) {
                //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                    ex.printStackTrace();
                    //++++++++++++++++++++++++++++++++++++++++++++++++
		}
	}


	protected void close(ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException ex) {
                    //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                    ex.printStackTrace();
                    //++++++++++++++++++++++++++++++++++++++++++++++++
		}
	}
}
