View Javadoc

1   /**
2    * Copyright 2012 The Kuali Foundation
3    *
4    * Licensed under the the Educational Community License, Version 1.0
5    * (the "License"); you may not use this file except in compliance
6    * with the License.  You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl1.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.kuali.student.enrollment.class1.lpr.service.impl;
18  
19  import static org.junit.Assert.assertEquals;
20  import static org.junit.Assert.assertNotNull;
21  import static org.junit.Assert.assertTrue;
22  import static org.junit.Assert.fail;
23  
24  import java.sql.ResultSet;
25  import java.sql.ResultSetMetaData;
26  import java.sql.SQLException;
27  import java.sql.Timestamp;
28  import java.util.Date;
29  import java.util.concurrent.atomic.AtomicInteger;
30  
31  import javax.annotation.Resource;
32  import javax.sql.DataSource;
33  
34  import org.apache.log4j.Logger;
35  import org.junit.After;
36  import org.junit.Assert;
37  import org.junit.Before;
38  import org.junit.Test;
39  import org.junit.runner.RunWith;
40  import org.kuali.student.enrollment.class1.lpr.dao.LprDao;
41  import org.kuali.student.enrollment.class1.lpr.service.impl.mock.LprTestDataLoader;
42  import org.kuali.student.enrollment.lpr.dto.LprInfo;
43  import org.kuali.student.enrollment.lpr.service.LprService;
44  import org.kuali.student.enrollment.test.util.AttributeTester;
45  import org.kuali.student.enrollment.test.util.ListOfStringTester;
46  import org.kuali.student.enrollment.test.util.MetaTester;
47  import org.kuali.student.enrollment.test.util.RelationshipTester;
48  import org.kuali.student.r2.common.dto.AttributeInfo;
49  import org.kuali.student.r2.common.dto.ContextInfo;
50  import org.kuali.student.r2.common.dto.StatusInfo;
51  import org.kuali.student.r2.common.exceptions.DoesNotExistException;
52  import org.kuali.student.r2.common.util.constants.LprServiceConstants;
53  import org.springframework.test.annotation.Rollback;
54  import org.springframework.test.context.ContextConfiguration;
55  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
56  import org.springframework.test.context.transaction.TransactionConfiguration;
57  import org.springframework.transaction.PlatformTransactionManager;
58  import org.springframework.transaction.TransactionDefinition;
59  import org.springframework.transaction.TransactionStatus;
60  import org.springframework.transaction.annotation.Transactional;
61  import org.springframework.transaction.support.TransactionCallback;
62  import org.springframework.transaction.support.TransactionTemplate;
63  
64  @RunWith(SpringJUnit4ClassRunner.class)
65  @ContextConfiguration(locations = { "classpath:lpr-test-context.xml" })
66  @TransactionConfiguration(transactionManager = "JtaTxManager", defaultRollback = false)
67  /**
68   * Here all of the test methods are not transactional.
69   * 
70   * This allows us to call crud methods on a service and have then occur transactionally within each call (rather than inherit from an outer transactional scope).
71   * 
72   * We can also go behind and check out the resultant database content for consistency.
73   * 
74   * @author ocleirig
75   *
76   */
77  public class TestLprServiceTransactionallyImpl {
78  
79  	private static final Logger log = Logger
80  			.getLogger(TestLprServiceTransactionallyImpl.class);
81  
82  	public LprService getLprService() {
83  		return lprService;
84  	}
85  
86  	public void setLprService(LprService lprService) {
87  		this.lprService = lprService;
88  	}
89  
90  	@Resource
91  	private LprService lprService;
92  
93  	@Resource
94  	private LprDao lprDao;
95  
96  	@Resource
97  	private DataSource dataSource;
98  
99  	@Resource(name = "JtaTxManager")
100 	private PlatformTransactionManager txManager;
101 
102 	private TransactionTemplate txTemplate;
103 
104 	private ContextInfo callContext;
105 
106 	public LprDao getLprDao() {
107 		return lprDao;
108 	}
109 
110 	public void setLprDao(LprDao lprDao) {
111 		this.lprDao = lprDao;
112 	}
113 
114 	@Before
115 	public  void setUp() {
116 		// intentionally does not call super.setUp()
117 
118 			String principalId = "123";
119 			callContext = new ContextInfo();
120 			callContext.setPrincipalId(principalId);
121 
122 			txTemplate = new TransactionTemplate(txManager);
123 
124 			txTemplate
125 					.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
126 			txTemplate.execute(new TransactionCallback<Void>() {
127 
128 				@Override
129 				public Void doInTransaction(TransactionStatus status) {
130 
131 					try {
132 						
133 						if (lprDao.findAll().size() == 0)
134 							new LprTestDataLoader(lprDao).loadData();
135 					} catch (Exception ex) {
136 						throw new RuntimeException(ex);
137 					}
138 					return null;
139 				}
140 
141 			});
142 
143 	}
144 	
145 	@After
146 	public void cleanup() {
147 		
148 	}
149 
150 	
151 
152 	
153 	
154 
155 	/**
156 	 * Tests that the deleteOrphan JPA annotation is working properly.
157 	 * 
158 	 * @throws Exception
159 	 */
160 	@Test
161 	public void testDeleteOrphanAnnotation() throws Exception {
162 
163 		Assert.assertTrue(true);
164 
165 		// test create
166 		LprInfo expected = new LprInfo();
167 		expected.setPersonId("person1");
168 		expected.setLuiId("lui1");
169 		expected.setTypeKey(LprServiceConstants.INSTRUCTOR_MAIN_TYPE_KEY);
170 		expected.setStateKey(LprServiceConstants.ASSIGNED_STATE_KEY);
171 		expected.setEffectiveDate(new Date());
172 		expected.setExpirationDate(new Date(new Date().getTime() + 1000));
173 		expected.setCommitmentPercent("100.00");
174 		expected.getResultValuesGroupKeys().add("rvg1");
175 		expected.getResultValuesGroupKeys().add("rvg2");
176 		new AttributeTester().add2ForCreate(expected.getAttributes());
177 		LprInfo actual = lprService.createLpr(expected.getPersonId(),
178 				expected.getLuiId(), expected.getTypeKey(), expected,
179 				callContext);
180 		assertNotNull(actual.getId());
181 		new RelationshipTester().check(expected, actual);
182 		new AttributeTester().check(expected.getAttributes(),
183 				actual.getAttributes());
184 		new MetaTester().checkAfterCreate(actual.getMeta());
185 		new ListOfStringTester().check(expected.getResultValuesGroupKeys(),
186 				actual.getResultValuesGroupKeys());
187 		assertEquals(expected.getPersonId(), actual.getPersonId());
188 		assertEquals(expected.getLuiId(), actual.getLuiId());
189 		assertEquals(expected.getCommitmentPercent(),
190 				actual.getCommitmentPercent());
191 
192 		// test read
193 		expected = actual;
194 		actual = lprService.getLpr(actual.getId(), callContext);
195 		assertEquals(expected.getId(), actual.getId());
196 		new RelationshipTester().check(expected, actual);
197 		new AttributeTester().check(expected.getAttributes(),
198 				actual.getAttributes());
199 		new MetaTester().checkAfterGet(expected.getMeta(), actual.getMeta());
200 		new ListOfStringTester().check(expected.getResultValuesGroupKeys(),
201 				actual.getResultValuesGroupKeys());
202 		assertEquals(expected.getPersonId(), actual.getPersonId());
203 		assertEquals(expected.getLuiId(), actual.getLuiId());
204 		assertEquals(expected.getCommitmentPercent(),
205 				actual.getCommitmentPercent());
206 
207 		// test update
208 		expected = actual;
209 		expected.setEffectiveDate(new Timestamp(expected.getEffectiveDate()
210 				.getTime() - 2000));
211 		expected.setExpirationDate(new Timestamp(expected.getExpirationDate()
212 				.getTime() + 2000));
213 		expected.setCommitmentPercent("33.33");
214 		expected.getResultValuesGroupKeys().remove(0);
215 		expected.getResultValuesGroupKeys().add("rvg3");
216 		new AttributeTester().delete1Update1Add1ForUpdate(expected
217 				.getAttributes());
218 		actual = lprService.updateLpr(expected.getId(), expected, callContext);
219 		assertEquals(expected.getId(), actual.getId());
220 		new RelationshipTester().check(expected, actual);
221 		
222 		 for (AttributeInfo itemInfo : expected.getAttributes()) {
223 				
224 	        	// clear out any id's set during the persistence
225 	        	// to let the checks work properly
226 	        	itemInfo.setId(null);
227 			}
228 		 
229 		new AttributeTester().check(expected.getAttributes(),
230 				actual.getAttributes());
231 		new MetaTester().checkAfterUpdate(expected.getMeta(), actual.getMeta());
232 		new ListOfStringTester().check(expected.getResultValuesGroupKeys(),
233 				actual.getResultValuesGroupKeys());
234 		assertEquals(expected.getPersonId(), actual.getPersonId());
235 		assertEquals(expected.getLuiId(), actual.getLuiId());
236 		assertEquals(expected.getCommitmentPercent(),
237 				actual.getCommitmentPercent());
238 
239 		checkTableContents("KSEN_LPR_ATTR");
240 		checkTableRows("KSEN_LPR_ATTR", "OWNER_ID", actual.getId(), 2);
241 
242 	}
243 
244 	private void checkTableContents(final String table) throws SQLException {
245 
246 		txTemplate.execute(new TransactionCallback<Void>() {
247 
248 			@Override
249 			public Void doInTransaction(TransactionStatus status) {
250 				try {
251 					String query = "select * from " + table;
252 
253 					ResultSet rs = dataSource.getConnection().createStatement()
254 							.executeQuery(query);
255 
256 					while (rs.next()) {
257 						Object row = rs.getObject(1);
258 
259 						log.debug("row = " + row);
260 
261 					}
262 				} catch (SQLException e) {
263 					throw new RuntimeException(e);
264 				}
265 				return null;
266 			}
267 		});
268 
269 	}
270 
271 	private void checkTableRows(final String table, final String keyColumn,
272 			final String key, final int expectedRows) throws SQLException {
273 
274 		txTemplate.execute(new TransactionCallback<Void>() {
275 
276 			@Override
277 			public Void doInTransaction(TransactionStatus status) {
278 				try {
279 					String query = "select * from " + table + " where "
280 							+ keyColumn + " = '" + key + "'";
281 
282 					ResultSet rs = dataSource.getConnection().createStatement()
283 							.executeQuery(query);
284 
285 					AtomicInteger rowCounter = new AtomicInteger(0);
286 
287 					while (rs.next()) {
288 						Object row = rs.getObject(1);
289 
290 						log.debug("row = " + row);
291 
292 						rowCounter.addAndGet(1);
293 
294 					}
295 
296 					Assert.assertEquals(expectedRows, rowCounter.intValue());
297 				} catch (SQLException e) {
298 					throw new RuntimeException(e);
299 				}
300 				return null;
301 			}
302 		});
303 	}
304 
305 }