KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibatis > common > jdbc > ScriptRunner


1 /*
2  * Copyright 2004 Clinton Begin
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.ibatis.common.jdbc;
17
18 import com.ibatis.common.resources.Resources;
19
20 import java.io.IOException JavaDoc;
21 import java.io.LineNumberReader JavaDoc;
22 import java.io.PrintWriter JavaDoc;
23 import java.io.Reader JavaDoc;
24 import java.sql.*;
25 import java.util.Map JavaDoc;
26
27 /**
28  * Tool to run database scripts
29  * @deprecated There are better tools available for running scripts. This
30  * class has become out of scope for iBATIS.
31  */

32 public class ScriptRunner {
33
34   //private static final Log log = LogFactory.getLog(ScriptRunner.class);
35

36
37   private String JavaDoc driver;
38   private String JavaDoc url;
39   private String JavaDoc username;
40   private String JavaDoc password;
41   private boolean stopOnError;
42   private boolean autoCommit;
43   private PrintWriter JavaDoc logWriter = new PrintWriter JavaDoc(System.out);
44   private PrintWriter JavaDoc errorLogWriter = new PrintWriter JavaDoc(System.err);
45
46   /**
47    * Default constructor
48    */

49   public ScriptRunner() {
50     stopOnError = false;
51     autoCommit = false;
52   }
53
54   /**
55    * Constructor to allow passing in a Map with configuration data
56    *
57    * @param props - the configuration properties
58    */

59   public ScriptRunner(Map JavaDoc props) {
60     setDriver((String JavaDoc) props.get("driver"));
61     setUrl((String JavaDoc) props.get("url"));
62     setUsername((String JavaDoc) props.get("username"));
63     setPassword((String JavaDoc) props.get("password"));
64     setStopOnError("true".equals(props.get("stopOnError")));
65     setAutoCommit("true".equals(props.get("autoCommit")));
66   }
67
68   /**
69    * Getter for stopOnError property
70    *
71    * @return The value of the stopOnError property
72    */

73   public boolean isStopOnError() {
74     return stopOnError;
75   }
76
77   /**
78    * Setter for stopOnError property
79    *
80    * @param stopOnError - the new value of the stopOnError property
81    */

82   public void setStopOnError(boolean stopOnError) {
83     this.stopOnError = stopOnError;
84   }
85
86   /**
87    * Getter for autoCommit property
88    *
89    * @return The value of the autoCommit property
90    */

91   public boolean isAutoCommit() {
92     return autoCommit;
93   }
94
95   /**
96    * Setter for autoCommit property
97    *
98    * @param autoCommit - the new value of the autoCommit property
99    */

100   public void setAutoCommit(boolean autoCommit) {
101     this.autoCommit = autoCommit;
102   }
103
104   /**
105    * Getter for logWriter property
106    *
107    * @return The value of the logWriter property
108    */

109   public PrintWriter JavaDoc getLogWriter() {
110     return logWriter;
111   }
112
113   /**
114    * Setter for logWriter property
115    *
116    * @param logWriter - the new value of the logWriter property
117    */

118   public void setLogWriter(PrintWriter JavaDoc logWriter) {
119     this.logWriter = logWriter;
120   }
121
122   /**
123    * Getter for errorLogWriter property
124    *
125    * @return The value of the errorLogWriter property
126    */

127   public PrintWriter JavaDoc getErrorLogWriter() {
128     return errorLogWriter;
129   }
130
131   /**
132    * Setter for errorLogWriter property
133    *
134    * @param errorLogWriter - the new value of the errorLogWriter property
135    */

136   public void setErrorLogWriter(PrintWriter JavaDoc errorLogWriter) {
137     this.errorLogWriter = errorLogWriter;
138   }
139
140   /**
141    * Getter for driver property
142    *
143    * @return The value of the driver property
144    */

145   public String JavaDoc getDriver() {
146     return driver;
147   }
148
149   /**
150    * Setter for driver property
151    *
152    * @param driver - the new value of the driver property
153    */

154   public void setDriver(String JavaDoc driver) {
155     this.driver = driver;
156   }
157
158   /**
159    * Getter for url property
160    *
161    * @return The value of the url property
162    */

163   public String JavaDoc getUrl() {
164     return url;
165   }
166
167   /**
168    * Setter for url property
169    *
170    * @param url - the new value of the url property
171    */

172   public void setUrl(String JavaDoc url) {
173     this.url = url;
174   }
175
176   /**
177    * Getter for username property
178    *
179    * @return The value of the username property
180    */

181   public String JavaDoc getUsername() {
182     return username;
183   }
184
185   /**
186    * Setter for username property
187    *
188    * @param username - the new value of the username property
189    */

190   public void setUsername(String JavaDoc username) {
191     this.username = username;
192   }
193
194   /**
195    * Getter for password property
196    *
197    * @return The value of the password property
198    */

199   public String JavaDoc getPassword() {
200     return password;
201   }
202
203   /**
204    * Setter for password property
205    *
206    * @param password - the new value of the password property
207    */

208   public void setPassword(String JavaDoc password) {
209     this.password = password;
210   }
211
212   /**
213    * Runs an SQL script (read in using the Reader parameter)
214    *
215    * @param reader - the source of the script
216    * @throws ClassNotFoundException if the driver class cannot be found
217    * @throws SQLException if any SQL errors occur
218    * @throws IOException if there is an error reading from the Reader
219    * @throws IllegalAccessException if there are problems creating the driver class
220    * @throws InstantiationException if there are problems creating the driver class
221    */

222   public void runScript(Reader JavaDoc reader)
223       throws ClassNotFoundException JavaDoc, SQLException, IOException JavaDoc,
224       IllegalAccessException JavaDoc, InstantiationException JavaDoc {
225     DriverManager.registerDriver((Driver) Resources.classForName(driver).newInstance());
226     Connection conn = DriverManager.getConnection(url, username, password);
227     if (conn.getAutoCommit() != autoCommit) {
228       conn.setAutoCommit(autoCommit);
229     }
230     runScript(conn, reader);
231     conn.close();
232   }
233
234   /**
235    * Runs an SQL script (read in using the Reader parameter) using the connection passed in
236    *
237    * @param conn - the connection to use for the script
238    * @param reader - the source of the script
239    * @throws SQLException if any SQL errors occur
240    * @throws IOException if there is an error reading from the Reader
241    */

242   public void runScript(Connection conn, Reader JavaDoc reader)
243       throws IOException JavaDoc, SQLException {
244     StringBuffer JavaDoc command = null;
245     try {
246       LineNumberReader JavaDoc lineReader = new LineNumberReader JavaDoc(reader);
247       String JavaDoc line = null;
248       while ((line = lineReader.readLine()) != null) {
249         if (command == null) {
250           command = new StringBuffer JavaDoc();
251         }
252         String JavaDoc trimmedLine = line.trim();
253         if (trimmedLine.startsWith("--")) {
254           println(trimmedLine);
255 // if (log.isDebugEnabled()) {
256
// log.debug(trimmedLine);
257
// }
258
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
259           //Do nothing
260
} else if (trimmedLine.endsWith(";")) {
261           command.append(line.substring(0, line.lastIndexOf(";")));
262           command.append(" ");
263           Statement statement = conn.createStatement();
264
265           println(command);
266 // if (log.isDebugEnabled()) {
267
// log.debug(command);
268
// }
269

270           boolean hasResults = false;
271           if (stopOnError) {
272             hasResults = statement.execute(command.toString());
273           } else {
274             try {
275               statement.execute(command.toString());
276             } catch (SQLException e) {
277               e.fillInStackTrace();
278               printlnError("Error executing: " + command);
279               printlnError(e);
280             }
281           }
282
283           if (autoCommit && !conn.getAutoCommit()) {
284             conn.commit();
285           }
286
287           ResultSet rs = statement.getResultSet();
288           if (hasResults && rs != null) {
289             ResultSetMetaData md = rs.getMetaData();
290             int cols = md.getColumnCount();
291             for (int i = 0; i < cols; i++) {
292               String JavaDoc name = md.getColumnName(i);
293               print(name + "\t");
294             }
295             println("");
296             while (rs.next()) {
297               for (int i = 0; i < cols; i++) {
298                 String JavaDoc value = rs.getString(i);
299                 print(value + "\t");
300               }
301               println("");
302             }
303           }
304
305           command = null;
306           try {
307             statement.close();
308           } catch (Exception JavaDoc e) {
309             // Ignore to workaround a bug in Jakarta DBCP
310
}
311           Thread.yield();
312         } else {
313           command.append(line);
314           command.append(" ");
315         }
316       }
317       if (!autoCommit) {
318         conn.commit();
319       }
320     } catch (SQLException e) {
321       e.fillInStackTrace();
322       printlnError("Error executing: " + command);
323       printlnError(e);
324 // log.error("Error executing: " + command, e);
325
throw e;
326     } catch (IOException JavaDoc e) {
327       e.fillInStackTrace();
328       printlnError("Error executing: " + command);
329       printlnError(e);
330 // log.error("Error executing: " + command, e);
331
throw e;
332     } finally {
333       conn.rollback();
334       flush();
335     }
336   }
337
338   private void print(Object JavaDoc o) {
339     if (logWriter != null) {
340       System.out.print(o);
341     }
342   }
343
344   private void println(Object JavaDoc o) {
345     if (logWriter != null) {
346       logWriter.println(o);
347     }
348   }
349
350   private void printlnError(Object JavaDoc o) {
351     if (errorLogWriter != null) {
352       errorLogWriter.println(o);
353     }
354   }
355
356   private void flush() {
357     if (logWriter != null) {
358       logWriter.flush();
359     }
360     if (errorLogWriter != null) {
361       errorLogWriter.flush();
362     }
363   }
364
365
366 }
367
Popular Tags