KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dbunit > ant > DbUnitTask


1 /*
2  *
3  * The DbUnit Database Testing Framework
4  * Copyright (C)2002-2004, DbUnit.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  */

21
22 package org.dbunit.ant;
23
24 import org.apache.tools.ant.AntClassLoader;
25 import org.apache.tools.ant.BuildException;
26 import org.apache.tools.ant.Project;
27 import org.apache.tools.ant.Task;
28 import org.apache.tools.ant.types.Path;
29 import org.apache.tools.ant.types.Reference;
30 import org.dbunit.DatabaseUnitException;
31 import org.dbunit.database.DatabaseConfig;
32 import org.dbunit.database.DatabaseConnection;
33 import org.dbunit.database.ForwardOnlyResultSetTableFactory;
34 import org.dbunit.database.IDatabaseConnection;
35 import org.dbunit.dataset.datatype.IDataTypeFactory;
36
37 import java.sql.Connection JavaDoc;
38 import java.sql.Driver JavaDoc;
39 import java.sql.SQLException JavaDoc;
40 import java.util.ArrayList JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.Properties JavaDoc;
44
45 /**
46  * <code>DbUnitTask</code> is the task definition for an Ant
47  * interface to <code>DbUnit</code>. DbUnit is a JUnit extension
48  * which sets your database to a known state before executing your
49  * tasks.
50  *
51  * @author Timothy Ruppert
52  * @author Ben Cox
53  * @version $Revision: 1.13 $
54  * @since Jun 10, 2002
55  * @see org.apache.tools.ant.Task
56  */

