View Javadoc

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.test.spring;
17  
18  import java.io.BufferedReader;
19  import java.io.File;
20  import java.io.FileReader;
21  import java.util.List;
22  import java.util.Map;
23  
24  import javax.persistence.EntityManager;
25  import javax.persistence.PersistenceContext;
26  import javax.persistence.PersistenceException;
27  
28  import org.apache.commons.lang.StringUtils;
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.springframework.context.ApplicationContext;
32  import org.springframework.context.ApplicationContextAware;
33  import org.springframework.context.ConfigurableApplicationContext;
34  import org.springframework.context.support.FileSystemXmlApplicationContext;
35  import org.springframework.core.io.ClassPathResource;
36  import org.springframework.transaction.annotation.Transactional;
37  
38  @Deprecated
39  @Transactional
40  public class LoadDataBean implements ApplicationContextAware{
41  	private static final Log LOG = LogFactory.getLog(LoadDataBean.class);
42  
43  
44  
45  	@PersistenceContext
46  	EntityManager em;
47  	private boolean loaded = false;
48  	private String daoAnnotations;
49  
50  	private ApplicationContext applicationContext;
51  
52  	public void loadData(){
53  		if (daoAnnotations == null || loaded || daoAnnotations.trim().isEmpty()) {
54  			return;
55  		}
56  
57  		// Load all the beans
58  		String[] classes = daoAnnotations.split(",");
59  		for (String line : classes) {
60  			try {
61  				String[] split = line.split("\\|");
62  
63  				// Invoke the data loader for this dao
64                  invokeDataLoader(split[0]);
65  
66                  // Load data bean file for this dao
67                  if (split.length > 1&& !split[1].isEmpty()) {
68  				    String testDataFile = split[1];
69  
70  					ConfigurableApplicationContext ac = new FileSystemXmlApplicationContext(
71  							testDataFile);
72                      List<?> persistList = (List<?>) ac.getBean("persistList");
73                      ac.close();
74                      for (Object bean : persistList) {
75  						if(!em.contains(bean)){
76  							em.persist(bean);
77  						}
78  					}
79  				}
80                  // Load sql file for this dao
81                  if (split.length > 2&& !split[2].isEmpty()) {
82  
83  					String testDataFile = split[2];
84  				    File sqlFile;
85  				    if(testDataFile.startsWith("classpath:")){
86  				 	   sqlFile = new ClassPathResource(testDataFile.substring("classpath:".length())).getFile();
87  				    }else{
88  				    	sqlFile = new File(testDataFile);
89  				    }
90  					BufferedReader in
91  					   = new BufferedReader(new FileReader(sqlFile));
92  					try {
93      					String ln = "";
94      					int lnNr = 0;
95  
96      					try {
97                              while((ln=in.readLine())!=null){
98                                  lnNr++;
99                              	if(!ln.startsWith("/")&&!ln.startsWith("--")&&StringUtils.isNotBlank(ln)){
100                             		ln=ln.replaceFirst("[;/]\\s*$","");
101                             		em.createNativeQuery(ln).executeUpdate();
102                             	}
103                             }
104                         } catch (PersistenceException e) {
105                             LOG.error("Failed statement at line " + lnNr + ": " + ln);
106                             throw e;
107                         }
108 					} finally {
109 					    in.close();
110 					}
111 				}
112 
113 			} catch (Exception e) {
114 				throw new RuntimeException(e);
115 			}
116 		}
117 
118 		loaded = true;
119 
120 	}
121 
122 	protected void invokeDataLoader(String dao){
123 	    try {
124             //Check if there is a loader class for this dao
125 	        Class<?> daoType = Class.forName(dao).getInterfaces()[0];
126 
127 	        Class<?> clazz = Class.forName(daoType.getName() + "Loader");
128             DaoLoader daoLoader = (DaoLoader)clazz.newInstance();
129 
130             //Get spring bean for the dao
131             Map<?,?> daoBeans = applicationContext.getBeansOfType(daoType);
132 
133             //Invoke the loader for this doa bean (there shouldn't be more than one)
134             if (daoBeans.size() == 1){
135                 daoLoader.setDao(daoBeans.values().iterator().next());
136                 daoLoader.run();
137             }
138 
139 	    } catch (ClassNotFoundException cnfe) {
140 	    	LOG.info(cnfe);
141 	    } catch (Exception e) {
142             LOG.error(e);
143         }
144 	}
145 
146 	/**
147 	 * @return the daoAnnotations
148 	 */
149 	public String getDaoAnnotations() {
150 		return daoAnnotations;
151 	}
152 
153 	/**
154 	 * @param daoAnnotations
155 	 *            the daoAnnotations to set
156 	 */
157 	public void setDaoAnnotations(String daoAnnotations) {
158 		this.daoAnnotations = daoAnnotations;
159 	}
160 
161 	public void setApplicationContext(ApplicationContext applicationContext){
162 	    this.applicationContext = applicationContext;
163 	}
164 }