| 1 package com.tdsecurities.itracker.common; 2 3 import java.sql.Connection ; 4 import java.sql.ResultSet ; 5 import java.sql.Statement ; 6 import java.util.Hashtable ; 7 8 import javax.naming.Context ; 9 import javax.naming.InitialContext ; 10 import javax.naming.NamingException ; 11 import javax.sql.DataSource ; 12 13 import org.apache.log4j.Logger; 14 15 17 public class DataSourceManager 18 { 19 protected final Logger log = Logger.getLogger(DataSourceManager.class); 20 21 public static final String ITRACKER = "java:/ITrackerDS"; 22 public static final String SOURCEFORGE = "java:/SourceForgeDS"; 23 24 private Hashtable sources = new Hashtable (); 25 private static DataSourceManager singletion; 26 27 static { 28 singletion = new DataSourceManager(); 29 } 30 31 static public DataSourceManager getInstance() 32 { 33 return singletion; 34 } 35 36 private DataSourceManager() 37 { 38 try 39 { 40 Context context = new InitialContext (); 41 sources.put( ITRACKER, context.lookup(ITRACKER)); 42 sources.put( SOURCEFORGE, context.lookup(SOURCEFORGE)); 43 } 44 catch (NamingException ne) 45 { 46 log.error( 47 "NamingException caught while trying to instantiate DataSourceManager.", 48 ne); 49 throw new Error (ne); 50 } 51 } 52 53 public Connection getConnection(String dataSourceName) 54 { 55 Connection conn = null; 56 try 57 { 58 DataSource ds = (DataSource ) sources.get(dataSourceName); 59 conn = ds.getConnection(); 60 } 61 catch (Throwable t) 62 { 63 log.error("Cannot establish a database connection to " + dataSourceName, t); 64 } 65 return conn; 66 } 67 68 public void cleanup( 69 Connection connection, 70 Statement statement, 71 ResultSet resultSet) 72 { 73 closeResultSet(resultSet); 74 if (statement != null) 75 { 76 try 77 { 78 statement.close(); 79 } 80 catch (Exception e) 81 { 82 log.warn("Problem closing Statement object.", e); 83 } 84 } 85 statement = null; 86 closeConnection(connection); 87 } 88 89 private void closeResultSet(ResultSet resultSet) 90 { 91 if (resultSet != null) 92 { 93 try 94 { 95 resultSet.close(); 96 } 97 catch (Exception e) 98 { 99 log.warn("Problem closing ResultSet object.", e); 100 } 101 } 102 resultSet = null; 103 } 104 105 private void closeConnection(Connection connection) 106 { 107 if (connection != null) 108 { 109 try 110 { 111 connection.close(); 112 } 113 catch (Exception e) 114 { 115 log.warn("Problem closing Connection object.", e); 116 } 117 } 118 connection = null; 119 } 120 } 121 | Popular Tags |