1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.orangesignal.csv.handlers;
18
19 import java.io.IOException;
20 import java.sql.ResultSet;
21 import java.sql.ResultSetMetaData;
22 import java.sql.SQLException;
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import com.orangesignal.csv.CsvHandler;
27 import com.orangesignal.csv.CsvReader;
28 import com.orangesignal.csv.CsvResultSet;
29 import com.orangesignal.csv.CsvWriter;
30
31
32
33
34
35
36 public class ResultSetHandler implements CsvHandler<ResultSet> {
37
38
39
40
41
42
43 private boolean header = true;
44
45
46
47
48 public ResultSetHandler() {
49 }
50
51
52
53
54
55
56
57
58 public ResultSetHandler header(final boolean header) {
59 this.header = header;
60 return this;
61 }
62
63 @Override
64 public ResultSet load(final CsvReader reader) throws IOException {
65 return new CsvResultSet(reader);
66 }
67
68 @Override
69 public void save(final ResultSet rs, final CsvWriter writer) throws IOException {
70 try {
71 final int count = writeHeader(rs.getMetaData(), writer);
72 while (rs.next()) {
73 final List<String> list = new ArrayList<String>(count);
74 for (int i = 1; i <= count; i++) {
75 final Object o = rs.getObject(i);
76 if (rs.wasNull()) {
77 list.add(null);
78 } else {
79 list.add(o.toString());
80 }
81 }
82 writer.writeValues(list);
83 }
84 } catch (SQLException e) {
85 throw new IOException(e.getMessage(), e);
86 }
87 }
88
89 private int writeHeader(final ResultSetMetaData meta, final CsvWriter writer) throws IOException {
90 try {
91 final int count = meta.getColumnCount();
92 final List<String> list = new ArrayList<String>(count);
93 for (int i = 1; i <= count; i++) {
94 list.add(meta.getColumnLabel(i));
95 }
96 if (header) {
97 writer.writeValues(list);
98 }
99 return count;
100 } catch (SQLException e) {
101 throw new IOException(e.getMessage(), e);
102 }
103 }
104
105 }