This project has retired. For details please refer to its Attic page.
DatabaseWriter xref
View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.chukwa.util;
20  
21  import java.sql.SQLException;
22  import java.sql.Connection;
23  import java.sql.Statement;
24  import java.sql.PreparedStatement;
25  import java.sql.ResultSet;
26  import java.util.List;
27  import java.text.SimpleDateFormat;
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  
31  public class DatabaseWriter {
32    private static Log log = LogFactory.getLog(DatabaseWriter.class);
33    private Connection conn = null;
34    private Statement stmt = null;
35    private PreparedStatement pstmt = null;
36    private ResultSet rs = null;
37  
38    public DatabaseWriter(String host, String user, String password) {
39      String jdbc_url = "jdbc:mysql://" + host + "/";
40      if (user != null) {
41        jdbc_url = jdbc_url + "?user=" + user;
42        if (password != null) {
43          jdbc_url = jdbc_url + "&password=" + password;
44        }
45      }
46      try {
47        // The newInstance() call is a work around for some
48        // broken Java implementations
49        DriverManagerUtil.loadDriver().newInstance();
50      } catch (Exception ex) {
51        // handle the error
52        log.error(ex, ex);
53      }
54      try {
55        conn = org.apache.hadoop.chukwa.util.DriverManagerUtil.getConnection(jdbc_url);
56        log.debug("Initialized JDBC URL: " + jdbc_url);
57      } catch (SQLException ex) {
58        log.error(ex, ex);
59      }
60    }
61  
62    public DatabaseWriter(String cluster) {
63      ClusterConfig cc = new ClusterConfig();
64      String jdbc_url = cc.getURL(cluster);
65      try {
66        // The newInstance() call is a work around for some
67        // broken Java implementations
68        DriverManagerUtil.loadDriver().newInstance();
69      } catch (Exception ex) {
70        // handle the error
71        log.error(ex, ex);
72      }
73      try {
74        conn = org.apache.hadoop.chukwa.util.DriverManagerUtil.getConnection(jdbc_url);
75        log.debug("Initialized JDBC URL: " + jdbc_url);
76      } catch (SQLException ex) {
77        log.error(ex, ex);
78      }
79    }
80  
81    public void execute(String query) throws SQLException {
82      try {
83        stmt = conn.createStatement();
84        stmt.execute(query);
85      } catch (SQLException ex) {
86        // handle any errors
87        log.error(ex, ex);
88        log.error("SQL Statement:" + query);
89        log.error("SQLException: " + ex.getMessage());
90        log.error("SQLState: " + ex.getSQLState());
91        log.error("VendorError: " + ex.getErrorCode());
92        throw ex;
93      } finally {
94        if (stmt != null) {
95          try {
96            stmt.close();
97          } catch (SQLException sqlEx) {
98            // ignore
99            log.debug(ExceptionUtil.getStackTrace(sqlEx));
100         }
101         stmt = null;
102       }
103     }
104   }
105 
106   public Connection getConnection() {
107     return conn;
108   }
109 
110   public ResultSet query(String query, List<Object> parameters) throws SQLException {
111     try {
112       pstmt = conn.prepareStatement(query);
113       for(int i=0;i<parameters.size();i++) {
114         int index = i+1;
115         pstmt.setObject(index,parameters.get(i));
116       }
117       rs = pstmt.executeQuery();
118     } catch (SQLException ex) {
119       // handle any errors
120       //only log at debug level because caller will still see exception
121       log.debug(ex, ex);
122       log.debug("SQL Statement:" + query);
123       log.debug("SQLException: " + ex.getMessage());
124       log.debug("SQLState: " + ex.getSQLState());
125       log.debug("VendorError: " + ex.getErrorCode());
126       throw ex;
127     }
128     return rs;
129   }
130 
131   public ResultSet query(String query) throws SQLException {
132     try {
133       stmt = conn.createStatement();
134       rs = stmt.executeQuery(query);
135     } catch (SQLException ex) {
136       // handle any errors
137       //only log at debug level because caller will still see exception
138       log.debug(ex, ex);
139       log.debug("SQL Statement:" + query);
140       log.debug("SQLException: " + ex.getMessage());
141       log.debug("SQLState: " + ex.getSQLState());
142       log.debug("VendorError: " + ex.getErrorCode());
143       throw ex;
144     }
145     return rs;
146   }
147 
148   public void close() {
149     // it is a good idea to release
150     // resources in a finally{} block
151     // in reverse-order of their creation
152     // if they are no-longer needed
153     if (rs != null) {
154       try {
155         rs.close();
156       } catch (SQLException sqlEx) {
157         // ignore
158         log.debug(ExceptionUtil.getStackTrace(sqlEx));
159       }
160       rs = null;
161     }
162     if (stmt != null) {
163       try {
164         stmt.close();
165       } catch (SQLException sqlEx) {
166         // ignore
167         log.debug(ExceptionUtil.getStackTrace(sqlEx));
168       }
169       stmt = null;
170     }
171     if (conn != null) {
172       try {
173         conn.close();
174       } catch (SQLException sqlEx) {
175         // ignore
176         log.debug(ExceptionUtil.getStackTrace(sqlEx));
177       }
178       conn = null;
179     }
180   }
181 
182   public static String formatTimeStamp(long timestamp) {
183     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
184     String format = formatter.format(timestamp);
185 
186     return format;
187   }
188 }