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