View Javadoc

1   /*
2    * Copyright 2004 Carlos Sanchez.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * 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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package net.sf.oness.common.model.testing;
17  
18  import java.io.FileOutputStream;
19  import java.sql.Connection;
20  
21  import javax.sql.DataSource;
22  
23  import org.dbunit.database.DatabaseConnection;
24  import org.dbunit.database.DatabaseSequenceFilter;
25  import org.dbunit.database.IDatabaseConnection;
26  import org.dbunit.dataset.FilteredDataSet;
27  import org.dbunit.dataset.IDataSet;
28  import org.dbunit.dataset.filter.ITableFilter;
29  import org.dbunit.dataset.xml.FlatDtdDataSet;
30  import org.dbunit.dataset.xml.FlatXmlWriter;
31  
32  /***
33   * <p>
34   * Utility class to export database to file dbunit.xml and dbunit.dtd for its
35   * use with dbunit
36   * </p>
37   * 
38   * <p>
39   * Uses "dataSource" object defined in Spring application context
40   * </p>
41   * 
42   * @author Carlos Sanchez
43   * @version $Revision: 1.5 $
44   */
45  public class SpringDatabaseExport {
46  
47      private static final String DATASET_FILE_NAME = "dbunit.xml";
48  
49      private static final String DTD_FILE_NAME = "dbunit.dtd";
50  
51      public static void main(String[] args) throws Exception {
52  
53          DataSource dataSource = (DataSource) SpringApplicationContext
54                  .getBean("dataSource");
55  
56          /* database connection */
57          Connection jdbcConnection = dataSource.getConnection();
58          IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
59  
60          /* full database export */
61          ITableFilter filter = new DatabaseSequenceFilter(connection);
62          IDataSet fullDataSet = new FilteredDataSet(filter, connection
63                  .createDataSet());
64  
65          FlatXmlWriter datasetWriter = new FlatXmlWriter(new FileOutputStream(
66                  DATASET_FILE_NAME));
67          datasetWriter.setDocType(DTD_FILE_NAME);
68          datasetWriter.write(fullDataSet);
69  
70          /* write DTD file */
71          FlatDtdDataSet.write(connection.createDataSet(), new FileOutputStream(
72                  DTD_FILE_NAME));
73  
74          /* Close connection */
75          jdbcConnection.close();
76  
77          System.out.println("DONE");
78      }
79  
80  }