KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > sample > FindFile


1 /* Copyright (c) 1995-2000, The Hypersonic SQL Group.
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of the Hypersonic SQL Group nor the names of its
15  * contributors may be used to endorse or promote products derived from this
16  * software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE HYPERSONIC SQL GROUP,
22  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * This software consists of voluntary contributions made by many individuals
31  * on behalf of the Hypersonic SQL Group.
32  *
33  *
34  * For work added by the HSQL Development Group:
35  *
36  * Copyright (c) 2001-2005, The HSQL Development Group
37  * All rights reserved.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions are met:
41  *
42  * Redistributions of source code must retain the above copyright notice, this
43  * list of conditions and the following disclaimer.
44  *
45  * Redistributions in binary form must reproduce the above copyright notice,
46  * this list of conditions and the following disclaimer in the documentation
47  * and/or other materials provided with the distribution.
48  *
49  * Neither the name of the HSQL Development Group nor the names of its
50  * contributors may be used to endorse or promote products derived from this
51  * software without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
54  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
57  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
60  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
61  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
62  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  */

65
66
67 package org.hsqldb.sample;
68
69 import java.io.File JavaDoc;
70 import java.sql.Connection JavaDoc;
71 import java.sql.DriverManager JavaDoc;
72 import java.sql.PreparedStatement JavaDoc;
73 import java.sql.ResultSet JavaDoc;
74 import java.sql.SQLException JavaDoc;
75 import java.sql.Statement JavaDoc;
76
77 /**
78  * Extract a directory tree and store in an HSQLDB database.
79  *
80  * @author Thomas Mueller (Hypersonic SQL Group)
81  * @version 1.7.0
82  * @since Hypersonic SQL
83  */

84 class FindFile {
85
86     /**
87      * Extracts a directory tree and stores it ina HSQLDB database.<br>
88      * Usage:<p>
89      * <pre>
90      * java org.hsqldb.sample.FindFile -init .
91      * Re-create database from directory '.'
92      * java org.hsqldb.sample.FindFile name
93      * Find files like 'name'
94      * </pre>
95      *
96      * @param arg
97      */

98     public static void main(String JavaDoc[] arg) {
99
100         // Exceptions may occur
101
try {
102
103             // Load the HSQL Database Engine JDBC driver
104
Class.forName("org.hsqldb.jdbcDriver");
105
106             // Connect to the database
107
// It will be create automatically if it does not yet exist
108
// 'testfiles' in the URL is the name of the database
109
// "sa" is the user name and "" is the (empty) password
110
Connection JavaDoc conn =
111                 DriverManager.getConnection("jdbc:hsqldb:testfiles", "sa",
112                                             "");
113
114             // Check the command line parameters
115
if (arg.length == 1) {
116
117                 // One parameter:
118
// Find and print the list of files that are like this
119
listFiles(conn, arg[0]);
120             } else if ((arg.length == 2) && arg[0].equals("-init")) {
121
122                 // Command line parameters: -init pathname
123
// Init the database and fill all file names in
124
fillFileNames(conn, arg[1]);
125             } else {
126
127                 // Display the usage info
128
System.out.println("Usage:");
129                 System.out.println("java FindFile -init .");
130                 System.out.println(" Re-create database from directory '.'");
131                 System.out.println("java FindFile name");
132                 System.out.println(" Find files like 'name'");
133             }
134
135             // Finally, close the connection
136
conn.close();
137         } catch (Exception JavaDoc e) {
138
139             // Print out the error message
140
System.out.println(e);
141             e.printStackTrace();
142         }
143     }
144
145     // Search in the database and list out files like this
146

147     /**
148      * Method declaration
149      *
150      *
151      * @param conn
152      * @param name
153      *
154      * @throws SQLException
155      */

156     static void listFiles(Connection JavaDoc conn, String JavaDoc name) throws SQLException JavaDoc {
157
158         System.out.println("Files like '" + name + "'");
159
160         // Convert to upper case, so the search is case-insensitive
161
name = name.toUpperCase();
162
163         // Create a statement object
164
Statement JavaDoc stat = conn.createStatement();
165
166         // Now execute the search query
167
// UCASE: This is a case insensitive search
168
// ESCAPE ':' is used so it can be easily searched for '\'
169
ResultSet JavaDoc result = stat.executeQuery("SELECT Path FROM Files WHERE "
170                                              + "UCASE(Path) LIKE '%" + name
171                                              + "%' ESCAPE ':'");
172
173         // Moves to the next record until no more records
174
while (result.next()) {
175
176             // Print the first column of the result
177
// could use also getString("Path")
178
System.out.println(result.getString(1));
179         }
180
181         // Close the ResultSet - not really necessary, but recommended
182
result.close();
183     }
184
185     // Re-create the database and fill the file names in
186

187     /**
188      * Method declaration
189      *
190      *
191      * @param conn
192      * @param root
193      *
194      * @throws SQLException
195      */

196     static void fillFileNames(Connection JavaDoc conn,
197                               String JavaDoc root) throws SQLException JavaDoc {
198
199         System.out.println("Re-creating the database...");
200
201         // Create a statement object
202
Statement JavaDoc stat = conn.createStatement();
203
204         // Try to drop the table
205
try {
206             stat.executeUpdate("DROP TABLE Files");
207         } catch (SQLException JavaDoc e) { // Ignore Exception, because the table may not yet exist
208
}
209
210         // For compatibility to other database, use varchar(255)
211
// In HSQL Database Engine, length is unlimited, like Java Strings
212
stat.execute("CREATE TABLE Files"
213                      + "(Path varchar(255),Name varchar(255))");
214
215         // Close the Statement object, it is no longer used
216
stat.close();
217
218         // Use a PreparedStatement because Path and Name could contain '
219
PreparedStatement JavaDoc prep =
220             conn.prepareCall("INSERT INTO Files (Path,Name) VALUES (?,?)");
221
222         // Start with the 'root' directory and recurse all subdirectories
223
fillPath(root, "", prep);
224
225         // Close the PreparedStatement
226
prep.close();
227         System.out.println("Finished");
228     }
229
230     // Fill the file names, using the PreparedStatement
231

232     /**
233      * Method declaration
234      *
235      *
236      * @param path
237      * @param name
238      * @param prep
239      *
240      * @throws SQLException
241      */

242     static void fillPath(String JavaDoc path, String JavaDoc name,
243                          PreparedStatement JavaDoc prep) throws SQLException JavaDoc {
244
245         File JavaDoc f = new File JavaDoc(path);
246
247         if (f.isFile()) {
248
249             // Clear all Parameters of the PreparedStatement
250
prep.clearParameters();
251
252             // Fill the first parameter: Path
253
prep.setString(1, path);
254
255             // Fill the second parameter: Name
256
prep.setString(2, name);
257
258             // Its a file: add it to the table
259
prep.execute();
260         } else if (f.isDirectory()) {
261             if (!path.endsWith(File.separator)) {
262                 path += File.separator;
263             }
264
265             String JavaDoc[] list = f.list();
266
267             // Process all files recursivly
268
for (int i = 0; (list != null) && (i < list.length); i++) {
269                 fillPath(path + list[i], list[i], prep);
270             }
271         }
272     }
273 }
274
Popular Tags