KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > quadcap > app > bugdb > Loader


1 package com.quadcap.app.bugdb;
2
3 /* Copyright 1999 - 2003 Quadcap Software. All rights reserved.
4  *
5  * This software is distributed under the Quadcap Free Software License.
6  * This software may be used or modified for any purpose, personal or
7  * commercial. Open Source redistributions are permitted. Commercial
8  * redistribution of larger works derived from, or works which bundle
9  * this software requires a "Commercial Redistribution License"; see
10  * http://www.quadcap.com/purchase.
11  *
12  * Redistributions qualify as "Open Source" under one of the following terms:
13  *
14  * Redistributions are made at no charge beyond the reasonable cost of
15  * materials and delivery.
16  *
17  * Redistributions are accompanied by a copy of the Source Code or by an
18  * irrevocable offer to provide a copy of the Source Code for up to three
19  * years at the cost of materials and delivery. Such redistributions
20  * must allow further use, modification, and redistribution of the Source
21  * Code under substantially the same terms as this license.
22  *
23  * Redistributions of source code must retain the copyright notices as they
24  * appear in each source code file, these license terms, and the
25  * disclaimer/limitation of liability set forth as paragraph 6 below.
26  *
27  * Redistributions in binary form must reproduce this Copyright Notice,
28  * these license terms, and the disclaimer/limitation of liability set
29  * forth as paragraph 6 below, in the documentation and/or other materials
30  * provided with the distribution.
31  *
32  * The Software is provided on an "AS IS" basis. No warranty is
33  * provided that the Software is free of defects, or fit for a
34  * particular purpose.
35  *
36  * Limitation of Liability. Quadcap Software shall not be liable
37  * for any damages suffered by the Licensee or any third party resulting
38  * from use of the Software.
39  */

40
41 import java.io.BufferedInputStream JavaDoc;
42 import java.io.File JavaDoc;
43 import java.io.FileInputStream JavaDoc;
44 import java.io.IOException JavaDoc;
45 import java.io.InputStream JavaDoc;
46 import java.io.PrintWriter JavaDoc;
47
48 import java.sql.Connection JavaDoc;
49 import java.sql.DriverManager JavaDoc;
50 import java.sql.ResultSet JavaDoc;
51 import java.sql.ResultSetMetaData JavaDoc;
52 import java.sql.SQLException JavaDoc;
53 import java.sql.Statement JavaDoc;
54
55 /**
56  * A simple SQL loader utility.
57  *
58  * @author Stan Bailes
59  */

