001 /**
002 * Copyright 2004-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 */
016 package org.kuali.hr.time.util;
017
018 import java.sql.SQLException;
019 import java.sql.Statement;
020 import java.util.ArrayList;
021 import java.util.List;
022
023 import javax.sql.DataSource;
024
025 import junit.framework.Assert;
026
027 import org.apache.commons.lang.StringUtils;
028 import org.springframework.jdbc.core.JdbcTemplate;
029 import org.springframework.jdbc.core.StatementCallback;
030 import org.springframework.transaction.PlatformTransactionManager;
031 import org.springframework.transaction.TransactionStatus;
032 import org.springframework.transaction.support.TransactionCallback;
033 import org.springframework.transaction.support.TransactionTemplate;
034
035 public class DatabaseCleanupDataLifecycle extends SQLDataLifeCycle {
036
037 public DatabaseCleanupDataLifecycle(Class caller) {
038 super(caller);
039 }
040
041 public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource, final String schemaName) {
042 Assert.assertNotNull("DataSource could not be located.", dataSource);
043
044 if (schemaName == null || schemaName.equals("")) {
045 Assert.fail("Empty schema name given");
046 }
047 new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
048 public Object doInTransaction(final TransactionStatus status) {
049 verifyTestEnvironment(dataSource);
050 return new JdbcTemplate(dataSource).execute(new StatementCallback() {
051 public Object doInStatement(Statement statement) throws SQLException {
052 List<String> sqlStatements = new ArrayList<String>();
053 //
054 // djunk - add a per-class special test data loader,
055 // loads <testclassname>.sql from the same directory
056 // as the other SQL loaded.
057 if (callingTestClass != null) {
058 sqlStatements.addAll(getTestDataSQLStatements("src/test/config/sql/" + callingTestClass.getSimpleName() + "-cleanup.sql"));
059 }
060 for(String sql : sqlStatements){
061 if (!sql.startsWith("#") && !sql.startsWith("//") && !StringUtils.isEmpty(sql.trim())) {
062 // ignore comment lines in our sql reader.
063 statement.addBatch(sql);
064 }
065 }
066 statement.executeBatch();
067 return null;
068 }
069 });
070 }
071 });
072 }
073 }