1 53 54 55 package com.Yasna.forum.database; 56 import java.sql.*; 57 import com.Yasna.forum.*; 58 59 import javax.sql.DataSource ; 60 import javax.naming.InitialContext ; 61 62 66 public class DbConnectionManager { 67 68 private static DbConnectionProvider connectionProvider; 69 private static Object providerLock = new Object (); 70 private static boolean AppServerPooler = false; 71 private static boolean checkedPooler = false; 72 private static DataSource appServerSource; 73 public static final String CONTEXT_JDBC_NAME=SystemProperty.getProperty("JNDI.dataprovider"); 74 75 79 public static Connection getConnection() { 80 Connection con=null; 81 if (appServerSource == null && !checkedPooler){ 82 checkedPooler=true; 83 try{ 84 InitialContext ctxt = new InitialContext (); 85 appServerSource = (DataSource )ctxt.lookup(CONTEXT_JDBC_NAME); 86 AppServerPooler=true; 87 System.err.println("Yazd got a connection provider from app server ("+CONTEXT_JDBC_NAME+")"); 88 }catch(Exception e){ 89 System.err.println("Failed to find an application datasource ("+CONTEXT_JDBC_NAME+"): "+e.getMessage()); 90 } 91 } 92 if (connectionProvider == null && !AppServerPooler) { 93 synchronized (providerLock) { 94 if (connectionProvider == null) { 95 String className = 98 PropertyManager.getProperty("connectionProvider.className"); 99 if (className != null) { 100 try { 102 Class conClass = Class.forName(className); 103 connectionProvider = (DbConnectionProvider)conClass.newInstance(); 104 } 105 catch(Exception e) { 106 System.err.println("Warning: failed to create the " + 107 "connection provider specified by connection" + 108 "Provider.className. Using the default pool."); 109 connectionProvider = new DbConnectionDefaultPool(); 110 } 111 } 112 else { 113 connectionProvider = new DbConnectionDefaultPool(); 114 } 115 connectionProvider.start(); 116 } 117 } 118 } 119 if(AppServerPooler){ 120 try{ 121 con = appServerSource.getConnection (); 122 }catch(Exception e){ 123 System.err.println("There was a problem obtaining a connection from application server :"+e.getMessage()); 124 } 125 }else{ 126 con = connectionProvider.getConnection(); 127 } 128 if (con == null) { 129 System.err.println("WARNING: DbConnectionManager.getConnection() " + 130 "failed to obtain a connection."); 131 } 132 return con; 133 } 134 135 141 public static DbConnectionProvider getDbConnectionProvider() { 142 return connectionProvider; 143 } 144 145 151 public static void setDbConnectionProvider(DbConnectionProvider provider) { 152 synchronized (providerLock) { 153 if (connectionProvider != null) { 154 connectionProvider.destroy(); 155 connectionProvider = null; 156 } 157 connectionProvider = provider; 158 provider.start(); 159 } 160 } 161 162 163 } 164 | Popular Tags |