package CoreFS.SA04;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.sql.DataSource;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.sun.org.apache.bcel.internal.generic.Type;

import CoreFS.SA01.CoreException;
import CoreFS.SA01.CoreExceptionHandler;
import CoreFS.SA01.CoreGlobalConstants;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA06.CoreSqlType.CoreOracleType;
import CoreFS.Util.StringUtils;
import CoreFS.Util.XmlUtil;


public class CoreDBManager {
	private static final long serialVersionUID = -986600646149636690L;
	protected final Log log = LogFactory.getLog(getClass());	
	public CoreDBProxy dbProxy;

	public CoreDBManager() {

	}

	public CoreDBManager(CoreDBProxy dbproxy) {
		this.dbProxy = dbproxy;
	}
	/**
	 * @desc 获取数据库连接
	 * @return
	 */
	public Connection getConnection() {
		Connection conn = null;
		try {
			conn = this.dbProxy.getJdbcTemplate().getDataSource()
					.getConnection();
			log.info("连接数据库成功！conn= " + conn);
		} catch (SQLException e) {
			throw (new CoreException("数据库连接失败 请检查网络或数据库配置文件..."));
		}	
		return conn;
	}

	public CoreReturnObject ExecutequeryForRowSet(String sql, Object[] args)throws SQLException {
		SqlRowSet srs = null;
		this.PrintSQL(sql, args);
		CoreReturnObject cro = new CoreReturnObject();
		srs = this.dbProxy.getJdbcTemplate().queryForRowSet(sql, args);
		cro.setResult(srs);
		return cro;
	}

	public CoreReturnObject ExecutequeryForRowSet(String sql)throws SQLException {
		return this.ExecutequeryForRowSet(sql, null);
	}

	public int getQueryCount(String sql) {
		return this.getQueryCount(sql, null);
	}

