001/**
002 * Copyright 2005-2013 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.rice.test;
017
018import org.apache.commons.lang.StringUtils;
019import org.apache.log4j.Logger;
020import org.springframework.core.io.DefaultResourceLoader;
021import org.springframework.jdbc.core.ConnectionCallback;
022import org.springframework.jdbc.core.JdbcTemplate;
023import org.springframework.transaction.TransactionStatus;
024import org.springframework.transaction.support.TransactionCallback;
025import org.springframework.transaction.support.TransactionTemplate;
026
027import java.io.BufferedReader;
028import java.io.InputStreamReader;
029import java.sql.Connection;
030import java.sql.SQLException;
031import java.sql.Statement;
032
033public class SQLDataLoader {
034
035    private static final Logger LOG = Logger.getLogger(SQLDataLoader.class);
036    public static final String SQL_LINE_COMMENT_PREFIX = "--";
037
038    private String fileLoc;
039    private String seperatorChar;
040    private String statement;
041
042    public SQLDataLoader(String statement) {
043        this.fileLoc = null;
044        this.seperatorChar = null;
045        this.statement = statement;
046    }
047
048    public SQLDataLoader(String fileLoc, String seperatorChar) {
049        this.fileLoc = fileLoc;
050        this.seperatorChar = seperatorChar;
051        this.statement = null;
052    }
053
054    public void runSql() throws Exception {
055        String[] sqlStatements = null;
056        if (statement == null) {
057            String sqlStatementsContent = getContentsAsString(fileLoc);
058            // separator char must be the last non-whitespace char on the line
059            // to avoid splitting in the middle of data that might contain the separator char
060            sqlStatements = sqlStatementsContent.split("(?m)" + getSeperatorChar() + "\\s*$");
061        } else {
062            sqlStatements = new String[]{statement};
063        }
064        final String[] finalSqlStatements = sqlStatements;
065        new TransactionTemplate(TestHarnessServiceLocator.getJtaTransactionManager()).execute(new TransactionCallback() {
066            public Object doInTransaction(TransactionStatus status) {
067                return new JdbcTemplate(TestHarnessServiceLocator.getDataSource()).execute(new ConnectionCallback() {
068                    public Object doInConnection(Connection connection) throws SQLException {
069                        Statement statement = connection.createStatement();
070                        LOG.info("################################");
071                        LOG.info(fileLoc != null ? "#" + fileLoc : "#");
072                        LOG.info("#");
073                        for (String sqlStatement : finalSqlStatements) {
074                            if (StringUtils.isNotBlank(sqlStatement)) {
075                                LOG.info("# Executing sql statement ->" + sqlStatement + "<-");
076                                statement.execute(sqlStatement);
077                            }
078                        }
079                        LOG.info("#");
080                        LOG.info("#");
081                        LOG.info("################################");
082                        statement.close();
083                        return null;
084                    }
085                });
086            }
087        });
088    }
089
090    private String getContentsAsString(String fileLoc) throws Exception {
091        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
092        String data = "";
093        BufferedReader reader = null;
094        try {
095            reader = new BufferedReader(new InputStreamReader(resourceLoader.getResource(fileLoc).getInputStream()));
096            String line = "";
097            while ((line = reader.readLine()) != null) {
098                // discard comments...commented single line statements
099                // will result in errors when executed because there are no
100                // results
101                if (!line.trim().startsWith(SQL_LINE_COMMENT_PREFIX)) {
102                    data += line + "\r\n ";
103                }
104            }
105        } finally {
106            if (reader != null) {
107                try {
108                    reader.close();
109                } catch (Exception e) {
110                    LOG.error(e);
111                }
112            }
113
114        }
115        return data;
116    }
117
118    public String getSeperatorChar() {
119        if (this.seperatorChar == null) {
120            return ";";
121        }
122        return seperatorChar;
123    }
124
125}