CsvProducer.java

  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. package org.dbunit.dataset.csv;

  22. import java.io.BufferedReader;
  23. import java.io.File;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.io.InputStreamReader;
  27. import java.net.URL;
  28. import java.util.ArrayList;
  29. import java.util.Iterator;
  30. import java.util.List;

  31. import org.dbunit.dataset.Column;
  32. import org.dbunit.dataset.DataSetException;
  33. import org.dbunit.dataset.DefaultTableMetaData;
  34. import org.dbunit.dataset.ITableMetaData;
  35. import org.dbunit.dataset.common.handlers.IllegalInputCharacterException;
  36. import org.dbunit.dataset.common.handlers.PipelineException;
  37. import org.dbunit.dataset.datatype.DataType;
  38. import org.dbunit.dataset.stream.DefaultConsumer;
  39. import org.dbunit.dataset.stream.IDataSetConsumer;
  40. import org.dbunit.dataset.stream.IDataSetProducer;
  41. import org.slf4j.Logger;
  42. import org.slf4j.LoggerFactory;

  43. /**
  44.  * @author Federico Spinazzi
  45.  * @author Last changed by: $Author$
  46.  * @version $Revision$ $Date$
  47.  * @since 1.5 (Sep 17, 2003)
  48.  */
  49. public class CsvProducer implements IDataSetProducer {

  50.     /**
  51.      * Logger for this class
  52.      */
  53.     private static final Logger logger = LoggerFactory.getLogger(CsvProducer.class);

  54.     private static final IDataSetConsumer EMPTY_CONSUMER = new DefaultConsumer();
  55.     private IDataSetConsumer _consumer = EMPTY_CONSUMER;
  56.     private String _theDirectory;

  57.     public CsvProducer(String theDirectory) {
  58.         _theDirectory = theDirectory;
  59.     }

  60.     public CsvProducer(File theDirectory) {
  61.         _theDirectory = theDirectory.getAbsolutePath();
  62.     }

  63.     public void setConsumer(IDataSetConsumer consumer) throws DataSetException {
  64.         logger.debug("setConsumer(consumer) - start");

  65.         _consumer = consumer;
  66.     }

  67.     public void produce() throws DataSetException {
  68.         logger.debug("produce() - start");

  69.         File dir = new File(_theDirectory);

  70.         if (!dir.isDirectory()) {
  71.             throw new DataSetException("'" + _theDirectory + "' should be a directory");
  72.         }

  73.         _consumer.startDataSet();
  74.         try {
  75.             List tableSpecs = CsvProducer.getTables(dir.toURL(), CsvDataSet.TABLE_ORDERING_FILE);
  76.             for (Iterator tableIter = tableSpecs.iterator(); tableIter.hasNext();) {
  77.                 String table = (String) tableIter.next();
  78.                 try {
  79.                     produceFromFile(new File(dir, table + ".csv"));
  80.                 } catch (CsvParserException e) {
  81.                     throw new DataSetException("error producing dataset for table '" + table + "'", e);
  82.                 } catch (DataSetException e) {
  83.                     throw new DataSetException("error producing dataset for table '" + table + "'", e);
  84.                 }

  85.             }
  86.             _consumer.endDataSet();
  87.         } catch (IOException e) {
  88.             throw new DataSetException("error getting list of tables", e);
  89.         }
  90.     }

  91.     private void produceFromFile(File theDataFile) throws DataSetException, CsvParserException {
  92.         logger.debug("produceFromFile(theDataFile={}) - start", theDataFile);

  93.         try {
  94.             CsvParser parser = new CsvParserImpl();
  95.             List readData = parser.parse(theDataFile);
  96.             List readColumns = ((List) readData.get(0));
  97.             Column[] columns = new Column[readColumns.size()];

  98.             for (int i = 0; i < readColumns.size(); i++) {
  99.                 String columnName = (String) readColumns.get(i);
  100.                 columnName = columnName.trim();
  101.                 columns[i] = new Column(columnName, DataType.UNKNOWN);
  102.             }

  103.             String tableName = theDataFile.getName().substring(0, theDataFile.getName().indexOf(".csv"));
  104.             ITableMetaData metaData = new DefaultTableMetaData(tableName, columns);
  105.             _consumer.startTable(metaData);
  106.             for (int i = 1 ; i < readData.size(); i++) {
  107.                 List rowList = (List)readData.get(i);
  108.                 Object[] row = rowList.toArray();
  109.                 for(int col = 0; col < row.length; col++) {
  110.                     row[col] = row[col].equals(CsvDataSetWriter.NULL) ? null : row[col];
  111.                 }
  112.                 _consumer.row(row);
  113.             }
  114.             _consumer.endTable();
  115.         } catch (PipelineException e) {
  116.             throw new DataSetException(e);
  117.         } catch (IllegalInputCharacterException e) {
  118.             throw new DataSetException(e);
  119.         } catch (IOException e) {
  120.             throw new DataSetException(e);
  121.         }
  122.     }

  123.     /**
  124.      * Get a list of tables that this producer will create
  125.      * @return a list of Strings, where each item is a CSV file relative to the base URL
  126.      * @throws IOException when IO on the base URL has issues.
  127.      */
  128.     public static List getTables(URL base, String tableList) throws IOException {
  129.         logger.debug("getTables(base={}, tableList={}) - start", base, tableList);

  130.         List orderedNames = new ArrayList();
  131.         InputStream tableListStream = new URL(base, tableList).openStream();
  132.         BufferedReader reader = null;
  133.         try {
  134.             reader = new BufferedReader(new InputStreamReader(tableListStream));
  135.             String line = null;
  136.             while((line = reader.readLine()) != null) {
  137.                 String table = line.trim();
  138.                 if (table.length() > 0) {
  139.                     orderedNames.add(table);
  140.                 }
  141.             }
  142.         }
  143.         finally {
  144.             if(reader != null)
  145.             {
  146.                 reader.close();
  147.             }
  148.         }
  149.         return orderedNames;
  150.     }

  151. }