1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.ken.test;
17
18
19 import java.io.BufferedReader;
20 import java.io.InputStreamReader;
21 import java.sql.Connection;
22 import java.sql.Statement;
23
24 import javax.sql.DataSource;
25
26 import org.apache.commons.lang.StringUtils;
27 import org.apache.log4j.Logger;
28 import org.springframework.core.io.DefaultResourceLoader;
29
30
31
32
33 public class SQLDataLoader {
34 private static final Logger LOG = Logger.getLogger(SQLDataLoader.class);
35 public static final String SQL_LINE_COMMENT_PREFIX = "--";
36
37 private String fileLoc;
38 private String seperatorChar;
39 private DataSource dataSource;
40
41 public SQLDataLoader(String fileLoc, String seperatorChar, DataSource dataSource) {
42 this.fileLoc = fileLoc;
43 this.seperatorChar = seperatorChar;
44 this.dataSource = dataSource;
45 }
46
47 public void runSql() throws Exception {
48 String sqlStatementsContent = getContentsAsString(fileLoc);
49 String[] sqlStatements = sqlStatementsContent.split(getSeperatorChar());
50 Connection conn = dataSource.getConnection();
51 Statement statement = conn.createStatement();
52 LOG.info("################################");
53 LOG.info("#");
54 LOG.info("#");
55 for (String sqlStatement : sqlStatements) {
56
57 if (StringUtils.isNotBlank(sqlStatement)) {
58
59 LOG.info("# Executing sql statement ->" + sqlStatement + "<-");
60 statement.execute(sqlStatement);
61 }
62
63 }
64 LOG.info("#");
65 LOG.info("#");
66 LOG.info("################################");
67 try {
68 statement.close();
69 }
70 catch (Exception e) {
71 LOG.error(e);
72 }
73 try {
74 conn.close();
75 }
76 catch (Exception e) {
77 LOG.error(e);
78 }
79
80 }
81
82 private String getContentsAsString(String fileLoc) throws Exception {
83 DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
84 String data = "";
85 BufferedReader reader = null;
86 try {
87 reader = new BufferedReader(new InputStreamReader(resourceLoader.getResource(fileLoc).getInputStream()));
88 String line = "";
89 while ((line = reader.readLine()) != null) {
90
91
92
93 if (!line.trim().startsWith(SQL_LINE_COMMENT_PREFIX)) {
94 data += line + " ";
95 }
96 }
97 }
98 finally {
99 if (reader != null) {
100 try {
101 reader.close();
102 }
103 catch (Exception e) {
104 LOG.error(e);
105 }
106 }
107
108 }
109 return data;
110 }
111
112 public String getSeperatorChar() {
113 if (this.seperatorChar == null) {
114 return ";";
115 }
116 return seperatorChar;
117 }
118
119 }