1 21 22 package org.dbunit.dataset.csv; 23 24 import org.dbunit.dataset.Column; 25 import org.dbunit.dataset.DataSetException; 26 import org.dbunit.dataset.DefaultTableMetaData; 27 import org.dbunit.dataset.ITableMetaData; 28 import org.dbunit.dataset.csv.handlers.PipelineException; 29 import org.dbunit.dataset.datatype.DataType; 30 import org.dbunit.dataset.stream.DefaultConsumer; 31 import org.dbunit.dataset.stream.IDataSetConsumer; 32 import org.dbunit.dataset.stream.IDataSetProducer; 33 34 import java.io.File ; 35 import java.io.FilenameFilter ; 36 import java.io.IOException ; 37 import java.util.List ; 38 39 44 45 public class CsvProducer implements IDataSetProducer { 46 47 private static final IDataSetConsumer EMPTY_CONSUMER = new DefaultConsumer(); 48 private IDataSetConsumer _consumer = EMPTY_CONSUMER; 49 private String _theDirectory; 50 51 public CsvProducer(String theDirectory) { 52 _theDirectory = theDirectory; 53 } 54 55 public CsvProducer(File theDirectory) { 56 _theDirectory = theDirectory.getAbsolutePath(); 57 } 58 59 public void setConsumer(IDataSetConsumer consumer) throws DataSetException { 60 _consumer = consumer; 61 } 62 63 public void produce() throws DataSetException { 64 65 File dir = new File (_theDirectory); 66 67 if (!dir.isDirectory()) { 68 throw new DataSetException("'" + _theDirectory + "' should be a directory"); 69 } 70 71 FilenameFilter filter = new FilenameFilter () { 73 public boolean accept(File dir, String name) { 74 return name.endsWith(".csv") && !dir.isFile(); 75 } 76 }; 77 78 _consumer.startDataSet(); 79 80 File [] children = dir.listFiles(filter); 81 for (int i = 0; i < children.length; i++) { 82 try { 83 produceFromFile(children[i]); 84 } catch (CsvParserException e) { 85 throw new DataSetException(e); 86 } 87 } 88 89 _consumer.endDataSet(); 90 91 } 92 93 private void produceFromFile(File theDataFile) throws DataSetException, CsvParserException { 94 try { 95 CsvParser parser = new CsvParserImpl(); 96 List readData = parser.parse(theDataFile); 97 List readColumns = ((List ) readData.get(0)); 98 Column[] columns = new Column[readColumns.size()]; 99 100 for (int i = 0; i < readColumns.size(); i++) { 101 columns[i] = new Column((String ) readColumns.get(i), DataType.UNKNOWN); 102 } 103 104 String tableName = theDataFile.getName().substring(0, theDataFile.getName().indexOf(".csv")); 105 ITableMetaData metaData = new DefaultTableMetaData(tableName, columns); 106 _consumer.startTable(metaData); 107 for (int i = 1 ; i < readData.size(); i++) { 108 List rowList = (List )readData.get(i); 109 _consumer.row(rowList.toArray()); 110 } 111 _consumer.endTable(); 112 } catch (PipelineException e) { 113 throw new DataSetException(e); 114 } catch (IllegalInputCharacterException e) { 115 throw new DataSetException(e); 116 } catch (IOException e) { 117 throw new DataSetException(e); 118 } 119 } 120 121 } 122 | Popular Tags |