1 package org.jzonic.jlo.handler; 2 3 import org.jzonic.jlo.LogRecord; 4 import org.jzonic.jlo.error.ErrorHandler; 5 import org.jzonic.jlo.formatter.tokens.TokenParser; 6 7 import java.util.Map ; 8 import java.sql.Connection ; 9 import java.sql.DriverManager ; 10 import java.sql.SQLException ; 11 import java.sql.Statement ; 12 13 18 public class JDBCHandler extends AbstractHandler { 19 20 private String insertSQL; 21 private TokenParser tp = new TokenParser(); 22 private Connection con; 23 private String jdbcDriver; 24 private String jdbcURL; 25 private String jdbcUser; 26 private String jdbcPassword; 27 28 public JDBCHandler(String configName) { 29 super(configName); 30 } 31 32 public void publish(String msg) { 33 throw new UnsupportedOperationException ("no supported"); 34 } 35 36 public Connection getConnection() { 37 try { 38 Class.forName(jdbcDriver); 39 } 40 catch (Exception e) { 41 ErrorHandler.reportError("Could not load driver", e); 42 } 43 try { 44 if ( con == null) { 45 con = DriverManager.getConnection(jdbcURL, jdbcUser,jdbcPassword); 46 } 47 return con; 48 } 49 catch (Exception e) { 50 ErrorHandler.reportError("Error while establishing connection", e); 51 } 52 return null; 53 } 54 55 public void closeConnection(Connection con) { 56 } 57 58 public void publish(LogRecord lr) { 59 String sql = tp.parseLine(lr,insertSQL); 61 Connection con = null; 63 try { 64 con = getConnection(); 65 if ( con != null ) { 66 Statement stmt = con.createStatement(); 67 stmt.executeUpdate(sql); 68 stmt.close(); 69 } 70 } 71 catch (SQLException e) { 72 ErrorHandler.reportError("Error while running insert query", e); 73 } 74 closeConnection(con); 75 } 76 77 public void setParameter(Map parameters) { 78 if ( parameters.containsKey("sql")) { 79 insertSQL = (String )parameters.get("sql"); 80 } 81 if ( parameters.containsKey("user")) { 82 jdbcUser = (String )parameters.get("user"); 83 } 84 if ( parameters.containsKey("password")) { 85 jdbcPassword = (String )parameters.get("password"); 86 } 87 if ( parameters.containsKey("driver")) { 88 jdbcDriver = (String )parameters.get("driver"); 89 } 90 if ( parameters.containsKey("url")) { 91 jdbcURL = (String )parameters.get("url"); 92 } 93 } 94 95 } 96 | Popular Tags |