	public int getQueryCount(String sql, Object[] args) {
		return this.dbProxy.getJdbcTemplate().queryForList(sql, args).size();
	}
   //执行大数据非操作查询
	public CoreReturnObject ExceuteNonQueryForBlobList(String sql) throws SQLException
	{
		return this.ExceuteNonQueryForBlobList( sql,null);
	}
	/**
	 * @desc 带参数的对含有Blob类型数据的非查询操作
	 * @param sql
	 * @param args
	 * @return
	 * @throws SQLException
	 */
	public CoreReturnObject ExceuteNonQueryForBlobList(String sql,Object[] args) throws SQLException
	{
		this.PrintSQL(sql, args);
		CoreReturnObject cro = new CoreReturnObject();
		PreparedStatement stmt = null;
		Connection conn=null;
		try{
		conn=this.getConnection();
		stmt = conn.prepareStatement(sql);
		// 设置占位符
		if (args != null) {
			for (int i = 0; i < args.length; i++) {
				int j=i+1;
				//String ii=args[i].toString();
				if (args[i] != null) {
					if (args[i] instanceof String) {
						if(((String)args[i]).length()<800)
						{
						stmt.setString(j, (String)args[i]);
						}else
						{
							this.dbProxy.getLobHandler().getLobCreator().setClobAsString(stmt, j, (String) args[i]);
						}
					} else if (args[i] instanceof Integer) {
						stmt.setInt(i, ((Integer) args[i]).intValue());
					} else if (args[i] instanceof Double) {
						stmt.setDouble(i, ((Double) args[i]).doubleValue());
					} else if (args[i] instanceof Float) {
						stmt.setFloat(i, ((Float) args[i]).floatValue());
					} else if (args[i] instanceof Date) {
						stmt.setDate(i, ((Date) args[i]));
					}else if(args[i] instanceof byte[])
					{						
						this.dbProxy.getLobHandler().getLobCreator().setBlobAsBytes(stmt, j, (byte[]) args[i]);
					}
				}
			}			
		}
		int count=stmt.executeUpdate();
		cro.setResult(count);
		}catch(SQLException sqlex)
		{
			throw sqlex;
		}
		catch(Exception ex)
		{
			log.debug(ex);
		}finally
		{
			try {
			   if (stmt != null) {
					stmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 
		}
		return cro;
	}
	/**
	 * @desc 带参数的对含有Blob类型数据的表的查询操作
	 * @param sql
	 * @param args
	 * @return
	 * @throws SQLException
	 * @author Lofty
	 */
	public CoreReturnObject ExceuteQueryForBlobList(String sql, Object[] args) throws SQLException{
		CoreReturnObject cro = new CoreReturnObject();
		this.PrintSQL(sql, args);
		Connection conn = null;
		List ls = new ArrayList();
		ResultSet rs = null;
		PreparedStatement stmt = null;
		try {
			try {
				conn = this.dbProxy.getJdbcTemplate().getDataSource()
						.getConnection();
				log.info("连接数据库成功！ " + conn);
			} catch (SQLException e) {
				throw (new CoreException("数据库连接失败 请检查网络或数据库配置文件..."));
			}
			conn.setAutoCommit(false);
			stmt = conn.prepareStatement(sql); // this.getPreparedStatement(sql);
			// 设置占位符
			if (args != null) {
				for (int i = 0; i < args.length; i++) {
					int j = i + 1;
					String ii = args[i].toString();
					if (args[i] != null) {
						if (args[i] instanceof String) {
							stmt.setString(j, (String) args[i]);
						} else if (args[i] instanceof Integer) {
							stmt.setInt(i, ((Integer) args[i]).intValue());
						} else if (args[i] instanceof Double) {
							stmt.setDouble(i, ((Double) args[i]).doubleValue());
						} else if (args[i] instanceof Float) {
							stmt.setFloat(i, ((Float) args[i]).floatValue());
						} else if (args[i] instanceof Date) {
							stmt.setDate(i, ((Date) args[i]));
						}
					}
				}
			}
			// 获得ResultSet
			rs = stmt.executeQuery();// sql);			
			int clumncount = rs.getMetaData().getColumnCount();
			int columntype = 0;
			String columnname = "";
			// HashMap rowmap = new LinkedHashMap();
			while (rs.next()) {
				HashMap rowmap = new LinkedHashMap();
				// 构建行记录

				// HashMap table = new HashMap();

				for (int i = 1; i <= clumncount; i++) {
					HashMap table = new HashMap();
					columntype = rs.getMetaData().getColumnType(i);
					columnname = rs.getMetaData().getColumnName(i);

					switch (columntype) {
					case Types.VARCHAR:
						table.put(columnname, (String) rs.getObject(i));
						break;
					case Types.NUMERIC:
						table.put(columnname, (Number) rs.getObject(i));
						break;
					case Types.BLOB:
						byte[] barry = this.dbProxy.getLobHandler()
								.getBlobAsBytes(rs, i);
						if (barry == null) {
							table.put(columnname, new byte[0]);
						} else {
							table.put(columnname, barry);
						}
						break;
					case Types.CLOB:
						table.put(columnname, this.dbProxy.getLobHandler()
								.getClobAsString(rs, i));
						break;
					case Types.INTEGER:
						table.put(columnname, (Integer) rs.getObject(i));
						break;
					case Types.DOUBLE:
						table.put(columnname, (Double) rs.getObject(i));
						break;
					case Types.FLOAT:
						table.put(columnname, (Float) rs.getObject(i));
						break;
					case Types.DATE:
						table.put(columnname, (Date) rs.getObject(i));
						break;
					default:
						throw (new CoreException("超出平台所定义的类型 ... "));
					}
					rowmap.putAll(table);
				}

				ls.add(rowmap);
			}
		} catch (SQLException e) {
			conn.rollback();
			throw e;
			//log.equals(e);
		}catch(Exception ex)
		{
			log.debug(ex.getMessage());
		}
		finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (stmt != null) {
					stmt.close();
				}
				if (conn != null) {
					conn.close();						
				}
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		// 构建结果集

		cro.setResult(ls);		
		return cro;
	}

	public CoreReturnObject ExceuteQueryForBlobList(String sql)throws SQLException {
		return this.ExceuteQueryForBlobList(sql, null);
	}
	
	
	public ResultSet ExceuteQueryForResultSet(String sql, Object[] args)throws SQLException{
		this.PrintSQL(sql, args);
		ResultSet rs = null;
		Statement stmt = null;
		Connection conn = this.getConnection();
		try {
			stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
					ResultSet.CONCUR_UPDATABLE);
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			JdbcUtils.closeConnection(conn);
			conn = null;
			JdbcUtils.closeStatement(stmt);
			stmt = null;
			JdbcUtils.closeResultSet(rs);
			rs = null;
			e.printStackTrace();
		}
		// 创建Statement接口实例
		return rs;
	}

	public ResultSet ExceuteQueryForResultSet(String sql)throws SQLException{
		return this.ExceuteQueryForResultSet(sql, null);
	}

	/**
	 * @desc 不带参数的非查询操作，包括增、删、改操作
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public CoreReturnObject ExcuteNonQuery(String sql) throws SQLException {
		return this.ExcuteNonQuery(sql, null);
	}
	/**
	 * @desc 带参数的非查询操作，包括增、删、改操作
	 * @param sql 要执行的SQL语句
	 * @param args SQL语句所需要的参数，所有参数都存放在一个Object数组中
	 * @return
	 * @throws SQLException
	 */
	public CoreReturnObject ExcuteNonQuery(String sql, Object[] args) throws SQLException{
		CoreReturnObject cro = new CoreReturnObject();
		this.PrintSQL(sql, args);
		int count = 0;
		try {
			count = this.dbProxy.getJdbcTemplate().update(sql, args);	
		}catch (CoreException ce) {
			cro = CoreExceptionHandler.coreExceptionHandler(ce);
		}//catch (SQLException e) {
			//cro = CoreExceptionHandler.exceptionHandler(e);		
		//}
		cro.setResult(count);		
		return cro;
	}
	
	
	/**
	 * @desc 取得调存储过程的CallableStatement对象，使用完毕后请注意释放连接对象
	 * @param s
	 * @return
	 */
	public CallableStatement getCallableStatement(String s) {
		CallableStatement callablestatement = null;
		try {
			callablestatement = this.getConnection().prepareCall(s);
		} catch (Exception e) {
			try {
				// logger.info("不能够创建存储过程" + e.getMessage());
				throw new Exception("Can not create CallableStatement!! SQL ["
						+ s + "]", e);
			} catch (Exception ex) {
				try {
					callablestatement.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
				callablestatement = null;
				ex.printStackTrace();
			}
		}
		return callablestatement;
	}
	/**
	 * 调用无参数存储过程
	 * @param name
	 * @return
	 * @throws SQLException
	 */
	public CoreReturnObject ExcuteProcedure(String name) throws SQLException
	{
		ArrayList temp=new ArrayList();
		return this.ExcuteProcedure(name, temp, temp, temp, temp,temp);
	}
	/**
 * @description 调用存储过程方法
	 * @param name    存储过程名
	 * @param sqltypes 输入参数类型
	 * @param sqlparams 输入参数
	 * @return
	 * @throws SQLException
	 */
	public CoreReturnObject ExcuteProcedure(String name, ArrayList sqltypes,ArrayList sqlparams) throws SQLException
	{
		ArrayList temp=new ArrayList();
		return this.ExcuteProcedure(name, sqltypes, sqlparams, temp, temp,null);
	}
	/**
	 * @description 调用存储过程方法
	 * @param name    存储过程名
	 * @param sqltypes 输入参数类型
	 * @param sqlparams 输入参数
	 * @param outSqltypes 输出参数类型
	 * @param outparm   存放输出值
	 * @return
	 * @throws SQLException
	 */
	 
	public CoreReturnObject ExcuteProcedure(String name, ArrayList sqltypes,
			ArrayList sqlparams,ArrayList outSqltypes,ArrayList outparm) throws SQLException
	{		
		return this.ExcuteProcedure(name, sqltypes, sqlparams, outSqltypes, outparm, null);
	}
	/**
	 * @description 调用存储过程方法
	 * @param name    存储过程名
	 * @param sqltypes 输入参数类型
	 * @param sqlparams 输入参数
	 * @param outSqltypes 输出参数类型
	 * @param outparm   存放输出值
	 * @param cusTypeDB   当输出参数为数据库自定义的Type时，存放该Type名
	 * @return
	 * @throws SQLException
	 */
	
	public CoreReturnObject ExcuteProcedure(String name, ArrayList sqltypes,
			ArrayList sqlparams,ArrayList outSqltypes,ArrayList outparm,ArrayList cusTypeDB) throws SQLException {
		CoreReturnObject cro=new CoreReturnObject();
		int len=sqltypes.size()+outSqltypes.size();
		String query="";
		for(int i=0;i<len;i++)
		{	if(i==len-1)
		{
			query+="?";
		}else{
			query+="?,";
		}
		}	
		String sname="";
		if(query.equals(""))
		{
			sname="{call "+name+"}";
		}else
		{
			sname="{call "+name+"("+query+")}";
		}
		CallableStatement cstmt = null;
		Connection conn=null;
		try{
			try {				
				conn = this.dbProxy.getJdbcTemplate().getDataSource().getConnection();
				log.info("连接数据库成功！ " + conn);
			} catch (SQLException e) {				
				conn=null;
				throw (new CoreException("数据库连接失败 请检查网络或数据库配置文件..."));				
			}		
		cstmt = conn.prepareCall(sname);
		cro=this.setbatch(sqltypes, sqlparams, cstmt,outSqltypes,outparm,cusTypeDB);
		}catch(SQLException se)
		{
			throw se;
		}
		catch(Exception ex)
		{			
			log.debug(ex);
			ex.printStackTrace();
		}finally
		{
			try {
				if (cstmt != null) {
					cstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}
	
	public CoreReturnObject ExcuteProcedure(String name, String[] inparams,
			String[] outparams)throws SQLException {
		CoreReturnObject cro = new CoreReturnObject();
		CallableStatement cstmt = null;
		Connection conn=null;
		
		//cstmt = this.getCallableStatement(name);
		try {
			try {				
				conn = this.dbProxy.getJdbcTemplate().getDataSource()
						.getConnection();
				log.info("连接数据库成功！ " + conn);
			} catch (SQLException e) {				
				conn=null;
				throw (new CoreException("数据库连接失败 请检查网络或数据库配置文件..."));				
			}		
			cstmt=conn.prepareCall(name);
			if (cstmt != null) {
				// 设置输入变量
				for (int i = 0; i < inparams.length; i++) {
					cstmt.setString(i + 1, inparams[i]);
				}
				// 设置输出变量
				for (int i = 0, j = inparams.length + 1; i < outparams.length; i++, j++) {
					cstmt.registerOutParameter(j, Types.VARCHAR);
				}
				// 执行存储过程
				cstmt.execute();
				ArrayList outls = new ArrayList();
				for (int i = 0, j = inparams.length + 1; i < outparams.length; i++, j++) {
					outparams[i] = cstmt.getString(j);
					outls.add(outparams[i]);
				}
				cro.setResult(outls);
			}		
		}catch(SQLException se)
		{
			throw se;
		}
		catch (Exception e) {
			log.debug(e);
		} finally {
			try {
				if (cstmt != null) {
					cstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}
	/**
	 * 
	 * @param sql
	 * @return
	 */
	public PreparedStatement getPreparedStatement(String sql) {
		PreparedStatement pstmt = null;
		Connection conn = null;
		try {
			conn = this.getConnection();
			pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			try {
				pstmt.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			conn = null;
			e.printStackTrace();
		}
		return pstmt;
	}

	private CoreReturnObject setbatch(ArrayList lts, ArrayList lps,
			CallableStatement cstmt) {
		CoreReturnObject cro = new CoreReturnObject();
		// 如果是String类型
		try {
			if (cstmt != null) {
				ArrayList outMsgList = new ArrayList();
				CoreFS.SA06.CoreSqlType.CoreOracleType m;
				Object obj = null;
				int outbegin = 0;
				int cnt_out_begin = 0;
				for (int i = 0; i < lts.size(); i++) {
					int j = i + 1;
					m = (CoreOracleType) lts.get(i);
					obj = lps.get(i);
					if (m == CoreOracleType.STRING_TYPE) {
						// if (m == CoreSqlType.STRING_TYPE) {
						cstmt.setString(j, (String) obj);
					} else if (m == CoreOracleType.INTEGER_TYPE) {
						cstmt.setInt(j, (Integer) obj);
					} else if (m == CoreOracleType.FLOAT_TYPE) {
						cstmt.setFloat(j, (Float) obj);

					} else if (m == CoreOracleType.DOUBLE_TYPE) {
						cstmt.setDouble(j, (Double) obj);

					} else if (m == CoreOracleType.DATE_TYPE) {
						cstmt.setDate(j, (java.sql.Date) obj);

					} else if (m == CoreOracleType.TIME_TYPE) {
						cstmt.setTime(j, (Time) obj);

					} else if (m == CoreOracleType.TIMESTAMP_TYPE) {
						cstmt.setTimestamp(j, (Timestamp) obj);

					} else if (m == CoreOracleType.BLOB_TYPE) {
						this.dbProxy.getLobHandler().getLobCreator()
								.setBlobAsBytes(cstmt, j, (byte[]) obj);

						// cstmt.setBlob(i, (Blob) obj);
					} else if (m == CoreOracleType.CLOB_TYPE) {
						this.dbProxy.getLobHandler().getLobCreator()
								.setClobAsString(cstmt, j, (String) obj);

						// cstmt.setClob(i, (Clob) obj);
					} else if (m == CoreOracleType.BOOLEAN_TYPE) {
						cstmt.setBoolean(j, (Boolean) obj);

					} else if (m == CoreOracleType.BYTES_TYPE) {
						this.dbProxy.getLobHandler().getLobCreator()
								.setBlobAsBytes(cstmt, j, (byte[]) obj);

						// cstmt.setBytes(i, (byte[]) obj);
					} 
//					else if (m == CoreOracleType.STRING_OUT_TYPE) {
//						cstmt.registerOutParameter(j, Types.VARCHAR);
//						if (cnt_out_begin == 0) {
//							outbegin = j;
//							cnt_out_begin++;
//						}
//					}
				}
				cstmt.execute();
				for (int j = outbegin; outbegin <= lts.size(); outbegin++) {
					outMsgList.add(cstmt.getString(j));
				}
				cro.setResult(outMsgList);
			}
		} catch (CoreException ce) {
			cro = CoreExceptionHandler.coreExceptionHandler(ce);
		} catch (Exception e) {
			cro = CoreExceptionHandler.exceptionHandler(e);
		} finally {
			try {
				cstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cstmt = null;
		}
		return cro;	
	}
	
	
	
	
	private CoreReturnObject setbatch(ArrayList lts, ArrayList lps,
			CallableStatement cstmt,ArrayList outparm,ArrayList outty,ArrayList cusTypeDB) throws Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		// 如果是String类型
		try {
			if (cstmt != null) {
			//	ArrayList outMsgList = new ArrayList();
			//	CoreFS.SA06.CoreSqlType.CoreOracleType m;
				int m;
				//String mm;
				Object obj = null;
				int outbegin = 0;
				int cnt_out_begin = 0;
				for (int i = 0; i < lts.size(); i++) {
					int j = i + 1;
					//m=CoreOracleType.STRING_TYPE;
					//mm=(String) lts.get(i);
					m =Integer.parseInt(lts.get(i).toString());//(CoreOracleType) lts.get(i);
					obj = lps.get(i);
					if (m == CoreOracleType.STRING_TYPE.ordinal()) {
						// if (m == CoreSqlType.STRING_TYPE) {
						cstmt.setString(j, (String) obj);
					} else if (m == CoreOracleType.INTEGER_TYPE.ordinal()) {
						cstmt.setInt(j, (Integer) obj);
					} else if (m == CoreOracleType.FLOAT_TYPE.ordinal()) {
						cstmt.setFloat(j, (Float) obj);

					} else if (m == CoreOracleType.DOUBLE_TYPE.ordinal()) {
						cstmt.setDouble(j, (Double) obj);

					} else if (m == CoreOracleType.DATE_TYPE.ordinal()) {
						cstmt.setDate(j, (java.sql.Date) obj);

					} else if(m == CoreOracleType.TIME_TYPE.ordinal()) {
						cstmt.setTime(j, (Time) obj);

					} else if(m == CoreOracleType.TIMESTAMP_TYPE.ordinal()) {
						cstmt.setTimestamp(j, (Timestamp) obj);

					} else if(m == CoreOracleType.BLOB_TYPE.ordinal()) {
						this.dbProxy.getLobHandler().getLobCreator()
								.setBlobAsBytes(cstmt, j, (byte[]) obj);

						// cstmt.setBlob(i, (Blob) obj);
					} else if(m == CoreOracleType.CLOB_TYPE.ordinal()) {
						this.dbProxy.getLobHandler().getLobCreator()
								.setClobAsString(cstmt, j, (String) obj);

						// cstmt.setClob(i, (Clob) obj);
					} else if(m == CoreOracleType.BOOLEAN_TYPE.ordinal()) {
						cstmt.setBoolean(j, (Boolean) obj);

					} else if(m == CoreOracleType.BYTES_TYPE.ordinal()) {
						this.dbProxy.getLobHandler().getLobCreator()
								.setBlobAsBytes(cstmt, j, (byte[]) obj);

						// cstmt.setBytes(i, (byte[]) obj);
					} else if(m==CoreOracleType.ARRAY_TYPE.ordinal())
					{
						//cstmt.setObject(j, (Array)obj,Types.ARRAY);
						cstmt.setArray(j, (Array)obj);						
					}
//					else if (m == CoreOracleType.STRING_OUT_TYPE) {
//						cstmt.registerOutParameter(j, Types.VARCHAR);
//						if (cnt_out_begin == 0) {
//							outbegin = j;
//							cnt_out_begin++;
//						}
//					}
				}
				
				//输出参数
				int k=0;
				for (int i = 0, j = lts.size()+ 1; i < outparm.size(); i++, j++) {
					m =Integer.parseInt(outparm.get(i).toString()); //(CoreOracleType) outparm.get(i);					
					if(m == CoreOracleType.STRING_TYPE.ordinal()) {
						// if (m == CoreSqlType.STRING_TYPE) {
						cstmt.registerOutParameter(j, Types.VARCHAR);
					} else if(m == CoreOracleType.INTEGER_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.INTEGER);						
					} else if(m == CoreOracleType.FLOAT_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.FLOAT);

					} else if(m == CoreOracleType.DOUBLE_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.DOUBLE);

					} else if(m == CoreOracleType.DATE_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.DATE);

					} else if(m == CoreOracleType.TIME_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.TIME);

					} else if(m == CoreOracleType.TIMESTAMP_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.TIMESTAMP);
					} else if(m == CoreOracleType.BLOB_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.BLOB);

						// cstmt.setBlob(i, (Blob) obj);
					} else if(m == CoreOracleType.CLOB_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.CLOB);

						// cstmt.setClob(i, (Clob) obj);
					} else if(m == CoreOracleType.BOOLEAN_TYPE.ordinal()) {
						cstmt.registerOutParameter(j, Types.BOOLEAN);
					} else if(m==CoreOracleType.ARRAY_TYPE.ordinal())
					{
						String dtype=(String)cusTypeDB.get(k);						
						cstmt.registerOutParameter(j, Types.ARRAY,dtype.toUpperCase());
						k++;
					} else if(m==CoreOracleType.CURSOR_TYPE.ordinal())
					{											
						//cstmt.registerOutParameter(j, OracleTypes.CURSOR);						
					}
//					} else if (m == CoreOracleType.BTYES_TYPE) {
//						this.dbProxy.getLobHandler().getLobCreator()
//								.setBlobAsBytes(cstmt, j, (byte[]) obj);
//
//						// cstmt.setBytes(i, (byte[]) obj);
					
			//		cstmt.registerOutParameter(j, Types.VARCHAR);
				}
				cstmt.execute();				
				for (int i = 0, j = lts.size() + 1; i < outparm.size(); i++, j++) {
					m = Integer.parseInt(outparm.get(i).toString());//(CoreOracleType) outparm.get(i);					
					if (m == CoreOracleType.STRING_TYPE.ordinal()) {
						// if (m == CoreSqlType.STRING_TYPE) {
						outty.add(cstmt.getString(j));
					} else if (m == CoreOracleType.INTEGER_TYPE.ordinal()) {
						outty.add(cstmt.getInt(j));						
					} else if (m == CoreOracleType.FLOAT_TYPE.ordinal()) {
						outty.add(cstmt.getFloat(j));

					} else if (m == CoreOracleType.DOUBLE_TYPE.ordinal()) {
						outty.add(cstmt.getDouble(j));

					} else if(m == CoreOracleType.DATE_TYPE.ordinal()) {
						outty.add(cstmt.getDate(j));

					} else if(m == CoreOracleType.TIME_TYPE.ordinal()) {
						outty.add(cstmt.getTime(j));

					} else if (m == CoreOracleType.TIMESTAMP_TYPE.ordinal()) {
						outty.add(cstmt.getTimestamp(j));
					} else if(m == CoreOracleType.BLOB_TYPE.ordinal()) {
						outty.add(cstmt.getBlob(j));

						// cstmt.setBlob(i, (Blob) obj);
					} else if(m == CoreOracleType.CLOB_TYPE.ordinal()) {
						outty.add(cstmt.getClob(j));

						// cstmt.setClob(i, (Clob) obj);
					} else if(m == CoreOracleType.BOOLEAN_TYPE.ordinal()) {
						outty.add(cstmt.getBoolean(j));
					} else if(m==CoreOracleType.ARRAY_TYPE.ordinal())
					{	
						Array simpleArray=cstmt.getArray(j);
						String[] values=(String[])simpleArray.getArray();
						outty.add(values);
					}else if(m==CoreOracleType.CURSOR_TYPE.ordinal())					
					{
						ResultSet rs=(ResultSet)cstmt.getObject(j);
						List result=ConvertRsToList(rs);
						outty.add(result);
					}
				}
				cro.setResult(outty);
			}
		} catch (CoreException ce) {
			throw(ce);
			//cro = CoreExceptionHandler.coreExceptionHandler(ce);
		} catch (Exception e) {
			throw(e);
			//cro = CoreExceptionHandler.exceptionHandler(e);
		} finally {
			try {
				cstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cstmt = null;
		}
		return cro;	
		
	}
	/**
	 *@descrip 取数据库自定义类型的转为数组
	 * @param Oraclelist
	 * @param objlist
	 * @return
	 * @throws SQLException
	 */

	public Array getArray(String Oraclelist,ArrayList objlist) throws SQLException {
		Connection conn = null;
		try {
			conn = this.dbProxy.getJdbcTemplate().getDataSource()
					.getConnection();
			log.info("连接数据库成功！ " + conn);
		} catch (SQLException e) {
			conn = null;
			throw (new CoreException("数据库连接失败 请检查网络或数据库配置文件..."));
		}
		Object[] parm = objlist.toArray();
		Array list = null;
		try {
//			ArrayDescriptor desc = ArrayDescriptor.createDescriptor(Oraclelist.toUpperCase(),getNativeConnection(conn));
//			list = new ARRAY(desc, getNativeConnection(conn), parm);
		}catch(Exception ex)
		{
			ex.printStackTrace();
		} finally {
			conn.close();
		}
		return list;

	}
	
	private List ConvertRsToList(ResultSet rs)
	{
		List ls=new ArrayList();
		try {
			int clumncount = rs.getMetaData().getColumnCount();
			int columntype = 0;
			String columnname = "";
			while (rs.next()) {
				HashMap rowmap = new LinkedHashMap();
				// 构建行记录
				for (int i = 1; i <= clumncount; i++) {
					HashMap table = new HashMap();
					columntype = rs.getMetaData().getColumnType(i);
					columnname = rs.getMetaData().getColumnName(i);

					switch (columntype) {
					case Types.VARCHAR:
						table.put(columnname, (String) rs.getObject(i));
						break;
					case Types.NUMERIC:
						table.put(columnname, (Number) rs.getObject(i));
						break;
					case Types.BLOB:
						byte[] barry = this.dbProxy.getLobHandler()
								.getBlobAsBytes(rs, i);
						if (barry == null) {
							table.put(columnname, new byte[0]);
						} else {
							table.put(columnname, barry);
						}
						break;
					case Types.CLOB:
						table.put(columnname, this.dbProxy.getLobHandler()
								.getClobAsString(rs, i));
						break;
					case Types.INTEGER:
						table.put(columnname, (Integer) rs.getObject(i));
						break;
					case Types.DOUBLE:
						table.put(columnname, (Double) rs.getObject(i));
						break;
					case Types.FLOAT:
						table.put(columnname, (Float) rs.getObject(i));
						break;
					case Types.DATE:
						table.put(columnname, (Date) rs.getObject(i));
						break;
					default:
						throw (new CoreException("超出平台所定义的类型 ... "));
					}
					rowmap.putAll(table);
				}
				ls.add(rowmap);
			}
		} catch (Exception es) {
			log.debug(es.getMessage());
		}
		return ls;
	}
	/**
	 * 转换连接类型
	 * @param con
	 * @return
	 * @throws SQLException
	 */
	private static Connection getNativeConnection(Connection con) throws SQLException { 
//		  if (con instanceof DelegatingConnection) { 
//		   Connection nativeCon = ((DelegatingConnection) con).getInnermostDelegate(); 
//		   return (nativeCon != null ? nativeCon : con.getMetaData().getConnection()); 
//		  } 
		  return con; 
		} 
	/*
	 * 从数据库获取XML
	 */
	public String LoadXMLFromDB(String sql,String id) throws SQLException 
	{
		Connection conn=null;
		String xml="";
		//sql=(String)this.dbProxy.getJdbcTemplate().queryForObject(selSql, String.class);
		ResultSet rs = null;
		PreparedStatement stmt = null;
		try{
			try {				
				conn = this.dbProxy.getJdbcTemplate().getDataSource()
						.getConnection();
				log.info("连接数据库成功！ " + conn);
			} catch (SQLException e) {				
				conn=null;
				throw (new CoreException("数据库连接失败 请检查网络或数据库配置文件..."));				
			}		
		stmt = conn.prepareStatement(sql);//this.getPreparedStatement(sql);
		stmt.setString(1, id);
		rs = stmt.executeQuery();
		while(rs.next())
		{
			 xml=this.dbProxy.getLobHandler()
			.getClobAsString(rs, 1);
		}
		}catch(SQLException e)
		{
			throw e;		
		}finally
		{
			try {
				if (rs != null) {
					rs.close();
				}
				if(stmt!=null)
				{
					stmt.close();
				}
				if(conn!=null)
				{
					conn.close();					
				}
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
		}
		return xml;

	}
	
	/**
	 *@ 通过SQLID从数据库中提取对应SQL
	 *@表名为:core_app_sqldir
	 */
	//根据SqlID查找SQL获取SQL语句
	public String getSql(String SqlId)
	{
		
		String selSql="SELECT CONTENT,TYPE FROM PT4DEV_SQLDATA where ID='"+SqlId+"' AND MID='"+StringUtils.Sysid+"'";
		String sql="";	
		CoreReturnObject cro=new CoreReturnObject();
		try {
			cro=this.ExceuteQueryForBlobList(selSql);
			List sreuslt=(ArrayList)cro.getResult();
			if(sreuslt.size()==0)
			{
				throw (new CoreException("未找到SQLID:"+SqlId+"对应的SQL语句！请检查SQLID是否正确。"));
			}
			Iterator it= sreuslt.iterator();					
			while(it.hasNext())
			{
				Map rece = (Map) it.next();
				byte[] result=(byte[])rece.get("CONTENT");
				sql=new String(result);					
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();			
		}
		return sql;
	}
	
	private static String replacesql(String sql,String regex)
	{	
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(sql);		
			while (m.find()) {				
					sql = sql.replace(m.group(1), "");			
			}		
		//sql=sql.replaceAll(reg, "");
		return sql;
	}
	
	private void getPreparedSQL(String sql, Object[] params) {
		// 1 如果没有参数，说明是不是动态SQL语句
		int paramNum = 0;
		if (null != params)
			paramNum = params.length;
		if (1 > paramNum)
		{
			log.info("SQL---"+sql);
			return;
		}
		// 2 如果有参数，则是动态SQL语句
		StringBuffer returnSQL = new StringBuffer();
		String[] subSQL = sql.split("\\?");
		for (int i = 0; i < paramNum; i++) {
			if (params[i] instanceof java.util.Date) {
				// TO_DATE('2006-05-01 19:25:34', 'YYYY-MM-DD HH24:MI:SS')
				java.sql.Date dt = new java.sql.Date(
						((java.util.Date) params[i]).getDate());
				SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");// HH:MM:ss
				String time = tempDate.format((java.util.Date) params[i]);
				returnSQL.append(subSQL[i]).append(" to_date('").append(time)
						.append("','yyyy/mm/dd HH24:MI:SS')");// (MyDateUtil.dateUtil2SQL((java.util.Date)params[i])).append("' ");
			} else {
				returnSQL.append(subSQL[i]).append(" '").append(params[i])
						.append("' ");
			}
		}

		if (subSQL.length > params.length) {
			returnSQL.append(subSQL[subSQL.length - 1]);
		}
		log.info("SQL---"+returnSQL.toString());
	}

	
	/**
	 *@事务处理方法带参数，sqllist存放sql，parmlist存放sql参数 
	 */
	public CoreReturnObject ExcuteTransction(final ArrayList sqllist,final ArrayList<Object[]> parmlist)
	{
		CoreReturnObject cro = new CoreReturnObject();
		Object result=0;
	
		try {
			PlatformTransactionManager ptm = new DataSourceTransactionManager(this.dbProxy.getDataSource());
			TransactionTemplate tst = new TransactionTemplate(ptm);
			
			result=tst.execute(new TransactionCallback() {
				public Object doInTransaction(TransactionStatus status) {
					String sql="";
					Object[] args=null;
					for (int i = 0; i < sqllist.size(); i++) {
						sql=sqllist.get(i).toString();
						args=(Object[])parmlist.get(i);
						this.PrintSQL(sql, args);
						dbProxy.getJdbcTemplate().update(sql,args);	
					}
					return 1;
				}

				private void PrintSQL(String sql, Object[] args) {
					// TODO Auto-generated method stub
					String parm="";
					if (args != null) {
						parm="Sql Parameter is\n";
						for (int i = 0; i < args.length; i++) {
							parm = parm + "paramter[" + i + "]:" + args[i].toString()
									+ "\n";
						}
					}
					log.info("Excute SQL is\n"+sql+"\n"+parm+"------------------------------");						
				}			
			});
		} catch (Exception ce) {			
			log.debug(ce);
			cro=cro.SetErrInfo("事务处理失败");
		}
		cro.setResult(result);
		return cro;
	}
	/**
	 *@事务处理方法带参数，sqllist存放sql
	 */
	public CoreReturnObject ExcuteTransction(final ArrayList sqllist)
	{
		CoreReturnObject cro = new CoreReturnObject();
		Object result=0;
		try {
			PlatformTransactionManager ptm = new DataSourceTransactionManager(this.dbProxy.getDataSource());				
			TransactionTemplate tst = new TransactionTemplate(ptm);
			result=tst.execute(new TransactionCallback() {
				public Object doInTransaction(TransactionStatus status) {
					for (int i = 0; i < sqllist.size(); i++) {
							dbProxy.getJdbcTemplate().update(sqllist.get(i).toString());		
					}					
					return 1;
				}
			});
		} catch (Exception ce) {			
			log.debug(ce);
			cro=cro.SetErrInfo("事务处理失败");
		}	
		cro.setResult(result);
		return cro;
	}
	
	/**
	 * @desc 开始一个事务
	 * @return Map
	 */
	 
	public Map CoreBeginTranscation()
	{	
		Map<String,Object> result=new HashMap<String, Object>();
		DataSourceTransactionManager tran = new DataSourceTransactionManager(this.dbProxy.getDataSource()); 
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();//事务定义类 
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); 
		TransactionStatus status = tran.getTransaction(def);//返回事务对象 	
		result.put("tran", tran);
		result.put("status", status);
		return result;
	}
	/**
	 *@提交事务 
	 *@param Map类型 result
	 */
	public void CoreCommit(Map result)
	{
		DataSourceTransactionManager tran=(DataSourceTransactionManager)result.get("tran");
		TransactionStatus status=(TransactionStatus)result.get("status");
		tran.commit(status);		
	}
	/**
	 * @回滚事务 
	 * @param Map类型 result
	 */
	
	public void CoreRollBack(Map result)
	{
		DataSourceTransactionManager tran=(DataSourceTransactionManager)result.get("tran");
		TransactionStatus status=(TransactionStatus)result.get("status");		
		tran.rollback(status);			
	}
	/**
	 * @打印SQL及参数方法
	 * @param sql
	 * @param paramter
	 */
	private void PrintSQL(String sql,Object[] paramter)//
	{
		String parm="";
		if (paramter != null) {
			parm="Sql Parameter is\n";
			for (int i = 0; i < paramter.length; i++) {
				parm = parm + "paramter[" + i + "]:" + (paramter[i]==null?"":paramter[i].toString())
						+ "\n";
			}
		}
		log.info("Excute SQL is\n"+sql+"\n"+parm+"------------------------------");		
	}
	/**
	 * @连接池连接数查看方法
	 * @return
	 */	

	public CoreReturnObject ActiveConnectionNum()
	{		
		CoreReturnObject cro=new CoreReturnObject();
//		//Connection comm=this.getConnection();
//		// ApplicationContext context = new ClassPathXmlApplicationContext("springjndiConfig.xml"); 
//		BasicDataSource   ds= (BasicDataSource)this.dbProxy.getJdbcTemplate().getDataSource();
//		int Activenum=ds.getNumActive();
//		int IdleNum=ds.getNumIdle();
//		int MaxActive=ds.getMaxActive();
//		int MaxIdle=ds.getMaxIdle();
//		int MinIdel=ds.getMinIdle();
//		String result=Activenum+","+IdleNum+","+MaxActive+","+MaxIdle+","+MinIdel;
//		cro.setResult(result);
//		log.info("\n连接池中激活的连接数为："+Activenum+"\n允许最大并发数："+MaxActive+"\n 最大等待数： "+MaxIdle+"\n最小等待数:"+MinIdel+"\n空闲连接数："+IdleNum+"\n");
//		//System.out.println("连接池中激活的连接数为："+Activenum+"\n允许最大并发数："+MaxActive+"\n 最大等待数： "+MaxIdle+"\n最小等待数:"+MinIdel);
		return cro;
	}
	
	public static void main(String[] args) {
	  // CoreDBManager man = new CoreDBManager();
//		ResultSet rs = man.ExceuteQueryForResultSet("select * from emp t");
		//System.out.println(this.getSql("1111"));
		

	
	}  
}
