1 package org.kuali.common.jdbc.supplier;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.util.List;
6
7 import org.apache.commons.io.IOUtils;
8 import org.kuali.common.jdbc.DefaultSqlReader;
9 import org.kuali.common.jdbc.JdbcUtils;
10 import org.kuali.common.jdbc.SqlMetaData;
11 import org.kuali.common.jdbc.SqlReader;
12 import org.kuali.common.util.LocationUtils;
13 import org.springframework.util.Assert;
14
15
16
17
18 public class ComplexStringSupplier extends AbstractSupplier {
19
20 protected int index = 0;
21 protected BufferedReader in;
22
23 List<String> strings;
24 SqlReader reader = new DefaultSqlReader();
25
26 public ComplexStringSupplier() {
27 this(null);
28 }
29
30 public ComplexStringSupplier(List<String> strings) {
31 super();
32 this.strings = strings;
33 }
34
35 @Override
36 public void open() {
37
38
39 Assert.notNull(strings, "strings is null");
40
41
42 index = 0;
43
44
45 in = getBufferedReader(strings, index);
46 }
47
48 @Override
49 public List<String> getSql() {
50 try {
51
52 List<String> sql = reader.getSql(in);
53
54 if (sql != null) {
55
56 return sql;
57 } else {
58
59 index++;
60 }
61
62
63 if (index == strings.size()) {
64 return null;
65 }
66
67
68 in = getBufferedReader(strings, index);
69
70
71 return getSql();
72 } catch (IOException e) {
73 throw new IllegalStateException(e);
74 }
75 }
76
77
78
79
80 protected BufferedReader getBufferedReader(List<String> strings, int index) {
81 String string = strings.get(index);
82 return LocationUtils.getBufferedReaderFromString(string);
83 }
84
85 @Override
86 public void close() {
87
88 index = 0;
89
90
91 IOUtils.closeQuietly(in);
92 }
93
94 @Override
95 public void fillInMetaData() {
96 long count = 0;
97 long size = 0;
98 for (String string : strings) {
99 SqlMetaData smd = getMetaData(string);
100 count += smd.getCount();
101 size += smd.getSize();
102 }
103 this.metaData = new SqlMetaData(count, size);
104 }
105
106 protected SqlMetaData getMetaData(String sql) {
107 BufferedReader in = null;
108 try {
109 in = LocationUtils.getBufferedReaderFromString(sql);
110 return JdbcUtils.getSqlMetaData(in, reader);
111 } catch (IOException e) {
112 throw new IllegalStateException(e);
113 } finally {
114 IOUtils.closeQuietly(in);
115 }
116 }
117
118 public List<String> getStrings() {
119 return strings;
120 }
121
122 public void setStrings(List<String> strings) {
123 this.strings = strings;
124 }
125
126 public SqlReader getReader() {
127 return reader;
128 }
129
130 public void setReader(SqlReader reader) {
131 this.reader = reader;
132 }
133
134 }