57 public class DbUnitTask extends Task
58 {
59
60     /**
61      * Database connection
62      */

63     private Connection conn = null;
64
65     /**
66      * DB driver.
67      */

68     private String JavaDoc driver = null;
69
70     /**
71      * DB url.
72      */

73     private String JavaDoc url = null;
74
75     /**
76      * User name.
77      */

78     private String JavaDoc userId = null;
79
80     /**
81      * Password
82      */

83     private String JavaDoc password = null;
84
85     /**
86      * DB schema.
87      */

88     private String JavaDoc schema = null;
89
90     /**
91      * Steps
92      */

93     private List JavaDoc steps = new ArrayList JavaDoc();
94
95     private Path classpath;
96
97     private AntClassLoader loader;
98
99     /**
100      * Flag for using the qualified table names.
101      */

102     private boolean useQualifiedTableNames = false;
103
104     /**
105      * Flag for using batched statements.
106      */

107     private boolean supportBatchStatement = false;
108
109     /**
110      * Flag for datatype warning.
111      */

112     private boolean datatypeWarning = true;
113
114     private String JavaDoc escapePattern = null;
115
116     private String JavaDoc dataTypeFactory = "org.dbunit.dataset.datatype.DefaultDataTypeFactory";
117
118     /**
119      * Set the JDBC driver to be used.
120      */

121     public void setDriver(String JavaDoc driver)
122     {
123         this.driver = driver;
124     }
125
126     /**
127      * Set the DB connection url.
128      */

129     public void setUrl(String JavaDoc url)
130     {
131         this.url = url;
132     }
133
134     /**
135      * Set the user name for the DB connection.
136      */

137     public void setUserid(String JavaDoc userId)
138     {
139         this.userId = userId;
140     }
141
142     /**
143      * Set the password for the DB connection.
144      */

145     public void setPassword(String JavaDoc password)
146     {
147         this.password = password;
148     }
149
150     /**
151      * Set the schema for the DB connection.
152      */

153     public void setSchema(String JavaDoc schema)
154     {
155         this.schema = schema;
156     }
157
158     /**
159      * Set the flag for using the qualified table names.
160      */

161     public void setUseQualifiedTableNames(boolean useQualifiedTableNames)
162     {
163         this.useQualifiedTableNames = useQualifiedTableNames;
164     }
165
166     /**
167      * Set the flag for supporting batch statements.
168      * NOTE: This property cannot be used to force the usage of batch
169      * statement if your database does not support it.
170      */

171     public void setSupportBatchStatement(boolean supportBatchStatement)
172     {
173         this.supportBatchStatement = supportBatchStatement;
174     }
175
176     public void setDatatypeWarning(boolean datatypeWarning)
177     {
178         this.datatypeWarning = datatypeWarning;
179     }
180
181     public void setDatatypeFactory(String JavaDoc datatypeFactory)
182     {
183         this.dataTypeFactory = datatypeFactory;
184     }
185
186     public void setEscapePattern(String JavaDoc escapePattern)
187     {
188         this.escapePattern = escapePattern;
189     }
190
191     /**
192      * Set the classpath for loading the driver.
193      */

194     public void setClasspath(Path classpath)
195     {
196         if (this.classpath == null)
197         {
198             this.classpath = classpath;
199         }
200         else
201         {
202             this.classpath.append(classpath);
203         }
204     }
205
206     /**
207      * Create the classpath for loading the driver.
208      */

209     public Path createClasspath()
210     {
211         if (this.classpath == null)
212         {
213             this.classpath = new Path(project);
214         }
215         return this.classpath.createPath();
216     }
217
218     /**
219      * Set the classpath for loading the driver using the classpath reference.
220      */

221     public void setClasspathRef(Reference r)
222     {
223         createClasspath().setRefid(r);
224     }
225
226     /**
227      * Gets the Steps.
228      */

229     public List JavaDoc getSteps()
230     {
231         return steps;
232     }
233
234     /**
235      * Adds an Operation.
236      */

237     public void addOperation(Operation operation)
238     {
239         steps.add(operation);
240     }
241
242     /**
243      * Adds a Compare to the steps List.
244      */

245     public void addCompare(Compare compare)
246     {
247         steps.add(compare);
248     }
249
250     /**
251      * Adds an Export to the steps List.
252      */

253     public void addExport(Export export)
254     {
255         steps.add(export);
256     }
257
258     /**
259      * Load the step and then execute it
260      */

261     public void execute() throws BuildException
262     {
263         try
264         {
265             IDatabaseConnection connection = createConnection();
266
267             Iterator JavaDoc stepIter = steps.listIterator();
268             while (stepIter.hasNext())
269             {
270                 DbUnitTaskStep step = (DbUnitTaskStep)stepIter.next();
271                 log(step.getLogMessage(), Project.MSG_INFO);
272                 step.execute(connection);
273             }
274         }
275         catch (DatabaseUnitException e)
276         {
277             throw new BuildException(e, location);
278         }
279         catch (SQLException JavaDoc e)
280         {
281             throw new BuildException(e, location);
282         }
283         finally
284         {
285             try
286             {
287                 if (conn != null)
288                 {
289                     conn.close();
290                 }
291             }
292             catch (SQLException JavaDoc e)
293             {
294             }
295         }
296     }
297
298     IDatabaseConnection createConnection() throws SQLException JavaDoc
299     {
300         if (driver == null)
301         {
302             throw new BuildException("Driver attribute must be set!", location);
303         }
304         if (userId == null)
305         {
306             throw new BuildException("User Id attribute must be set!", location);
307         }
308         if (password == null)
309         {
310             throw new BuildException("Password attribute must be set!", location);
311         }
312         if (url == null)
313         {
314             throw new BuildException("Url attribute must be set!", location);
315         }
316         if (steps.size() == 0)
317         {
318             throw new BuildException("Must declare at least one step in a <dbunit> task!");
319         }
320
321         // Instanciate JDBC driver
322
Driver JavaDoc driverInstance = null;
323         try
324         {
325             Class JavaDoc dc;
326             if (classpath != null)
327             {
328                 log("Loading " + driver + " using AntClassLoader with classpath " + classpath,
329                         Project.MSG_VERBOSE);
330
331                 loader = new AntClassLoader(project, classpath);
332                 dc = loader.loadClass(driver);
333             }
334             else
335             {
336                 log("Loading " + driver + " using system loader.", Project.MSG_VERBOSE);
337                 dc = Class.forName(driver);
338             }
339             driverInstance = (Driver JavaDoc)dc.newInstance();
340         }
341         catch (ClassNotFoundException JavaDoc e)
342         {
343             throw new BuildException("Class Not Found: JDBC driver "
344                     + driver + " could not be loaded", e, location);
345         }
346         catch (IllegalAccessException JavaDoc e)
347         {
348             throw new BuildException("Illegal Access: JDBC driver "
349                     + driver + " could not be loaded", e, location);
350         }
351         catch (InstantiationException JavaDoc e)
352         {
353             throw new BuildException("Instantiation Exception: JDBC driver "
354                     + driver + " could not be loaded", e, location);
355         }
356
357         log("connecting to " + url, Project.MSG_VERBOSE);
358         Properties JavaDoc info = new Properties JavaDoc();
359         info.put("user", userId);
360         info.put("password", password);
361         conn = driverInstance.connect(url, info);
362
363         if (conn == null)
364         {
365             // Driver doesn't understand the URL
366
throw new SQLException JavaDoc("No suitable Driver for " + url);
367         }
368         conn.setAutoCommit(true);
369
370         IDatabaseConnection connection = new DatabaseConnection(conn, schema);
371         DatabaseConfig config = connection.getConfig();
372         config.setFeature(DatabaseConfig.FEATURE_BATCHED_STATEMENTS, supportBatchStatement);
373         config.setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, useQualifiedTableNames);
374         config.setFeature(DatabaseConfig.FEATURE_DATATYPE_WARNING, datatypeWarning);
375         config.setProperty(DatabaseConfig.PROPERTY_ESCAPE_PATTERN, escapePattern);
376         config.setProperty(DatabaseConfig.PROPERTY_RESULTSET_TABLE_FACTORY,
377                 new ForwardOnlyResultSetTableFactory());
378
379         // Setup data type factory
380
try
381         {
382             IDataTypeFactory dataTypeFactory = (IDataTypeFactory)Class.forName(
383                     this.dataTypeFactory).newInstance();
384             config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, dataTypeFactory);
385         }
386         catch (ClassNotFoundException JavaDoc e)
387         {
388             throw new BuildException("Class Not Found: DataType factory "
389                     + driver + " could not be loaded", e, location);
390         }
391         catch (IllegalAccessException JavaDoc e)
392         {
393             throw new BuildException("Illegal Access: DataType factory "
394                     + driver + " could not be loaded", e, location);
395         }
396         catch (InstantiationException JavaDoc e)
397         {
398             throw new BuildException("Instantiation Exception: DataType factory "
399                     + driver + " could not be loaded", e, location);
400         }
401
402         return connection;
403     }
404 }
405
406
Popular Tags