1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.backsource.alert.agent;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24
25 import org.backsource.alert.PropertyConstants;
26 import org.backsource.alert.AlertError;
27
28 import java.sql.*;
29
30 /***
31 * Execute a SQL query test.
32 *
33 * The test will succed if all the following conditions are true:
34 *
35 * <ul>
36 * <li>The database driver can be loaded</li>
37 * <li>A connection can be established</li>
38 * <li>The query executes without an error</li>
39 * <li>Atleast one row is returned</li>
40 * <li>The first column of the first row can be interpreted as boolean TRUE</li>
41 * </ul>
42 *
43 * @author <a href="mailto:jens.askengren@tim.se">Jens Askengren</a>
44 * @version $Id: SQLTest.java,v 1.1.1.1 2004/05/19 12:33:41 pra Exp $
45 */
46 public class SQLTest
47 extends BaseCase
48 {
49 static final Log log = LogFactory.getLog(SQLTest.class);
50
51 String user;
52 String pass;
53 String driver;
54 String url;
55 String query;
56
57 public SQLTest (String name)
58 {
59 super(name);
60 }
61
62 protected void setUp()
63 throws Exception
64 {
65 super.setUp();
66 query = prop.getProperty(PropertyConstants.SQL_QUERY);
67 user = prop.getProperty(PropertyConstants.SQL_USER);
68 pass = prop.getProperty(PropertyConstants.SQL_PASS);
69 driver = prop.getProperty(PropertyConstants.SQL_DRIVER);
70 url = prop.getProperty(PropertyConstants.SQL_URL);
71 }
72
73
74 public void testQuery()
75 {
76 Connection con = null;
77 try {
78 Class.forName(driver);
79 con = DriverManager.getConnection(url, user, pass);
80
81 executeSQL(con);
82
83 } catch (ClassNotFoundException e) {
84 throw new AlertError("Could load the database driver class " + driver + ": " + e.getMessage());
85 } catch (SQLException e) {
86 throw new AlertError("Could not connect to database " + url + ": " + e.getMessage());
87 } finally {
88 try { con.close(); } catch (Exception e){}
89 }
90 }
91
92 protected void executeSQL(Connection con)
93 throws AlertError
94 {
95 PreparedStatement pst = null;
96 ResultSet r = null;
97 try {
98 pst = con.prepareStatement(query);
99 r = pst.executeQuery();
100
101 if (r.next()) {
102 Object o = r.getObject(1);
103 if (o.equals(Boolean.FALSE)) {
104 throw new AlertError("Query \"" + query + "\" returned FALSE");
105 }
106 } else {
107 throw new AlertError("Query returned no results");
108 }
109
110 } catch (SQLException e) {
111 throw new AlertError("Query \"" + query + "\" failed: " + e.getMessage());
112 } finally {
113 try { r.close(); } catch (Exception e) {}
114 try { pst.close(); } catch (Exception e) {}
115 }
116 }
117
118 }