01: package org.jzonic.jlo.handler;
02:
03: import org.jzonic.jlo.LogRecord;
04: import org.jzonic.jlo.error.ErrorHandler;
05: import org.jzonic.jlo.formatter.tokens.TokenParser;
06:
07: import java.util.Map;
08: import java.sql.Connection;
09: import java.sql.DriverManager;
10: import java.sql.SQLException;
11: import java.sql.Statement;
12:
13: /**
14: * @author Andreas Mecky andreas.mecky@xcom.de
15: * @author Terry Dye terry.dye@xcom.de
16: *
17: */
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: } catch (Exception e) {
40: ErrorHandler.reportError("Could not load driver", e);
41: }
42: try {
43: if (con == null) {
44: con = DriverManager.getConnection(jdbcURL, jdbcUser,
45: jdbcPassword);
46: }
47: return con;
48: } catch (Exception e) {
49: ErrorHandler.reportError(
50: "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: // get the sql command
60: String sql = tp.parseLine(lr, insertSQL);
61: // execute sql
62: 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: } catch (SQLException e) {
71: ErrorHandler.reportError(
72: "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: }
|