1 9 package com.ziclix.python.sql.pipe.csv; 10 11 import com.ziclix.python.sql.pipe.Sink; 12 import org.python.core.Py; 13 import org.python.core.PyObject; 14 15 import java.io.PrintWriter ; 16 17 23 public class CSVSink implements Sink { 24 25 28 protected boolean header; 29 30 33 protected String delimiter; 34 35 38 protected PrintWriter writer; 39 40 43 protected PyObject converters; 44 45 50 public CSVSink(PrintWriter writer) { 51 this(writer, Py.None); 52 } 53 54 62 public CSVSink(PrintWriter writer, PyObject converters) { 63 64 this.header = false; 65 this.writer = writer; 66 this.converters = converters; 67 this.delimiter = ","; 68 } 69 70 73 public void row(PyObject row) { 74 75 String [] values = new String [row.__len__()]; 76 77 if (this.header) { 78 for (int i = 0; i < row.__len__(); i++) { 79 values[i] = this.convert(Py.newInteger(i), row.__getitem__(i)); 80 } 81 } else { 82 for (int i = 0; i < row.__len__(); i++) { 83 values[i] = row.__getitem__(i).__getitem__(0).toString(); 84 } 85 86 this.header = true; 87 } 88 89 this.println(values); 90 } 91 92 95 protected String convert(PyObject index, PyObject object) { 96 97 if (this.converters != Py.None) { 98 PyObject converter = this.converters.__finditem__(index); 99 100 if (converter != Py.None) { 101 object = converter.__call__(object); 102 } 103 } 104 105 if ((object == Py.None) || (object == null)) { 106 return ""; 107 } 108 109 return CSVString.toCSV(object.toString()); 110 } 111 112 115 protected void println(String [] row) { 116 117 for (int i = 0; i < row.length - 1; i++) { 118 this.writer.print(row[i]); 119 this.writer.print(this.delimiter); 120 } 121 122 this.writer.println(row[row.length - 1]); 123 } 124 125 128 public void start() { 129 } 130 131 134 public void end() { 135 } 136 } 137 | Popular Tags |