001: /*
002: *
003: * The DbUnit Database Testing Framework
004: * Copyright (C)2002, Manuel Laflamme
005: *
006: * This library is free software; you can redistribute it and/or
007: * modify it under the terms of the GNU Lesser General Public
008: * License as published by the Free Software Foundation; either
009: * version 2.1 of the License, or (at your option) any later version.
010: *
011: * This library is distributed in the hope that it will be useful,
012: * but WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * Lesser General Public License for more details.
015: *
016: * You should have received a copy of the GNU Lesser General Public
017: * License along with this library; if not, write to the Free Software
018: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
019: *
020: */
021: package org.dbunit.dataset.csv;
022:
023: import org.slf4j.Logger;
024: import org.slf4j.LoggerFactory;
025:
026: import java.io.File;
027: import java.io.FileWriter;
028: import java.io.IOException;
029: import java.io.PrintWriter;
030: import java.io.Writer;
031: import java.util.Iterator;
032: import java.util.LinkedList;
033: import java.util.List;
034:
035: import org.dbunit.dataset.Column;
036: import org.dbunit.dataset.DataSetException;
037: import org.dbunit.dataset.IDataSet;
038: import org.dbunit.dataset.ITable;
039: import org.dbunit.dataset.ITableMetaData;
040: import org.dbunit.dataset.datatype.DataType;
041: import org.dbunit.dataset.datatype.TypeCastException;
042: import org.dbunit.dataset.stream.DataSetProducerAdapter;
043: import org.dbunit.dataset.stream.IDataSetConsumer;
044:
045: /**
046: * @author fede
047: * @since 24-set-2003 15.27.05
048: * @version $Revision: 554 $
049: */
050: public class CsvDataSetWriter implements IDataSetConsumer {
051:
052: /**
053: * Logger for this class
054: */
055: private static final Logger logger = LoggerFactory
056: .getLogger(CsvDataSetWriter.class);
057:
058: /**
059: * todo: customizable separators (field, lines), manage the writers opened for each table
060: */
061:
062: public static final String NULL = "null";
063: private static final String NONE = "none";
064: private static final String FIELD_SEPARATOR = ", ";
065: private static final String QUOTE = "\"";
066: private static final String ESCAPE = "\\";
067:
068: private Writer writer;
069: private ITableMetaData _activeMetaData;
070: private String theDirectory;
071: private static char testExport;
072: /** list of tables */
073: private List tableList;
074:
075: public CsvDataSetWriter(String theDirectory) {
076: setTheDirectory(theDirectory);
077: }
078:
079: public CsvDataSetWriter(File theDirectory) {
080: setTheDirectory(theDirectory.getAbsolutePath());
081: }
082:
083: public void write(IDataSet dataSet) throws DataSetException {
084: logger.debug("write(dataSet=" + dataSet + ") - start");
085:
086: DataSetProducerAdapter provider = new DataSetProducerAdapter(
087: dataSet);
088: provider.setConsumer(this );
089: provider.produce();
090: }
091:
092: public void startDataSet() throws DataSetException {
093: logger.debug("startDataSet() - start");
094:
095: try {
096: tableList = new LinkedList();
097: new File(getTheDirectory()).mkdirs();
098: } catch (Exception e) {
099: logger.error("startDataSet()", e);
100:
101: throw new DataSetException(
102: "Error while creating the destination directory '"
103: + getTheDirectory() + "'", e);
104: }
105: }
106:
107: public void endDataSet() throws DataSetException {
108: logger.debug("endDataSet() - start");
109:
110: // write out table ordering file
111: File orderingFile = new File(getTheDirectory(),
112: "table-ordering.txt");
113:
114: try {
115: PrintWriter pw = new PrintWriter(new FileWriter(
116: orderingFile));
117: for (Iterator fileNames = tableList.iterator(); fileNames
118: .hasNext();) {
119: String file = (String) fileNames.next();
120: pw.println(file);
121: }
122: pw.close();
123: } catch (IOException e) {
124: logger.error("endDataSet()", e);
125:
126: throw new DataSetException(
127: "problems writing the table ordering file", e);
128: }
129: }
130:
131: public void startTable(ITableMetaData metaData)
132: throws DataSetException {
133: logger.debug("startTable(metaData=" + metaData + ") - start");
134:
135: try {
136: _activeMetaData = metaData;
137: String tableName = _activeMetaData.getTableName();
138: setWriter(new FileWriter(getTheDirectory() + File.separator
139: + tableName + ".csv"));
140: writeColumnNames();
141: getWriter().write(System.getProperty("line.separator"));
142: } catch (IOException e) {
143: logger.error("startTable()", e);
144:
145: throw new DataSetException(e);
146: }
147:
148: }
149:
150: private void writeColumnNames() throws DataSetException,
151: IOException {
152: logger.debug("writeColumnNames() - start");
153:
154: Column[] columns = _activeMetaData.getColumns();
155: for (int i = 0; i < columns.length; i++) {
156: String columnName = columns[i].getColumnName();
157: getWriter().write(columnName);
158: if (i < columns.length - 1)
159: getWriter().write(FIELD_SEPARATOR);
160: }
161: }
162:
163: public void endTable() throws DataSetException {
164: logger.debug("endTable() - start");
165:
166: try {
167: getWriter().close();
168: tableList.add(_activeMetaData.getTableName());
169: _activeMetaData = null;
170: } catch (IOException e) {
171: logger.error("endTable()", e);
172:
173: throw new DataSetException(e);
174: }
175: }
176:
177: public void row(Object[] values) throws DataSetException {
178: logger.debug("row(values=" + values + ") - start");
179:
180: try {
181:
182: Column[] columns = _activeMetaData.getColumns();
183: for (int i = 0; i < columns.length; i++) {
184: String columnName = columns[i].getColumnName();
185: Object value = values[i];
186:
187: // null
188: if (value == null) {
189: getWriter().write(NULL);
190: }
191: // none
192: else if (value == ITable.NO_VALUE) {
193: getWriter().write(NONE);
194: }
195: // values
196: else {
197: try {
198: String stringValue = DataType.asString(value);
199: final String quoted = quote(stringValue);
200: getWriter().write(quoted);
201: } catch (TypeCastException e) {
202: logger.error("row()", e);
203:
204: throw new DataSetException("table="
205: + _activeMetaData.getTableName()
206: + ", row=" + i + ", column="
207: + columnName + ", value=" + value, e);
208: }
209: }
210: if (i < columns.length - 1)
211: getWriter().write(",");
212: }
213: getWriter().write(System.getProperty("line.separator"));
214: } catch (IOException e) {
215: logger.error("row()", e);
216:
217: throw new DataSetException(e);
218: }
219: }
220:
221: private String quote(String stringValue) {
222: logger.debug("quote(stringValue=" + stringValue + ") - start");
223:
224: return new StringBuffer(QUOTE).append(escape(stringValue))
225: .append(QUOTE).toString();
226: }
227:
228: protected static String escape(String stringValue) {
229: logger.debug("escape(stringValue=" + stringValue + ") - start");
230:
231: char[] array = stringValue.toCharArray();
232: testExport = QUOTE.toCharArray()[0];
233: final char escape = ESCAPE.toCharArray()[0];
234: StringBuffer buffer = new StringBuffer();
235: for (int i = 0; i < array.length; i++) {
236: char c = array[i];
237: if (c == testExport || c == escape) {
238: buffer.append('\\');
239: }
240: buffer.append(c);
241: }
242: return buffer.toString();
243: }
244:
245: public Writer getWriter() {
246: logger.debug("getWriter() - start");
247:
248: return writer;
249: }
250:
251: public void setWriter(Writer writer) {
252: logger.debug("setWriter(writer=" + writer + ") - start");
253:
254: this .writer = writer;
255: }
256:
257: public String getTheDirectory() {
258: logger.debug("getTheDirectory() - start");
259:
260: return theDirectory;
261: }
262:
263: public void setTheDirectory(String theDirectory) {
264: logger.debug("setTheDirectory(theDirectory=" + theDirectory
265: + ") - start");
266:
267: this .theDirectory = theDirectory;
268: }
269:
270: public static void write(IDataSet dataset, File dest)
271: throws DataSetException {
272: logger.debug("write(dataset=" + dataset + ", dest=" + dest
273: + ") - start");
274:
275: CsvDataSetWriter writer = new CsvDataSetWriter(dest);
276: writer.write(dataset);
277: }
278:
279: protected void finalize() throws Throwable {
280: logger.debug("finalize() - start");
281:
282: if (getWriter() != null) {
283: getWriter().close();
284: }
285: }
286: }
|