001/**
002 * Copyright 2005-2014 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.logging.log4j.Logger;
020import org.apache.logging.log4j.LogManager;
021import org.kuali.rice.core.api.util.ClasspathOrFileResourceLoader;
022import org.springframework.jdbc.core.ConnectionCallback;
023import org.springframework.jdbc.core.JdbcTemplate;
024import org.springframework.transaction.TransactionStatus;
025import org.springframework.transaction.support.TransactionCallback;
026import org.springframework.transaction.support.TransactionTemplate;
027
028import java.io.BufferedReader;
029import java.io.InputStreamReader;
030import java.sql.Connection;
031import java.sql.SQLException;
032import java.sql.Statement;
033
034public class SQLDataLoader {
035
036    private static final Logger LOG = LogManager.getLogger(SQLDataLoader.class);
037    public static final String SQL_LINE_COMMENT_PREFIX = "--";
038
039    private String fileLoc;
040    private String seperatorChar;
041    private String statement;
042
043    public SQLDataLoader(String statement) {
044        this.fileLoc = null;
045        this.seperatorChar = null;
046        this.statement = statement;
047    }
048
049    public SQLDataLoader(String fileLoc, String seperatorChar) {
050        this.fileLoc = fileLoc;
051        this.seperatorChar = seperatorChar;
052        this.statement = null;
053    }
054
055    public void runSql() throws Exception {
056        String[] sqlStatements = null;
057        if (statement == null) {
058            String sqlStatementsContent = getContentsAsString(fileLoc);
059            // separator char must be the last non-whitespace char on the line
060            // to avoid splitting in the middle of data that might contain the separator char
061            sqlStatements = sqlStatementsContent.split("(?m)" + getSeperatorChar() + "\\s*$");
062        } else {
063            sqlStatements = new String[]{statement};
064        }
065        final String[] finalSqlStatements = sqlStatements;
066        new TransactionTemplate(TestHarnessServiceLocator.getJtaTransactionManager()).execute(new TransactionCallback() {
067            public Object doInTransaction(TransactionStatus status) {
068                return new JdbcTemplate(TestHarnessServiceLocator.getDataSource()).execute(new ConnectionCallback() {
069                    public Object doInConnection(Connection connection) throws SQLException {
070                        Statement statement = connection.createStatement();
071                        LOG.info("################################");
072                        LOG.info(fileLoc != null ? "#" + fileLoc : "#");
073                        LOG.info("#");
074                        for (String sqlStatement : finalSqlStatements) {
075                            if (StringUtils.isNotBlank(sqlStatement)) {
076                                LOG.info("# Executing sql statement ->" + sqlStatement + "<-");
077                                statement.execute(sqlStatement);
078                            }
079                        }
080                        LOG.info("#");
081                        LOG.info("#");
082                        LOG.info("################################");
083                        statement.close();
084                        return null;
085                    }
086                });
087            }
088        });
089    }
090
091    private String getContentsAsString(String fileLoc) throws Exception {
092        ClasspathOrFileResourceLoader resourceLoader = new ClasspathOrFileResourceLoader();
093        String data = "";
094        BufferedReader reader = null;
095        try {
096            reader = new BufferedReader(new InputStreamReader(resourceLoader.getResource(fileLoc).getInputStream()));
097            String line = "";
098            while ((line = reader.readLine()) != null) {
099                // discard comments...commented single line statements
100                // will result in errors when executed because there are no
101                // results
102                if (!line.trim().startsWith(SQL_LINE_COMMENT_PREFIX)) {
103                    data += line + "\r\n ";
104                }
105            }
106        } finally {
107            if (reader != null) {
108                try {
109                    reader.close();
110                } catch (Exception e) {
111                    LOG.error(e);
112                }
113            }
114
115        }
116        return data;
117    }
118
119    public String getSeperatorChar() {
120        if (this.seperatorChar == null) {
121            return ";";
122        }
123        return seperatorChar;
124    }
125
126}