1 16 17 package org.springframework.jdbc.support; 18 19 import java.sql.Connection ; 20 import java.sql.SQLException ; 21 import java.sql.Statement ; 22 23 import javax.sql.DataSource ; 24 25 import org.apache.commons.logging.Log; 26 import org.apache.commons.logging.LogFactory; 27 28 import org.springframework.beans.factory.InitializingBean; 29 import org.springframework.jdbc.CannotGetJdbcConnectionException; 30 31 42 public class DatabaseStartupValidator implements InitializingBean { 43 44 public static final int DEFAULT_INTERVAL = 1; 45 46 public static final int DEFAULT_TIMEOUT = 60; 47 48 49 protected final Log logger = LogFactory.getLog(getClass()); 50 51 private DataSource dataSource; 52 53 private String validationQuery; 54 55 private int interval = DEFAULT_INTERVAL; 56 57 private int timeout = DEFAULT_TIMEOUT; 58 59 60 63 public void setDataSource(DataSource dataSource) { 64 this.dataSource = dataSource; 65 } 66 67 70 public void setValidationQuery(String validationQuery) { 71 this.validationQuery = validationQuery; 72 } 73 74 78 public void setInterval(int interval) { 79 this.interval = interval; 80 } 81 82 86 public void setTimeout(int timeout) { 87 this.timeout = timeout; 88 } 89 90 91 96 public void afterPropertiesSet() { 97 if (this.dataSource == null) { 98 throw new IllegalArgumentException ("dataSource is required"); 99 } 100 if (this.validationQuery == null) { 101 throw new IllegalArgumentException ("validationQuery is required"); 102 } 103 104 boolean validated = false; 105 long beginTime = System.currentTimeMillis(); 106 long deadLine = beginTime + this.timeout * 1000; 107 SQLException latestEx = null; 108 109 while (!validated && System.currentTimeMillis() < deadLine) { 110 Connection con = null; 111 Statement stmt = null; 112 try { 113 con = this.dataSource.getConnection(); 114 stmt = con.createStatement(); 115 stmt.execute(this.validationQuery); 116 validated = true; 117 } 118 catch (SQLException ex) { 119 latestEx = ex; 120 logger.debug("Validation query [" + this.validationQuery + "] threw exception", ex); 121 float rest = ((float) (deadLine - System.currentTimeMillis())) / 1000; 122 if (rest > this.interval) { 123 logger.warn("Database has not started up yet - retrying in " + this.interval + 124 " seconds (timeout in " + rest + " seconds)"); 125 } 126 } 127 finally { 128 JdbcUtils.closeStatement(stmt); 129 JdbcUtils.closeConnection(con); 130 } 131 132 try { 133 Thread.sleep(this.interval * 1000); 134 } 135 catch (InterruptedException ex) { 136 Thread.currentThread().interrupt(); 138 } 139 } 140 141 if (validated) { 142 float duration = (System.currentTimeMillis() - beginTime) / 1000; 143 if (logger.isInfoEnabled()) { 144 logger.info("Database startup detected after " + duration + " seconds"); 145 } 146 } 147 else { 148 throw new CannotGetJdbcConnectionException( 149 "Database has not started up within " + this.timeout + " seconds", latestEx); 150 } 151 } 152 153 } 154 | Popular Tags |