60 public class Loader {
61     Connection JavaDoc conn;
62     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
63     PrintWriter JavaDoc writer = null;
64     
65     /**
66      * Construct a new loader. It needs a connection in order to do
67      * anything useful.
68      */

69     public Loader() {
70     }
71
72     /**
73      * Construct a new loader bound to the specified connection.
74      *
75      * @param conn the connection to use.
76      */

77     public Loader(Connection JavaDoc conn) {
78     this.conn = conn;
79     }
80
81     /**
82      * Set the loader's connection
83      *
84      * @param conn the connection to use.
85      */

86     public void setConnection(Connection JavaDoc conn) {
87     this.conn = conn;
88     }
89     
90     /**
91      * Get the loaders's connection
92      *
93      * @return the loader's current connection
94      */

95     public Connection JavaDoc getConnection() {
96     return this.conn;
97     }
98
99     /**
100      * Get the PrintWriter used to display the results of select statements.
101      *
102      * @return the current writer
103      */

104     public PrintWriter JavaDoc getWriter() {
105     return writer;
106     }
107
108     /**
109      * Set the PrintWriter used to display the results of select statements.
110      *
111      * @param writer the new writer
112      */

113     public void setWriter(PrintWriter JavaDoc writer) {
114     this.writer = writer;
115     }
116
117     /**
118      * Print (if a writer is set) the specified string
119      *
120      * @param s the string
121      */

122     final void print(String JavaDoc s) {
123     if (writer != null) writer.print(s);
124     }
125
126     /**
127      * Print (if a writer is set) the specified string,
128      * with a trailing newline.
129      *
130      * @param s the string
131      */

132     final void println(String JavaDoc s) {
133     if (writer != null) writer.println(s);
134     }
135
136     /**
137      * Print (if a writer is set) the stack trace for the specified throwable.
138      *
139      * @param t the throwable
140      */

141     final void print(Throwable JavaDoc t) {
142     if (writer != null) t.printStackTrace(writer);
143     if (t instanceof SQLException JavaDoc) {
144         SQLException JavaDoc e = ((SQLException JavaDoc)t).getNextException();
145         if (e != null) {
146         print(e);
147         }
148     }
149     }
150
151     /**
152      * Return a string left-justified in a field 'wid' characters wide.
153      *
154      * @param wid the field width
155      * @param s the input string
156      * @return the padded string
157      */

158     final static String JavaDoc pad(int wid, String JavaDoc s) {
159     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(s);
160     while (sb.length() < wid) sb.append(' ');
161     return sb.toString();
162     }
163
164     /**
165      * Display a result set (to the current writer)
166      *
167      * @param rs the result set
168      * @exception SQLException may be thrown
169      */

170     final void showResultSet(ResultSet JavaDoc rs) throws SQLException JavaDoc {
171     ResultSetMetaData JavaDoc rmeta = rs.getMetaData();
172     String JavaDoc delim = "";
173     for (int i = 1; i <= rmeta.getColumnCount(); i++) {
174         int wid = rmeta.getColumnDisplaySize(i);
175         if (wid > 32) wid = 32;
176         print(delim);
177         delim = " ";
178         print(pad(wid, rmeta.getColumnName(i)));
179     }
180     println("");
181     while (rs.next()) {
182         delim = "";
183         for (int i = 1; i <= rmeta.getColumnCount(); i++) {
184         int wid = rmeta.getColumnDisplaySize(i);
185         if (wid > 32) wid = 32;
186         print(delim);
187         delim = " ";
188         Object JavaDoc obj = rs.getObject(i);
189         if (obj == null) obj = "<null>";
190         if (obj instanceof byte[]) {
191             obj = hexBytes((byte[])obj);
192         }
193         print(pad(wid, obj.toString()));
194         }
195         println("");
196     }
197     }
198
199     /**
200      * Return the next SQL command from the input stream.
201      *
202      * @param is the input stream
203      * @return the SQL statement
204      * @exception IOException may be thrown
205      */

206     static String JavaDoc getLine(InputStream JavaDoc is) throws IOException JavaDoc {
207     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
208     int ch;
209     int state = 0;
210     while ((ch = is.read()) > 0) {
211         char c = (char)ch;
212         switch (state) {
213         case 0:
214         if (c == '-') {
215             state = 1;
216         } else if (c == ';') {
217             if (sb.length() > 0) {
218             return sb.toString();
219             }
220         } else if (Character.isWhitespace(c) && sb.length() == 0) {
221         } else {
222             sb.append(c);
223         }
224         break;
225         case 1:
226         if (c == '-') {
227             state = 2;
228         } else {
229             sb.append('-');
230             sb.append(c);
231             state = 0;
232         }
233         break;
234         case 2:
235         if (c == '\r') state = 3;
236         if (c == '\n') state = 0;
237         break;
238         case 3:
239         if (c == '\n') state = 0;
240         break;
241         }
242     }
243     return null;
244     }
245
246     /**
247      * Execute the specified SQL command
248      *
249      * @param sql the SQL statement to execute
250      */

251     final void execute(String JavaDoc sql) {
252     try {
253         Statement JavaDoc stmt = conn.createStatement();
254         try {
255         if (sql.equals("BEGINTRANSACTION")) {
256             conn.setAutoCommit(false);
257         } else if (sql.equals("ENDTRANSACTION") ||
258                sql.equals("COMMIT")) {
259             conn.commit();
260             conn.setAutoCommit(true);
261         } else if (sql.equals("ROLLBACK")) {
262             conn.rollback();
263             conn.setAutoCommit(true);
264         } else {
265             if (stmt.execute(sql)) {
266             ResultSet JavaDoc rs = stmt.getResultSet();
267             try {
268                 showResultSet(rs);
269             } finally {
270                 rs.close();
271             }
272             }
273         }
274         } catch (Throwable JavaDoc t) {
275         print(t);
276         } finally {
277         stmt.close();
278         }
279     } catch (Throwable JavaDoc t) {
280         print(t);
281     }
282     }
283
284     /**
285      * The main point of this class, which is to execute all the SQL commands
286      * found in the specified file.
287      *
288      * @param filename the name of the file
289      */

290     public void loadFile(String JavaDoc filename) throws IOException JavaDoc {
291         FileInputStream JavaDoc fis = new FileInputStream JavaDoc(filename);
292         loadStream(fis);
293     }
294
295     /**
296      * Execute the SQL script contained in the specified input stream
297      *
298      * @param is the input stream
299      */

300     public void loadStream(InputStream JavaDoc is) {
301     try {
302         Statement JavaDoc stmt = conn.createStatement();
303         BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(is, 1024);
304         String JavaDoc sql = null;
305         while ((sql = getLine(bis)) != null) {
306         try {
307             if (sql.equals("BEGINTRANSACTION")) {
308             conn.setAutoCommit(false);
309             } else if (sql.equals("ENDTRANSACTION") ||
310                    sql.equals("COMMIT")) {
311             conn.commit();
312             conn.setAutoCommit(true);
313             } else if (sql.equals("ROLLBACK")) {
314             conn.rollback();
315             conn.setAutoCommit(true);
316             } else {
317             if (stmt.execute(sql)) {
318                 ResultSet JavaDoc rs = stmt.getResultSet();
319                 showResultSet(rs);
320             }
321             }
322         } catch (Throwable JavaDoc t) {
323             print(t);
324         }
325         }
326     } catch (Throwable JavaDoc t) {
327         print(t);
328     } finally {
329             try {
330                 is.close();
331             } catch (Exception JavaDoc e) {}
332         }
333     }
334
335     static char[] hexMap = {'0', '1', '2', '3', '4', '5', '6', '7',
336                 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
337
338     /**
339      * Return a string containing the hexadecimal representation of the
340      * specified byte array
341      *
342      * @param buf the byte array
343      * @return the ASCII hex representation of the byte array.
344      */

345     public static String JavaDoc hexBytes(byte[] buf) {
346     if (buf == null) return "<null>";
347     return hexBytes(buf, 0, buf.length);
348     }
349
350     /**
351      * Return a string containing the hexadecimal representation of
352      * a portion of the specified byte array
353      *
354      * @param buf the byte array
355      * @param off the position of the first byte to convert
356      * @param len the number of bytes to convert
357      * @return the ASCII hex representation of the bytes
358      */

359     public static String JavaDoc hexBytes(byte[] buf, int off, int len) {
360     if (buf == null) return "<null>";
361     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
362     for (int i = off; i < off + len; i++) {
363         byte b = buf[i];
364         sb.append(hexMap[(b >> 4) & 0xf]);
365         sb.append(hexMap[b & 0xf]);
366     }
367     return sb.toString();
368     }
369 }
370
Popular Tags