Coverage Report - org.kuali.student.common.util.jpa.LoadSqlListener
 
Classes in this File Line Coverage Branch Coverage Complexity
LoadSqlListener
0%
0/51
0%
0/22
2.875
 
 1  
 /**
 2  
  * Copyright 2010 The Kuali Foundation Licensed under the
 3  
  * Educational Community License, Version 2.0 (the "License"); you may
 4  
  * not use this file except in compliance with the License. You may
 5  
  * obtain a copy of the License at
 6  
  *
 7  
  * http://www.osedu.org/licenses/ECL-2.0
 8  
  *
 9  
  * Unless required by applicable law or agreed to in writing,
 10  
  * software distributed under the License is distributed on an "AS IS"
 11  
  * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 12  
  * or implied. See the License for the specific language governing
 13  
  * permissions and limitations under the License.
 14  
  */
 15  
 
 16  
 package org.kuali.student.common.util.jpa;
 17  
 
 18  
 import java.io.BufferedReader;
 19  
 import java.io.File;
 20  
 import java.io.FileReader;
 21  
 import java.io.IOException;
 22  
 import java.util.List;
 23  
 import java.util.Map;
 24  
 import java.util.Map.Entry;
 25  
 
 26  
 import javax.persistence.EntityManager;
 27  
 import javax.persistence.EntityManagerFactory;
 28  
 
 29  
 import org.apache.commons.lang.StringUtils;
 30  
 import org.slf4j.Logger;
 31  
 import org.slf4j.LoggerFactory;
 32  
 import org.springframework.beans.BeansException;
 33  
 import org.springframework.context.ApplicationContext;
 34  
 import org.springframework.context.ApplicationContextAware;
 35  
 import org.springframework.context.ApplicationEvent;
 36  
 import org.springframework.context.ApplicationListener;
 37  
 import org.springframework.context.event.ContextRefreshedEvent;
 38  
 import org.springframework.core.io.ClassPathResource;
 39  
 import org.springframework.orm.jpa.EntityManagerFactoryUtils;
 40  
 import org.springframework.orm.jpa.SharedEntityManagerCreator;
 41  
 import org.springframework.transaction.TransactionDefinition;
 42  
 import org.springframework.transaction.TransactionStatus;
 43  
 import org.springframework.transaction.jta.JtaTransactionManager;
 44  
 import org.springframework.transaction.support.DefaultTransactionDefinition;
 45  
 
 46  
 /**
 47  
  * This Spring listener will load SQL files into your database after the context is loaded
 48  
  * This is used in testing when you need to load data before your tests are run.
 49  
  * To Configure, you will need the jtaTxManager from your application context (use ref="JtaTxManager" with our unit tests)
 50  
  * You will also need a map of persistence unit names to the sql files you want loaded. 
 51  
  * 
 52  
  * <p>Example configuration:</p>
 53  
  * <pre>
 54  
  * {@code
 55  
  *        <!--  Preloaded data -->
 56  
  *        <bean id="dataLoadListenerLum" class="org.kuali.student.common.util.jpa.LoadSqlListener">
 57  
  *                <property name="jtaTxManager" ref="JtaTxManager"/>
 58  
  *                <property name="shouldLoadData" value="true"/>
 59  
  *                <property name="preloadMap">
 60  
  *                        <map>
 61  
  *                                <entry key="Lu">
 62  
  *                                        <value>classpath:ks-lu.sql</value>
 63  
  *                                </entry>
 64  
  *                                <entry key="Statement">
 65  
  *                                        <list>
 66  
  *                                                <value>classpath:ks-statement.sql</value>
 67  
  *                                                <value>classpath:ks-statement-tree.sql</value>
 68  
  *                                        </list>
 69  
  *                                </entry>
 70  
  *                        </map>
 71  
  *                </property>
 72  
  *        </bean>
 73  
  * }
 74  
  * </pre>
 75  
  */
 76  0
 public class LoadSqlListener implements ApplicationListener,
 77  
                 ApplicationContextAware {
 78  
 
 79  0
         final static Logger logger = LoggerFactory.getLogger(LoadSqlListener.class);
 80  
 
 81  
         private ApplicationContext applicationContext;
 82  
 
 83  0
         private boolean loaded = false;
 84  
 
 85  
         private Map<String,Object> preloadMap;
 86  
         private JtaTransactionManager jtaTxManager;
 87  
 
 88  0
         private boolean shouldLoadData = false;
 89  
 
 90  
         @Override
 91  
         @SuppressWarnings("unchecked") 
 92  
         public void onApplicationEvent(ApplicationEvent event) {
 93  0
                 if (event instanceof ContextRefreshedEvent && !loaded && shouldLoadData) {
 94  
 
 95  0
                         for (Entry<String, Object> entry : preloadMap.entrySet()) {
 96  0
                                 if(entry.getValue() instanceof java.util.List<?>) {
 97  0
                                         List<String> sqlFileList = (List<String>) entry.getValue();
 98  0
                                         for(String sqlFile : sqlFileList) {
 99  0
                                                 process(entry.getKey(), sqlFile);
 100  
                                         }
 101  0
                                 } else {
 102  0
                                         process(entry.getKey(), entry.getValue().toString());
 103  
                                 }
 104  
                         }
 105  0
                         loaded=true;
 106  
                 }
 107  0
         }
 108  
         
 109  
         private void process(String entityKey, String sqlFileName) {
 110  0
                 EntityManagerFactory emf = EntityManagerFactoryUtils
 111  
                                 .findEntityManagerFactory(applicationContext, entityKey);
 112  0
                 EntityManager em = SharedEntityManagerCreator
 113  
                                 .createSharedEntityManager(emf);
 114  
 
 115  
                 File sqlFile;
 116  
                 BufferedReader in;
 117  
                 try{
 118  0
                     if(sqlFileName.startsWith("classpath:")){
 119  0
                                   sqlFile = new ClassPathResource(sqlFileName.substring("classpath:".length())).getFile();
 120  
                         }else{
 121  0
                             sqlFile = new File(sqlFileName);
 122  
                     }
 123  0
                         in = new BufferedReader(new FileReader(sqlFile));
 124  0
                 } catch (Exception e) {
 125  0
                         throw new RuntimeException(e);
 126  0
                 }
 127  
 
 128  0
                 String ln = "";
 129  
 
 130  0
                 TransactionDefinition txDefinition = new DefaultTransactionDefinition() ;
 131  0
                 TransactionStatus txStatus = jtaTxManager.getTransaction(txDefinition);
 132  
 
 133  
                 try {
 134  0
                         while((ln=in.readLine())!=null){
 135  0
                                 if(!ln.startsWith("/")&&!ln.startsWith("--")&&StringUtils.isNotBlank(ln)){
 136  0
                                         ln=ln.replaceFirst("[;/]\\s*$","");
 137  0
                                         em.createNativeQuery(ln).executeUpdate();
 138  
                                 }
 139  
                         }
 140  0
                         jtaTxManager.commit(txStatus);
 141  0
                 } catch (Exception e) {
 142  0
                         logger.error("Error loading sql file "+sqlFileName+". Failing statement was '" + ln + "'",e);
 143  0
                         jtaTxManager.rollback(txStatus);
 144  
                 }
 145  
                 finally{
 146  0
                         try {
 147  0
                                 in.close();
 148  0
                         } catch (IOException e) {
 149  0
                                 logger.error("IO Stream closed " + e);
 150  0
                         }
 151  0
                 }
 152  0
         }
 153  
 
 154  
         @Override
 155  
         public void setApplicationContext(ApplicationContext applicationContext)
 156  
                         throws BeansException {
 157  0
                 this.applicationContext = applicationContext;
 158  0
         }
 159  
 
 160  
         public JtaTransactionManager getJtaTxManager() {
 161  0
                 return jtaTxManager;
 162  
         }
 163  
 
 164  
         /**
 165  
          * A reference to a jta tx manager. To use with KS unit test framework,
 166  
          * use ref="JtaTxManager"
 167  
          * @param jtaTxManager
 168  
          */
 169  
         public void setJtaTxManager(JtaTransactionManager jtaTxManager) {
 170  0
                 this.jtaTxManager = jtaTxManager;
 171  0
         }
 172  
 
 173  
         public Map<String, Object> getPreloadMap() {
 174  0
                 return preloadMap;
 175  
         }
 176  
 
 177  
         /**
 178  
          * This is a map of persistence unit names to sql files
 179  
          * The file names are loaded as spring classpath resources so you can use the syntax "classpath:ks-lu.sql"
 180  
          * @param preloadMap
 181  
          */
 182  
         public void setPreloadMap(Map<String, Object> preloadMap) {
 183  0
                 this.preloadMap = preloadMap;
 184  0
         }
 185  
 
 186  
         /**
 187  
          * Sets whether data is loaded or not so that this param can be configured by properties
 188  
          * @param shouldLoadData defaults to false so you will need to set to true if you want data loaded.
 189  
          */
 190  
         public void setShouldLoadData(boolean shouldLoadData) {
 191  0
                 this.shouldLoadData = shouldLoadData;
 192  0
         }
 193  
 
 194  
 }