1 22 package org.jboss.resource.adapter.jdbc.vendor; 23 24 import java.io.Serializable ; 25 import java.lang.reflect.Method ; 26 import java.sql.Connection ; 27 import java.sql.SQLException ; 28 import java.sql.Statement ; 29 import java.sql.ResultSet ; 30 31 import org.jboss.logging.Logger; 32 import org.jboss.resource.adapter.jdbc.ValidConnectionChecker; 33 34 45 public class MySQLValidConnectionChecker implements ValidConnectionChecker, Serializable { 46 47 48 private static final Logger log = Logger.getLogger(MySQLValidConnectionChecker.class); 49 50 private static final long serialVersionUID = -2227528634302168878L; 51 52 private Method ping; 53 54 private boolean driverHasPingMethod = false; 55 56 private static Object [] params = new Object [] {}; 58 59 public MySQLValidConnectionChecker() 60 { 61 try 62 { 63 Class mysqlConnection = Thread.currentThread().getContextClassLoader().loadClass("com.mysql.jdbc.Connection"); 64 ping = mysqlConnection.getMethod("ping", new Class [] 65 {}); 66 if (ping != null) 67 { 68 driverHasPingMethod = true; 69 } 70 } 71 catch (Exception e) 72 { 73 log.warn("Cannot resolve com.mysq.jdbc.Connection.ping method. Will use 'SELECT 1' instead.", e); 74 } 75 } 76 77 public SQLException isValidConnection(Connection c) 78 { 79 if (driverHasPingMethod) 81 { 82 try 83 { 84 ping.invoke(c, params); 85 } 86 catch (Exception e) 87 { 88 if (e instanceof SQLException ) 89 { 90 return (SQLException ) e; 91 } 92 else 93 { 94 log.warn("Unexpected error in ping", e); 95 return new SQLException ("ping failed: " + e.toString()); 96 } 97 } 98 99 } 100 else 101 { 102 103 Statement stmt = null; 104 ResultSet rs = null; 105 try 106 { 107 stmt = c.createStatement(); 108 rs = stmt.executeQuery("SELECT 1"); 109 } 110 catch (Exception e) 111 { 112 if (e instanceof SQLException ) 113 { 114 return (SQLException ) e; 115 } 116 else 117 { 118 log.warn("Unexpected error in ping (SELECT 1)", e); 119 return new SQLException ("ping (SELECT 1) failed: " + e.toString()); 120 } 121 } 122 finally 123 { 124 try 126 { 127 if (rs != null) 128 rs.close(); 129 130 if (stmt != null) 131 stmt.close(); 132 } 133 catch (SQLException ignore) 134 { 135 136 } 137 } 138 139 } 140 return null; 141 } 142 } 143 | Popular Tags |