1 29 30 package com.caucho.jdbc; 31 32 import com.caucho.util.L10N; 33 import com.caucho.util.Log; 34 35 import javax.naming.Context ; 36 import javax.naming.InitialContext ; 37 import javax.naming.NamingException ; 38 import javax.sql.DataSource ; 39 import java.sql.Connection ; 40 import java.sql.SQLException ; 41 import java.util.HashMap ; 42 import java.util.logging.Level ; 43 import java.util.logging.Logger ; 44 45 48 public class ConnectionContext { 49 private static final L10N L = new L10N(ConnectionContext.class); 50 private static final Logger log = Log.open(ConnectionContext.class); 51 52 private static InitialContext _initialContext; 53 54 private static ThreadLocal <HashMap <String ,ConnectionContext>> _localConn 55 = new ThreadLocal <HashMap <String ,ConnectionContext>>(); 56 57 private int _depth; 58 private Connection _conn; 59 60 public static void begin(String jndiName) 61 { 62 HashMap <String ,ConnectionContext> map = _localConn.get(); 63 64 if (map == null) { 65 map = new HashMap <String ,ConnectionContext>(8); 66 67 _localConn.set(map); 68 } 69 70 ConnectionContext cxt = map.get(jndiName); 71 72 if (cxt == null) { 73 cxt = new ConnectionContext(); 74 75 map.put(jndiName, cxt); 76 } 77 78 cxt._depth++; 79 } 80 81 public static Connection getConnection(String jndiName) 82 throws SQLException 83 { 84 HashMap <String ,ConnectionContext> map = _localConn.get(); 85 86 if (map == null) 87 throw new IllegalStateException (L.l("'{0}' is not an available connection.", 88 jndiName)); 89 90 ConnectionContext cxt = map.get(jndiName); 91 92 if (cxt == null || cxt._depth == 0) 93 throw new IllegalStateException (L.l("'{0}' is not an available connection.", 94 jndiName)); 95 96 if (cxt._conn == null) { 97 try { 98 DataSource ds = (DataSource ) _initialContext.lookup(jndiName); 99 100 cxt._conn = ds.getConnection(); 101 } catch (NamingException e) { 102 throw new IllegalStateException (e); 103 } 104 } 105 106 return null; 107 } 108 109 public static void end(String jdbcName) 110 { 111 HashMap <String ,ConnectionContext> map = _localConn.get(); 112 113 if (map == null) 114 return; 115 116 ConnectionContext cxt = map.get(jdbcName); 117 118 if (cxt == null) 119 return; 120 121 if (--cxt._depth == 0) { 122 Connection conn = cxt._conn; 123 124 try { 125 cxt._conn = null; 126 conn.close(); 127 } catch (SQLException e) { 128 log.log(Level.FINE, e.toString(), e); 129 } 130 } 131 } 132 133 private static Context getInitialContext() 134 { 135 if (_initialContext == null) { 136 try { 137 _initialContext = new InitialContext (); 138 } catch (NamingException e) { 139 } 140 } 141 142 return _initialContext; 143 } 144 } 145 | Popular Tags |