1 17 package org.apache.log.output.db; 18 19 import java.sql.Connection ; 20 import java.sql.SQLException ; 21 import javax.sql.DataSource ; 22 import org.apache.log.LogEvent; 23 import org.apache.log.output.AbstractTarget; 24 25 31 public abstract class AbstractJDBCTarget 32 extends AbstractTarget 33 { 34 private DataSource m_dataSource; 36 37 private Connection m_connection; 39 40 44 protected AbstractJDBCTarget( final DataSource dataSource ) 45 { 46 m_dataSource = dataSource; 47 } 48 49 55 protected synchronized void doProcessEvent( final LogEvent event ) 56 throws Exception 57 { 58 checkConnection(); 59 60 if( isOpen() ) 61 { 62 output( event ); 63 } 64 } 65 66 72 protected abstract void output( LogEvent event ); 73 74 78 protected synchronized void open() 79 { 80 if( !isOpen() ) 81 { 82 super.open(); 83 openConnection(); 84 } 85 } 86 87 91 protected synchronized void openConnection() 92 { 93 try 94 { 95 m_connection = m_dataSource.getConnection(); 96 } 97 catch( final Throwable throwable ) 98 { 99 getErrorHandler().error( "Unable to open connection", throwable, null ); 100 } 101 } 102 103 108 protected final synchronized Connection getConnection() 109 { 110 return m_connection; 111 } 112 113 116 protected final synchronized void checkConnection() 117 { 118 if( isStale() ) 119 { 120 closeConnection(); 121 openConnection(); 122 } 123 } 124 125 130 protected synchronized boolean isStale() 131 { 132 if( null == m_connection ) 133 { 134 return true; 135 } 136 137 try 138 { 139 if( m_connection.isClosed() ) 140 { 141 return true; 142 } 143 } 144 catch( final SQLException se ) 145 { 146 return true; 147 } 148 149 return false; 150 } 151 152 157 public synchronized void close() 158 { 159 if( isOpen() ) 160 { 161 closeConnection(); 162 super.close(); 163 } 164 } 165 166 170 protected synchronized void closeConnection() 171 { 172 if( null != m_connection ) 173 { 174 try 175 { 176 m_connection.close(); 177 } 178 catch( final SQLException se ) 179 { 180 getErrorHandler().error( "Error shutting down JDBC connection", se, null ); 181 } 182 183 m_connection = null; 184 } 185 } 186 } 187 | Popular Tags |