All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.etlunit.io.file.RelationalDataFileWriterImpl Maven / Gradle / Ivy

package org.etlunit.io.file;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

class RelationalDataFileWriterImpl implements DataFileWriter
{
	private final FlatFile flatFile;

	private final DataFile.DataConverter converter;

	BufferedWriter bwriter;
	int rowNum = 0;

	public RelationalDataFileWriterImpl(DataFile.DataConverter converter, FlatFile flatFile) throws IOException
	{
		this.converter = converter;

		this.flatFile = flatFile;

		bwriter = new BufferedWriter(new FileWriter(flatFile.getSource()));

		// write out the column header
		List columns = flatFile.getDataFileSchema().getColumns();

		int size = columns.size();

		StringBuffer typeRow = new StringBuffer();

		// write this in a comment block
		bwriter.write("/*-- ");

		String columnDelimiter = flatFile.getDataFileSchema().getColumnDelimiter();

		if (columnDelimiter == null)
		{
			columnDelimiter = "|";
		}

		for (int i = 0; i < size; i++)
		{
			DataFileSchema.Column colu = columns.get(i);

			bwriter.write(colu.getId());

			typeRow.append(colu.getType());

			if (i != (size - 1))
			{
				bwriter.write(columnDelimiter);

				typeRow.append(columnDelimiter);
			}
		}

		bwriter.write("  --*/");
		bwriter.write(flatFile.getDataFileSchema().getRowDelimiter());

		// write this in a comment block
		bwriter.write("/*-- ");
		bwriter.write(typeRow.toString());
		bwriter.write("  --*/");
	}

	public void addRow(Map rowData) throws IOException
	{
		bwriter.write(flatFile.getDataFileSchema().getRowDelimiter());

		rowNum++;

		List columns = flatFile.getDataFileSchema().getColumns();

		for (int i = 0; i < columns.size(); i++)
		{
			if (i != 0)
			{
				if (flatFile.getDataFileSchema().getColumnDelimiter() != null)
				{
					bwriter.write(flatFile.getDataFileSchema().getColumnDelimiter());
				}
			}

			DataFileSchema.Column col = columns.get(i);

			Object data = rowData.get(col.getId());

			String text = flatFile.getDataFileSchema().getNullToken();

			if (data != null)
			{
				text = converter.format(data, col);
			}

			if (col.getLength() != -1 && flatFile.getDataFileSchema().getFormatType() == DataFileSchema.format_type.fixed)
			{
				int min = col.getLength();

				if (text.length() != min)
				{
					text =
							"                                                                                                     "
									+ text;
					text = text.substring(text.length() - min);
				}
			}

			bwriter.write(text);
		}
	}

	public void close() throws IOException
	{
		bwriter.close();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy