Merge branch 'release/3.12.0'
[cdmlib.git] / cdmlib-persistence / src / test / java / eu / etaxonomy / cdm / persistence / dao / hibernate / taxon / TaxonDaoHibernateImplTest.java
1 /**
2 * Copyright (C) 2009 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9
10 package eu.etaxonomy.cdm.persistence.dao.hibernate.taxon;
11
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertFalse;
14 import static org.junit.Assert.assertNotNull;
15 import static org.junit.Assert.assertNull;
16 import static org.junit.Assert.assertSame;
17 import static org.junit.Assert.assertTrue;
18 import static org.junit.Assert.fail;
19
20 import java.io.FileNotFoundException;
21 import java.io.FileOutputStream;
22 import java.util.ArrayList;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Set;
26 import java.util.UUID;
27
28 import org.apache.log4j.Level;
29 import org.hibernate.Hibernate;
30 import org.hibernate.envers.query.AuditEntity;
31 import org.hibernate.envers.query.criteria.AuditCriterion;
32 import org.hibernate.proxy.HibernateProxy;
33 import org.junit.After;
34 import org.junit.Assert;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.unitils.dbunit.annotation.DataSet;
38 import org.unitils.dbunit.annotation.ExpectedDataSet;
39 import org.unitils.spring.annotation.SpringBeanByType;
40
41 import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
42 import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
43 import eu.etaxonomy.cdm.model.common.Marker;
44 import eu.etaxonomy.cdm.model.common.MarkerType;
45 import eu.etaxonomy.cdm.model.location.NamedArea;
46 import eu.etaxonomy.cdm.model.name.NonViralName;
47 import eu.etaxonomy.cdm.model.name.Rank;
48 import eu.etaxonomy.cdm.model.name.TaxonNameBase;
49 import eu.etaxonomy.cdm.model.reference.Reference;
50 import eu.etaxonomy.cdm.model.taxon.Classification;
51 import eu.etaxonomy.cdm.model.taxon.Synonym;
52 import eu.etaxonomy.cdm.model.taxon.SynonymRelationship;
53 import eu.etaxonomy.cdm.model.taxon.SynonymRelationshipType;
54 import eu.etaxonomy.cdm.model.taxon.Taxon;
55 import eu.etaxonomy.cdm.model.taxon.TaxonBase;
56 import eu.etaxonomy.cdm.model.taxon.TaxonNode;
57 import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
58 import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
59 import eu.etaxonomy.cdm.model.view.AuditEvent;
60 import eu.etaxonomy.cdm.model.view.AuditEventRecord;
61 import eu.etaxonomy.cdm.model.view.context.AuditEventContextHolder;
62 import eu.etaxonomy.cdm.persistence.dao.common.AuditEventSort;
63 import eu.etaxonomy.cdm.persistence.dao.common.IDefinedTermDao;
64 import eu.etaxonomy.cdm.persistence.dao.reference.IReferenceDao;
65 import eu.etaxonomy.cdm.persistence.dao.taxon.IClassificationDao;
66 import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonDao;
67 import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
68 import eu.etaxonomy.cdm.persistence.fetch.CdmFetch;
69 import eu.etaxonomy.cdm.persistence.query.GroupByCount;
70 import eu.etaxonomy.cdm.persistence.query.GroupByDate;
71 import eu.etaxonomy.cdm.persistence.query.Grouping;
72 import eu.etaxonomy.cdm.persistence.query.MatchMode;
73 import eu.etaxonomy.cdm.persistence.query.NativeSqlOrderHint;
74 import eu.etaxonomy.cdm.persistence.query.OrderHint;
75 import eu.etaxonomy.cdm.persistence.query.OrderHint.SortOrder;
76 import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
77 import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
78
79 /**
80 * @author a.mueller
81 * @author ben.clark
82 *
83 */
84 public class TaxonDaoHibernateImplTest extends CdmTransactionalIntegrationTest {
85
86 @SpringBeanByType
87 private ITaxonDao taxonDao;
88
89 @SpringBeanByType
90 private IClassificationDao classificationDao;
91
92 @SpringBeanByType
93 private IReferenceDao referenceDao;
94
95 @SpringBeanByType
96 IDefinedTermDao definedTermDao;
97
98 private UUID uuid;
99 private UUID sphingidae;
100 private UUID acherontia;
101 private UUID mimas;
102 private UUID rethera;
103 private UUID retheraSecCdmtest;
104 private UUID atroposAgassiz; // a Synonym
105 private UUID atroposLeach; // a Synonym
106 private UUID acherontiaLachesis;
107
108 private AuditEvent previousAuditEvent;
109 private AuditEvent mostRecentAuditEvent;
110
111 private UUID northernAmericaUuid;
112 private UUID southernAmericaUuid;
113 private UUID antarcticaUuid;
114
115 private UUID classificationUuid;
116
117 private static final String[] TABLE_NAMES = new String[] {
118 "HOMOTYPICALGROUP", "HOMOTYPICALGROUP_AUD", "REFERENCE", "REFERENCE_AUD", "SYNONYMRELATIONSHIP", "SYNONYMRELATIONSHIP_AUD", "TAXONBASE", "TAXONBASE_AUD"
119 , "TAXONNAMEBASE", "TAXONNAMEBASE_AUD", "TAXONRELATIONSHIP", "TAXONRELATIONSHIP_AUD" };
120
121
122 @Before
123 public void setUp() {
124
125 uuid = UUID.fromString("496b1325-be50-4b0a-9aa2-3ecd610215f2");
126 sphingidae = UUID.fromString("54e767ee-894e-4540-a758-f906ecb4e2d9");
127 acherontia = UUID.fromString("c5cc8674-4242-49a4-aada-72d63194f5fa");
128 acherontiaLachesis = UUID.fromString("b04cc9cb-2b4a-4cc4-a94a-3c93a2158b06");
129 atroposAgassiz = UUID.fromString("d75b2e3d-7394-4ada-b6a5-93175b8751c1");
130 atroposLeach = UUID.fromString("3da4ab34-6c50-4586-801e-732615899b07");
131 rethera = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
132 retheraSecCdmtest = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
133 mimas = UUID.fromString("900052b7-b69c-4e26-a8f0-01c215214c40");
134
135 previousAuditEvent = new AuditEvent();
136 previousAuditEvent.setRevisionNumber(1025);
137 previousAuditEvent.setUuid(UUID.fromString("a680fab4-365e-4765-b49e-768f2ee30cda"));
138 mostRecentAuditEvent = new AuditEvent();
139 mostRecentAuditEvent.setRevisionNumber(1026);
140 mostRecentAuditEvent.setUuid(UUID.fromString("afe8e761-8545-497b-9134-6a6791fc0b0d"));
141 AuditEventContextHolder.clearContext(); // By default we're in the current view (i.e. view == null)
142
143 northernAmericaUuid = UUID.fromString("2757e726-d897-4546-93bd-7951d203bf6f");
144 southernAmericaUuid = UUID.fromString("6310b3ba-96f4-4855-bb5b-326e7af188ea");
145 antarcticaUuid = UUID.fromString("791b3aa0-54dd-4bed-9b68-56b4680aad0c");
146
147 classificationUuid = UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9");
148 }
149
150 @After
151 public void tearDown() {
152 AuditEventContextHolder.clearContext();
153 }
154
155 /**
156 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#TaxonDaoHibernateImpl()}.
157 */
158 @Test
159 @DataSet
160 public void testInit() {
161 logger.warn("testInit()");
162 assertNotNull("Instance of ITaxonDao expected",taxonDao);
163 assertNotNull("Instance of IReferenceDao expected",referenceDao);
164 }
165
166 /**
167 * Test method for
168 * {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getRootTaxa(eu.etaxonomy.cdm.model.reference.Reference)}
169 * .
170 */
171 @Test
172 @DataSet
173 public void testGetRootTaxa() {
174 Reference<?> sec1 = referenceDao.findById(1);
175 assert sec1 != null : "sec1 must exist";
176 Reference<?> sec2 = referenceDao.findById(2);
177 assert sec2 != null : "sec2 must exist";
178
179 List<Taxon> rootTaxa = taxonDao.getRootTaxa(sec1);
180 assertNotNull("getRootTaxa should return a List", rootTaxa);
181 assertFalse("The list should not be empty", rootTaxa.isEmpty());
182 assertEquals("There should be one root taxon", 1, rootTaxa.size());
183
184 rootTaxa = taxonDao.getRootTaxa(sec1, CdmFetch.FETCH_CHILDTAXA(), true, false);
185 assertNotNull("getRootTaxa should return a List", rootTaxa);
186 assertFalse("The list should not be empty", rootTaxa.isEmpty());
187 assertEquals("There should be one root taxon", 1, rootTaxa.size());
188
189 rootTaxa = taxonDao.getRootTaxa(Rank.GENUS(), sec1, CdmFetch.FETCH_CHILDTAXA(), true, false, null);
190 assertNotNull("getRootTaxa should return a List", rootTaxa);
191 assertFalse("The list should not be empty", rootTaxa.isEmpty());
192 assertEquals("There should be one root taxon", 1, rootTaxa.size());
193
194 rootTaxa = taxonDao.getRootTaxa(Rank.FAMILY(), sec2, CdmFetch.FETCH_CHILDTAXA(), true, false, null);
195 if (logger.isDebugEnabled()) {
196 logger.debug("Root taxa rank Family (" + rootTaxa.size() + "):");
197 for (Taxon taxon : rootTaxa) {
198 logger.debug(taxon.getTitleCache());
199 }
200 }
201 assertEquals("There should be one root taxon rank Family", 1, rootTaxa.size());
202 rootTaxa = taxonDao.getRootTaxa(Rank.GENUS(), sec2, CdmFetch.FETCH_CHILDTAXA(), true, false, null);
203 assertNotNull("getRootTaxa should return a List", rootTaxa);
204 assertFalse("The list should not be empty", rootTaxa.isEmpty());
205 if (logger.isDebugEnabled()) {
206 logger.debug("Root taxa rank Genus (" + rootTaxa.size() + "):");
207 for (Taxon taxon : rootTaxa) {
208 logger.debug(taxon.getTitleCache());
209 }
210 }
211 assertEquals("There should be 22 root taxa rank Genus", 22, rootTaxa.size());
212
213 rootTaxa = taxonDao.getRootTaxa(Rank.SPECIES(), sec2, CdmFetch.FETCH_CHILDTAXA(), true, false, null);
214 if (logger.isDebugEnabled()) {
215 logger.debug("Root taxa rank Species (" + rootTaxa.size() + "):");
216 for (Taxon taxon : rootTaxa) {
217 logger.debug(taxon.getTitleCache());
218 }
219 }
220 assertEquals("There should be 4 root taxa rank Species", 3, rootTaxa.size());
221 }
222
223 /**
224 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}.
225 */
226 @Test
227 @DataSet
228 public void testGetTaxaByName() {
229 Reference<?> sec = referenceDao.findById(1);
230 assert sec != null : "sec must exist";
231
232 List<TaxonBase> results = taxonDao.getTaxaByName("Aus", sec);
233 assertNotNull("getTaxaByName should return a List", results);
234 //assertFalse("The list should not be empty", results.isEmpty());
235 assertTrue(results.size() == 1);
236
237 results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, true, null, null);
238 assertNotNull("getTaxaByName should return a List", results);
239
240 int numberOfTaxaByName_A = 9;
241
242 logger.setLevel(Level.DEBUG); //FIXME #######################
243 if (logger.isDebugEnabled()) {
244 for (int i = 0; i < results.size(); i++) {
245 String nameCache = "";
246 TaxonNameBase<?,?> taxonNameBase= results.get(i).getName();
247 nameCache = HibernateProxyHelper.deproxy(taxonNameBase, NonViralName.class).getNameCache();
248 logger.debug(results.get(i).getClass() + "(" + i +")" +
249 ": Name Cache = " + nameCache + ", Title Cache = " + results.get(i).getTitleCache());
250 }
251 }
252
253 assertEquals(numberOfTaxaByName_A, results.size());
254
255
256 //System.err.println("Species group: " + Rank.SPECIESGROUP().getId() + "Species: " + Rank.SPECIES().getId() + "Section Botany: "+ Rank.SECTION_BOTANY());
257
258 // assertEquals(results.get(0).getTitleCache(), "Abies sec. ???");
259 // assertEquals(results.get(1).getTitleCache(), "Abies Mill.");
260 // assertEquals(results.get(2).getTitleCache(), "Abies mill. sec. ???");
261 // assertEquals(results.get(3).getTitleCache(), "Abies alba sec. ???");
262 // assertEquals(results.get(4).getTitleCache(), "Abies alba Michx. sec. ???");
263 // assertEquals(results.get(5).getTitleCache(), "Abies alba Mill. sec. ???");
264
265 results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, true, null, null);
266 assertNotNull("getTaxaByName should return a List", results);
267 assertEquals(numberOfTaxaByName_A, results.size());
268
269 results = taxonDao.getTaxaByName("Aus", MatchMode.EXACT, true, null, null);
270 assertNotNull("getTaxaByName should return a List", results);
271 assertEquals("Results list should contain one entity",1,results.size());
272 }
273
274
275 @Test
276 @DataSet (loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
277 public void testGetTaxaByNameWithMisappliedNames(){
278
279 Classification classification = classificationDao.load(classificationUuid);
280
281 /* NOTE:
282 * The testdata contains 3 misapplied names (1. nameCache = Aus, 2. nameCache = Rethera, 3. nameCache = Daphnis), two contained in the classification used in this test,
283 * the other one is not contained in any classification. This latter case is the more general situation.
284 * Misapplied names should be found regardless of whether they are contained in a classification or not.
285 */
286 //two accepted taxa starting with R in classification "TestBaum"
287 List<TaxonBase> results = taxonDao.getTaxaByName(true, false, false, "R*", classification, MatchMode.BEGINNING, null, null, null, null);
288 Assert.assertEquals("There should be 2 Taxa", 2, results.size());
289
290 //three taxa, 2 accepted and 1 misapplied name starting with R
291 results = taxonDao.getTaxaByName(true, false, true, "R*", null, MatchMode.BEGINNING, null, null, null, null);
292 Assert.assertEquals("There should be 3 Taxa", 3, results.size());
293
294 //one synonym is not in a synonymrelationship
295 results = taxonDao.getTaxaByName(true, true, true, "A*", null, MatchMode.BEGINNING, null, null, null, null);
296 Assert.assertEquals("There should be 11 Taxa",11, results.size());
297
298 //two accepted taxa in classification and 1 misapplied name with accepted name in classification
299 results = taxonDao.getTaxaByName(true, true, true, "R*", classification, MatchMode.BEGINNING, null, null, null, null);
300 Assert.assertEquals("There should be 3 Taxa", 3, results.size());
301
302 //same as above because all taxa, synonyms and misapplied names starting with R are in the classification
303 results = taxonDao.getTaxaByName(true, true, true, "R*", null, MatchMode.BEGINNING, null, null, null, null);
304 Assert.assertEquals("There should be 3 Taxa", 3, results.size());
305
306 //find misapplied names with accepted taxon in the classification, the accepted taxa of two misapplied names are in the classification
307 results = taxonDao.getTaxaByName(false, false, true, "*", classification, MatchMode.BEGINNING, null, null, null, null);
308 Assert.assertEquals("There should be 2 Taxa", 2, results.size());
309
310 //find misapplied names beginning with R
311 results = taxonDao.getTaxaByName(false, false, true, "R*", null, MatchMode.BEGINNING, null, null, null, null);
312 Assert.assertEquals("There should be 1 Taxa", 1, results.size());
313
314 //find all three misapplied names
315 results = taxonDao.getTaxaByName(false, false, true, "*", null, MatchMode.BEGINNING, null, null, null, null);
316 Assert.assertEquals("There should be 3 Taxa", 3, results.size());
317
318 }
319
320 /**
321 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}.
322 */
323 @Test
324 @DataSet
325 public void testGetTaxaByNameForEditor() {
326 Reference<?> sec = referenceDao.findById(1);
327 assert sec != null : "sec must exist";
328
329 List<UuidAndTitleCache<IdentifiableEntity>> results = taxonDao.getTaxaByNameForEditor(true, true, false,false,"Mand", null, MatchMode.BEGINNING, null);
330 assertNotNull("getTaxaByName should return a List", results);
331 //assertFalse("The list should not be empty", results.isEmpty());
332 assertTrue(results.size() == 5);
333
334
335 results = taxonDao.getTaxaByNameForEditor(true, true, false, false,"A",null, MatchMode.BEGINNING, null);
336 assertNotNull("getTaxaByName should return a List", results);
337 assertEquals(results.size(), 12);
338
339
340 results = taxonDao.getTaxaByNameForEditor(true, false,false, false,"A", null,MatchMode.BEGINNING, null);
341 assertNotNull("getTaxaByName should return a List", results);
342 assertTrue(results.size() == 9);
343 assertEquals(results.get(0).getType(), Taxon.class);
344
345 results = taxonDao.getTaxaByNameForEditor(false, true,false,false, "A", null,MatchMode.BEGINNING, null);
346 assertNotNull("getTaxaByName should return a List", results);
347 assertTrue(results.size() == 3);
348 assertEquals(results.get(0).getType(), Synonym.class);
349
350 results = taxonDao.getTaxaByNameForEditor(true, true,false,false,"Aus", null,MatchMode.EXACT, null);
351 assertNotNull("getTaxaByName should return a List", results);
352 assertEquals("Results list should contain one entity",1,results.size());
353
354 results = taxonDao.getTaxaByNameForEditor(true, true,true,false,"A", null,MatchMode.BEGINNING, null);
355 assertNotNull("getTaxaByName should return a List", results);
356 assertEquals("Results list should contain one entity",15,results.size());
357
358 //TODO: test the search for misapplied names
359
360 }
361
362
363 /**
364 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}
365 * restricting the search by a set of Areas.
366 */
367 @Test
368 @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
369 public void testGetTaxaByNameAndArea() {
370
371 Set<NamedArea> namedAreas = new HashSet<NamedArea>();
372 namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
373 //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
374 //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
375
376 Classification taxonmicTree = classificationDao.findByUuid(classificationUuid);
377
378 // prepare some synonym relation ships for some tests
379 Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
380 Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
381 taxonRethera.addSynonym(synAtroposAgassiz, SynonymRelationshipType.SYNONYM_OF());
382 logger.warn("addSynonym(..)");
383 //this.taxonDao.clear();
384 Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
385 Taxon taxonRetheraSecCdmtest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
386 taxonRetheraSecCdmtest.addSynonym(synAtroposLeach, SynonymRelationshipType.SYNONYM_OF());
387 this.taxonDao.save(taxonRetheraSecCdmtest);
388 //this.taxonDao.clear();
389 Taxon test = (Taxon)this.taxonDao.findByUuid(retheraSecCdmtest);
390 Set<Synonym> synonyms = test.getSynonyms();
391 // 1. searching for a taxon (Rethera)
392 //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
393
394 List<TaxonBase> results = taxonDao.getTaxaByName(true,false, false, "Rethera", null, MatchMode.BEGINNING, namedAreas,
395 null, null, null);
396 assertNotNull("getTaxaByName should return a List", results);
397 assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
398
399 // 2. searching for a taxon (Rethera) contained in a specific classification
400 results = taxonDao.getTaxaByName(true, false, false, "Rethera", taxonmicTree, MatchMode.BEGINNING, namedAreas,
401 null, null, null);
402 assertNotNull("getTaxaByName should return a List", results);
403 assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
404
405
406 // 3. searching for Synonyms
407 results = taxonDao.getTaxaByName(false, true, false, "Atropo", null, MatchMode.ANYWHERE, null,
408 null, null, null);
409 assertNotNull("getTaxaByName should return a List", results);
410 /*System.err.println(results.get(0).getTitleCache() + " - " +results.get(1).getTitleCache() + " - " +results.get(2).getTitleCache() );
411
412
413 System.err.println(((Synonym)results.get(0)).getAcceptedTaxa().contains(taxonRethera)+ " - " +((Synonym)results.get(1)).getAcceptedTaxa().contains(taxonRethera)+ " - " +((Synonym)results.get(2)).getAcceptedTaxa().contains(taxonRethera)+ " - " );
414 */
415 assertTrue("expected to find three taxa but found "+results.size(), results.size() == 3);
416
417 // 4. searching for Synonyms
418 results = taxonDao.getTaxaByName(false, true, false, "Atropo", null, MatchMode.BEGINNING, null,
419 null, null, null);
420 assertNotNull("getTaxaByName should return a List", results);
421 assertTrue("expected to find three taxa but found "+results.size(), results.size() == 3);
422
423
424 // 5. searching for a Synonyms and Taxa
425 // create a synonym relationship first
426 results = taxonDao.getTaxaByName(true, true, false, "A", null, MatchMode.BEGINNING, namedAreas,
427 null, null, null);
428 //only five taxa have a distribution
429 assertNotNull("getTaxaByName should return a List", results);
430 assertTrue("expected to find 7 taxa but found "+results.size(), results.size() == 8);
431 }
432
433
434 /**
435 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#findByNameTitleCache(Class<? extends TaxonBase>clazz, String queryString, Classification classification, MatchMode matchMode, Set<NamedArea> namedAreas, Integer pageNumber, Integer pageSize, List<String> propertyPaths)}
436 * restricting the search by a set of Areas.
437 */
438 @Test
439 @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
440 public void testFindByNameTitleCache() {
441
442 Set<NamedArea> namedAreas = new HashSet<NamedArea>();
443 namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
444 //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
445 //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
446
447 Classification classification = classificationDao.findByUuid(classificationUuid);
448
449 // prepare some synonym relation ships for some tests
450 Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
451 Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
452 taxonRethera.addSynonym(synAtroposAgassiz, SynonymRelationshipType.SYNONYM_OF());
453 logger.warn("addSynonym(..)");
454 this.taxonDao.clear();
455 Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
456 Taxon taxonRetheraSecCdmtest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
457 taxonRetheraSecCdmtest.addSynonym(synAtroposLeach, SynonymRelationshipType.SYNONYM_OF());
458 this.taxonDao.clear();
459 // 1. searching for a taxon (Rethera)
460 //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
461
462 List<TaxonBase> results = taxonDao.findByNameTitleCache(true, false, "Rethera Rothschild & Jordan, 1903", null, MatchMode.EXACT, namedAreas,
463 null, null, null);
464 assertNotNull("getTaxaByName should return a List", results);
465 assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
466
467 // 2. searching for a taxon (Rethera) contained in a specific classification
468 results = taxonDao.findByNameTitleCache(true, false, "Rethera Rothschild & Jordan, 1903", classification, MatchMode.EXACT, namedAreas,
469 null, null, null);
470 assertNotNull("getTaxaByName should return a List", results);
471 assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
472
473
474 // 3. searching for Synonyms
475 results = taxonDao.findByNameTitleCache(false, true, "*Atropo", null, MatchMode.ANYWHERE, null,
476 null, null, null);
477 assertNotNull("getTaxaByName should return a List", results);
478
479 assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
480
481 // 4. searching for Synonyms
482 results = taxonDao.findByNameTitleCache(false, true, "Atropo", null, MatchMode.BEGINNING, null,
483 null, null, null);
484 assertNotNull("getTaxaByName should return a List", results);
485 assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
486
487
488 // 5. searching for a Synonyms and Taxa
489 // create a synonym relationship first
490 Synonym syn = (Synonym)taxonDao.findByUuid(this.atroposLeach);
491 Taxon tax = (Taxon) taxonDao.findByUuid(rethera);
492 tax.addSynonym(syn, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
493
494 taxonDao.save(tax);
495 results = taxonDao.findByNameTitleCache(true, true, "A", null, MatchMode.BEGINNING, namedAreas,
496 null, null, null);
497 assertNotNull("getTaxaByName should return a List", results);
498 assertTrue("expected to find 8 taxa but found "+results.size(), results.size() == 8);
499 }
500
501 @Test
502 @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
503 public void testTaxonNameInTwoClassifications(){
504 int numberOfClassifications = classificationDao.count();
505 List<String> propertyPaths = new ArrayList<String>();
506 propertyPaths.add("taxonNodes");
507 List<TaxonBase> taxa = taxonDao.getTaxaByName(true, true, false, "P", null, MatchMode.BEGINNING, null, null, null, null);
508 Taxon taxon = (Taxon)taxa.get(0);
509 Set<TaxonNode> nodes = taxon.getTaxonNodes();
510 assertTrue(nodes.size() == 1);
511 //assertNotNull(taxa);
512 //assertTrue(taxa.size() > 0);
513 }
514
515 @Test
516 @DataSet
517 public void testFindByUuid() {
518 Taxon taxon = (Taxon)taxonDao.findByUuid(uuid);
519 assertNotNull("findByUuid should return a taxon",taxon);
520 assertFalse("findByUuid should not return a taxon with it's name initialized",Hibernate.isInitialized(taxon.getName()));
521 }
522
523 @Test
524 @DataSet
525 public void testLoad() {
526 List<String> propertyPaths = new ArrayList<String>();
527 propertyPaths.add("name");
528 propertyPaths.add("sec");
529 Taxon taxon = (Taxon)taxonDao.load(uuid, propertyPaths);
530 assertNotNull("findByUuid should return a taxon",taxon);
531 assertTrue("load should return a taxon with it's name initialized, given that the property was specified in the method",Hibernate.isInitialized(taxon.getName()));
532 assertTrue("load should return a taxon with it's secundum reference initialized, given that the property was specified in the method",Hibernate.isInitialized(taxon.getSec()));
533 }
534
535 @Test
536 @DataSet
537 public void testCountTaxonRelationships() {
538 Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
539 assert taxon != null : "taxon must exist";
540
541 int numberOfRelatedTaxa = taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo);
542 assertEquals("countTaxonRelationships should return 23", 23, numberOfRelatedTaxa);
543 }
544
545 @Test
546 @DataSet
547 public void testCountTaxaByName() {
548 long numberOfTaxa = taxonDao.countTaxaByName(true, false, false, "A", null, MatchMode.BEGINNING, null);
549 assertEquals(numberOfTaxa, 9);
550 numberOfTaxa = taxonDao.countTaxaByName(true, false, false, "Aus aus", null, MatchMode.EXACT, null);
551 assertEquals(numberOfTaxa, 1);
552 numberOfTaxa = taxonDao.countTaxaByName(false, true, false, "A", null, MatchMode.BEGINNING, null);
553 assertEquals(numberOfTaxa, 3);
554 numberOfTaxa = taxonDao.countTaxaByName(true, true, false, "A", null, MatchMode.BEGINNING, null);
555 assertEquals(numberOfTaxa,12);
556 numberOfTaxa = taxonDao.countTaxaByName(true, true, false, "Aasfwerfwf fffe", null, MatchMode.BEGINNING, null);
557 assertEquals(numberOfTaxa, 0);
558 // FIXME implement test for search in specific classification
559 // Reference reference = referenceDao.findByUuid(UUID.fromString("596b1325-be50-4b0a-9aa2-3ecd610215f2"));
560 // numberOfTaxa = taxonDao.countTaxaByName("A*", MatchMode.BEGINNING, SelectMode.ALL, null, null);
561 // assertEquals(numberOfTaxa, 2);
562 }
563
564 @Test
565 @DataSet
566 public void testRelatedTaxa() {
567 Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
568 assert taxon != null : "taxon must exist";
569
570 List<String> propertyPaths = new ArrayList<String>();
571 propertyPaths.add("fromTaxon");
572 propertyPaths.add("fromTaxon.name");
573 List<OrderHint> orderHints = new ArrayList<OrderHint>();
574 orderHints.add(new OrderHint("relatedFrom.name.genusOrUninomial", SortOrder.ASCENDING));
575 orderHints.add(new OrderHint("relatedFrom.name.specificEpithet", SortOrder.ASCENDING));
576 orderHints.add(new OrderHint("relatedFrom.name.infraSpecificEpithet", SortOrder.ASCENDING));
577
578 List<TaxonRelationship> relatedTaxa = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
579 assertNotNull("getRelatedTaxa should return a List",relatedTaxa);
580 assertEquals("getRelatedTaxa should return all 23 related taxa",relatedTaxa.size(),23);
581 assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon()));
582 assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon().getName()));
583
584 assertEquals("Acherontia should appear first in the list of related taxa", relatedTaxa.get(0).getFromTaxon().getTitleCache(), "Acherontia Laspeyres, 1809 sec. cate-sphingidae.org");
585 assertEquals("Sphingonaepiopsis should appear last in the list of related taxa", relatedTaxa.get(22).getFromTaxon().getTitleCache(), "Sphinx Linnaeus, 1758 sec. cate-sphingidae.org");
586 }
587
588 @Test
589 @DataSet
590 public void testGetRelatedTaxaPaged() {
591 Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
592 assert taxon != null : "taxon must exist";
593
594 List<String> propertyPaths = new ArrayList<String>();
595 propertyPaths.add("fromTaxon");
596 propertyPaths.add("fromTaxon.name");
597
598 List<OrderHint> orderHints = new ArrayList<OrderHint>();
599 orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
600
601 List<TaxonRelationship> firstPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), 10, 0, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
602 List<TaxonRelationship> secondPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),10, 1, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
603 List<TaxonRelationship> thirdPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), 10, 2, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
604
605 assertNotNull("getRelatedTaxa: 10, 0 should return a List",firstPage);
606 assertEquals("getRelatedTaxa: 10, 0 should return a List with 10 elements",10,firstPage.size());
607 assertNotNull("getRelatedTaxa: 10, 1 should return a List",secondPage);
608 assertEquals("getRelatedTaxa: 10, 1 should return a List with 10 elements",secondPage.size(),10);
609 assertNotNull("getRelatedTaxa: 10, 2 should return a List",thirdPage);
610 assertEquals("getRelatedTaxa: 10, 2 should return a List with 3 elements",thirdPage.size(),3);
611 }
612
613 @Test
614 @DataSet
615 public void testCountSynonymRelationships() {
616 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
617 assert taxon != null : "taxon must exist";
618
619 int numberOfSynonymRelationships = taxonDao.countSynonyms(taxon,null);
620 assertEquals("countSynonymRelationships should return 5",5,numberOfSynonymRelationships);
621 }
622
623 @Test
624 @DataSet
625 public void testSynonymRelationships() {
626 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
627 assert taxon != null : "taxon must exist";
628 List<String> propertyPaths = new ArrayList<String>();
629 propertyPaths.add("synonym");
630 propertyPaths.add("synonym.name");
631
632 List<OrderHint> orderHints = new ArrayList<OrderHint>();
633 orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
634
635 List<SynonymRelationship> synonyms = taxonDao.getSynonyms(taxon, null, null, null,orderHints,propertyPaths);
636
637 assertNotNull("getSynonyms should return a List",synonyms);
638 assertEquals("getSynonyms should return 5 SynonymRelationship entities",synonyms.size(),5);
639 assertTrue("getSynonyms should return SynonymRelationship objects with the synonym initialized",Hibernate.isInitialized(synonyms.get(0).getSynonym()));
640 }
641
642 @Test
643 @DataSet
644 public void testCountSynonymRelationshipsByType() {
645 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
646 assert taxon != null : "taxon must exist";
647
648 int numberOfTaxonomicSynonyms = taxonDao.countSynonyms(taxon, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
649 assertEquals("countSynonyms should return 4",numberOfTaxonomicSynonyms, 4);
650 }
651
652 @Test
653 @DataSet
654 public void testSynonymRelationshipsByType() {
655 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
656 assert taxon != null : "taxon must exist";
657
658 List<SynonymRelationship> synonyms = taxonDao.getSynonyms(taxon, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF(), null, null,null,null);
659
660 assertNotNull("getSynonyms should return a List",synonyms);
661 assertEquals("getSynonyms should return 4 SynonymRelationship entities",synonyms.size(),4);
662 }
663
664 @Test
665 @DataSet
666 public void testPageSynonymRelationships(){
667 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
668 assert taxon != null : "taxon must exist";
669
670 List<SynonymRelationship> firstPage = taxonDao.getSynonyms(taxon, null, 4, 0,null,null);
671 List<SynonymRelationship> secondPage = taxonDao.getSynonyms(taxon, null, 4, 1,null,null);
672
673 assertNotNull("getSynonyms: 4, 0 should return a List",firstPage);
674 assertEquals("getSynonyms: 4, 0 should return 4 SynonymRelationships", 4,firstPage.size());
675 assertNotNull("getSynonyms: 4, 1 should return a List",secondPage);
676 assertEquals("getSynonyms: 4, 1 should return 1 SynonymRelationship", 1, secondPage.size());
677 }
678
679 @Test
680 @DataSet("TaxonNodeDaoHibernateImplTest.xml")
681 public void testListAcceptedTaxaFor() {
682 UUID acheontitia_ciprosus = UUID.fromString("3ef145f7-bd92-4a64-8afd-2b8203e00e02");
683
684 Synonym synonym = (Synonym)taxonDao.findByUuid(acheontitia_ciprosus);
685 assertNotNull("synonym must exist", synonym);
686
687 List<Taxon> list = taxonDao.listAcceptedTaxaFor(synonym, null, 4, 0, null, null);
688 assertNotNull("listAcceptedTaxaFor should return a List");
689 assertEquals("listAcceptedTaxaFor should return 2 Taxa", 2, list.size());
690
691 Classification classification = classificationDao.load(classificationUuid);
692 assertNotNull("classification must exist", classification);
693
694 list = taxonDao.listAcceptedTaxaFor(synonym, classification, 4, 0, null, null);
695 assertNotNull("listAcceptedTaxaFor should return a List");
696 assertEquals("listAcceptedTaxaFor should return 1 Taxa", 1, list.size());
697 }
698
699
700 @Test
701 @DataSet
702 public void testGetTaxonMatchingUninomial() {
703 List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class, "Smerinthus", "*", "*", "*",null,null,null);
704
705 assertNotNull("findTaxaByName should return a List", result);
706 assertEquals("findTaxaByName should return two Taxa",2,result.size());
707 assertEquals("findTaxaByName should return a Taxon with id 5",5,result.get(0).getId());
708 }
709
710 @Test
711 @DataSet
712 public void testGetTaxonMatchingSpeciesBinomial() {
713 List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Smerinthus", null, "kindermannii", null,null,null,null);
714
715 assertNotNull("findTaxaByName should return a List", result);
716 assertEquals("findTaxaByName should return one Taxon",1,result.size());
717 assertEquals("findTaxaByName should return a Taxon with id 8",8,result.get(0).getId());
718 }
719
720 @Test
721 @DataSet
722 public void testGetTaxonMatchingTrinomial() {
723 List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Cryptocoryne", null,"purpurea","borneoensis",null,null,null);
724
725 assertNotNull("findTaxaByName should return a List", result);
726 assertEquals("findTaxaByName should return one Taxon",1,result.size());
727 assertEquals("findTaxaByName should return a Taxon with id 38",38,result.get(0).getId());
728 }
729
730 @Test
731 @DataSet
732 public void testNegativeMatch() {
733 List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Acherontia", null,"atropos","dehli",null,null,null);
734
735 assertNotNull("findTaxaByName should return a List", result);
736 assertTrue("findTaxaByName should return an empty List",result.isEmpty());
737 }
738
739 @Test
740 @DataSet
741 public void testCountAllTaxa() {
742 int numberOfTaxa = taxonDao.count(Taxon.class);
743 assertEquals("count should return 33 taxa",33, numberOfTaxa);
744 }
745
746 @Test
747 @DataSet
748 public void testListAllTaxa() {
749 List<Taxon> taxa = taxonDao.list(Taxon.class,100, 0);
750 assertNotNull("list should return a List",taxa);
751 assertEquals("list should return 33 taxa",33, taxa.size());
752 }
753
754 @Test
755 @DataSet
756 // @ExpectedDataSet
757 public void testDelete() {
758 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
759 assert taxon != null : "taxon must exist";
760 taxonDao.delete(taxon);
761 taxon = (Taxon)taxonDao.findByUuid(acherontia);
762 assert taxon == null : "taxon must not exist";
763 setComplete();
764 endTransaction();
765 try {
766 printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
767 } catch (FileNotFoundException e) {
768 e.printStackTrace();
769 }
770 }
771
772 @Test
773 @DataSet
774 // @ExpectedDataSet("TaxonDaoHibernateImplTest.testDelete-result.xml")
775 public void testDeleteWithMarker() {
776 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
777 taxon.addMarker(Marker.NewInstance(MarkerType.IS_DOUBTFUL(), true));
778 taxonDao.save(taxon);
779 assert taxon != null : "taxon must exist";
780
781 taxonDao.delete(taxon);
782 commitAndStartNewTransaction(null);
783 taxon = (Taxon)taxonDao.findByUuid(acherontia);
784 assert taxon == null : "taxon must not exist";
785 setComplete();
786 endTransaction();
787 try {
788 printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
789 } catch (FileNotFoundException e) {
790 e.printStackTrace();
791 }
792 }
793
794 @Test
795 @DataSet
796 public void testDeleteWithChildren() {
797 Taxon taxonWithChildren = (Taxon)taxonDao.findByUuid(mimas);
798 assert taxonWithChildren != null : "taxon must exist";
799 assertEquals(taxonWithChildren.getTaxonomicChildrenCount(), 2);
800 Taxon parent = (Taxon)taxonDao.findByUuid(sphingidae);
801 assertSame(taxonWithChildren.getTaxonomicParent(), parent);
802 assertEquals(parent.getTaxonomicChildrenCount(), 204);
803 taxonDao.delete(taxonWithChildren);
804 assertEquals(parent.getTaxonomicChildrenCount(), 203);
805 }
806
807 @Test
808 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
809 public void testFindDeleted() {
810 TaxonBase<?> taxon = taxonDao.findByUuid(acherontia);
811 assertNull("findByUuid should return null in this view", taxon);
812 assertFalse("exist should return false in this view",taxonDao.exists(acherontia));
813 }
814
815 @Test
816 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
817 public void testFindDeletedInPreviousView() {
818 AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
819 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
820 assertNotNull("findByUuid should return a taxon in this view",taxon);
821 assertTrue("exists should return true in this view", taxonDao.exists(acherontia));
822
823 try{
824 assertEquals("There should be 3 relations to this taxon in this view",3,taxon.getRelationsToThisTaxon().size());
825 } catch(Exception e) {
826 fail("We should not experience any problems initializing proxies with envers");
827 }
828 }
829
830 @Test
831 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
832 public void testGetAuditEvents() {
833 TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
834 assert taxon != null : "taxon cannot be null";
835
836 List<String> propertyPaths = new ArrayList<String>();
837 propertyPaths.add("name");
838 propertyPaths.add("createdBy");
839 propertyPaths.add("updatedBy");
840
841 List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,null,propertyPaths);
842 assertNotNull("getAuditEvents should return a list",auditEvents);
843 assertFalse("the list should not be empty",auditEvents.isEmpty());
844 assertEquals("There should be two AuditEventRecords in the list",2, auditEvents.size());
845 }
846
847 @Test
848 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
849 public void testGetAuditEventsFromNow() {
850 AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
851 TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
852 assert taxon != null : "taxon cannot be null";
853
854 List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,AuditEventSort.FORWARDS,null);
855 assertNotNull("getAuditEvents should return a list",auditEvents);
856 assertFalse("the list should not be empty",auditEvents.isEmpty());
857 assertEquals("There should be one audit event in the list",1,auditEvents.size());
858 }
859
860 @Test
861 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
862 public void testCountAuditEvents() {
863 TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
864 assert taxon != null : "taxon cannot be null";
865
866 int numberOfAuditEvents = taxonDao.countAuditEvents(taxon,null);
867 assertEquals("countAuditEvents should return 2",numberOfAuditEvents,2);
868 }
869
870 @Test
871 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
872 public void getPreviousAuditEvent() {
873 TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
874 assert taxon != null : "taxon cannot be null";
875
876 AuditEventRecord<TaxonBase> auditEvent = taxonDao.getPreviousAuditEvent(taxon);
877 assertNotNull("getPreviousAuditEvent should not return null as there is at least one audit event prior to the current one",auditEvent);
878 }
879
880 @Test
881 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
882 public void getPreviousAuditEventAtBeginning() {
883 AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
884 TaxonBase taxon = taxonDao.findByUuid(sphingidae);
885 assert taxon != null : "taxon cannot be null";
886
887 AuditEventRecord<TaxonBase> auditEvent = taxonDao.getPreviousAuditEvent(taxon);
888 assertNull("getPreviousAuditEvent should return null if we're at the first audit event anyway",auditEvent);
889 }
890
891 @Test
892 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
893 public void getNextAuditEvent() {
894 AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
895 TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
896 assert taxon != null : "taxon cannot be null";
897
898 AuditEventRecord<TaxonBase> auditEvent = taxonDao.getNextAuditEvent(taxon);
899 assertNotNull("getNextAuditEvent should not return null as there is at least one audit event after the current one",auditEvent);
900 }
901
902 @Test
903 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
904 public void getNextAuditEventAtEnd() {
905 AuditEventContextHolder.getContext().setAuditEvent(mostRecentAuditEvent);
906 TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
907 assert taxon != null : "taxon cannot be null";
908
909 AuditEventRecord<TaxonBase> auditEvent = taxonDao.getNextAuditEvent(taxon);
910 assertNull("getNextAuditEvent should return null as there no more audit events after the current one",auditEvent);
911 }
912
913 @Test
914 @DataSet
915 @ExpectedDataSet
916 public void testAddChild() throws Exception {
917 Taxon parent = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
918 assert parent != null : "taxon cannot be null";
919 Taxon child = Taxon.NewInstance(null, null);
920 child.setTitleCache("Acherontia lachesis diehli Eitschberger, 2003", true);
921 child.addTaxonRelation(parent, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),null, null);
922 taxonDao.save(child);
923 setComplete();
924 endTransaction();
925 }
926
927 @Test
928 @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
929 public void testFind() {
930 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
931 assert taxon != null : "taxon cannot be null";
932
933 assertEquals("getTaxonomicChildrenCount should return 1 in this view",1,taxon.getTaxonomicChildrenCount());
934 assertEquals("getRelationsToThisTaxon should contain 1 TaxonRelationship in this view",1,taxon.getRelationsToThisTaxon().size());
935 }
936
937 @Test
938 @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
939 public void testFindInPreviousView() {
940 AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
941 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
942 assert taxon != null : "taxon cannot be null";
943
944 assertEquals("getTaxonomicChildrenCount should return 0 in this view",0,taxon.getTaxonomicChildrenCount());
945 assertTrue("getRelationsToThisTaxon should contain 0 TaxonRelationship in this view",taxon.getRelationsToThisTaxon().isEmpty());
946 }
947
948 @Test
949 @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
950 public void testGetRelations() {
951 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
952 assert taxon != null : "taxon cannot be null";
953
954 List<String> propertyPaths = new ArrayList<String>();
955 propertyPaths.add("fromTaxon");
956 propertyPaths.add("fromTaxon.name");
957
958 List<OrderHint> orderHints = new ArrayList<OrderHint>();
959 orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
960
961 List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
962 assertNotNull("getRelatedTaxa should return a list", taxonRelations);
963 assertEquals("there should be one TaxonRelationship in the list in the current view",1,taxonRelations.size());
964 assertTrue("TaxonRelationship.relatedFrom should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon()));
965 assertTrue("TaxonRelationship.relatedFrom.name should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon().getName()));
966 }
967
968 @Test
969 @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
970 public void testCountRelations() {
971 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
972 assert taxon != null : "taxon cannot be null";
973 assertEquals("countRelatedTaxa should return 1 in the current view",1, taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo));
974 }
975
976 @Test
977 @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
978 public void testGetRelationsInPreviousView() {
979 AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
980 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
981 assert taxon != null : "taxon cannot be null";
982
983 List<String> propertyPaths = new ArrayList<String>();
984 propertyPaths.add("relatedFrom");
985 propertyPaths.add("relatedFrom.name");
986
987 List<OrderHint> orderHints = new ArrayList<OrderHint>();
988 orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
989
990 List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
991 assertNotNull("getRelatedTaxa should return a list",taxonRelations);
992 assertTrue("there should be no TaxonRelationships in the list in the prior view",taxonRelations.isEmpty());
993 }
994
995 @Test
996 @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
997 public void testCountRelationsInPreviousView() {
998 AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
999 Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
1000 assert taxon != null : "taxon cannot be null";
1001 assertEquals("countRelatedTaxa should return 0 in the current view",0, taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo));
1002 }
1003
1004 @Test
1005 @DataSet
1006 public void testGroupTaxa() {
1007 List<Grouping> groups = new ArrayList<Grouping>();
1008 groups.add(new GroupByCount("count",SortOrder.DESCENDING));
1009 groups.add(new Grouping("name.genusOrUninomial", "genus", "n", SortOrder.ASCENDING));
1010 List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1011 System.out.println("count\tname.genuOrUninomial");
1012 for(Object[] result : results) {
1013 System.out.println(result[0] + "\t" + result[1]);
1014 }
1015 }
1016
1017 @Test
1018 @DataSet
1019 public void testGroupTaxaByClass() {
1020 List<Grouping> groups = new ArrayList<Grouping>();
1021 groups.add(new GroupByCount("count",SortOrder.DESCENDING));
1022 groups.add(new Grouping("class", "class",null, SortOrder.ASCENDING));
1023 List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1024 System.out.println("count\tclass");
1025 for(Object[] result : results) {
1026 System.out.println(result[0] + "\t" + result[1]);
1027 }
1028 }
1029
1030 @Test
1031 @DataSet
1032 public void testNativeSQLOrder() {
1033 List<OrderHint> orderHints = new ArrayList<OrderHint>();
1034 orderHints.add(new NativeSqlOrderHint("case when {alias}.titleCache like 'C%' then 0 else 1 end",SortOrder.ASCENDING));
1035
1036 List<TaxonBase> results = taxonDao.list(null, null, orderHints);
1037 System.out.println("native SQL order");
1038 for(TaxonBase<?> result : results) {
1039 System.out.println(result.getTitleCache());
1040 }
1041 }
1042
1043 @Test
1044 @DataSet
1045 public void testGroupByDateTaxa() {
1046 List<Grouping> groups = new ArrayList<Grouping>();
1047 groups.add(new GroupByCount("count",null));
1048 groups.add(new GroupByDate("created", "dateGroup", SortOrder.ASCENDING, GroupByDate.Resolution.MONTH));
1049 List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1050 System.out.println("count\tyear\tmonth");
1051 for(Object[] result : results) {
1052 System.out.println(result[0] + "\t" + result[1] + "\t" + result[2]);
1053 }
1054 }
1055
1056 @Test
1057 @DataSet ("TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
1058 public final void testGetTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(){
1059 Classification classification = classificationDao.findByUuid(classificationUuid);
1060 List<UuidAndTitleCache<TaxonNode>> result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification);
1061 assertNotNull(result);
1062 assertEquals(5, result.size());
1063 UUID excludeUUID = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
1064 List<UUID> excludeUUids = new ArrayList<UUID>();
1065 excludeUUids.add(excludeUUID);
1066 result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, excludeUUids);
1067 assertEquals(4, result.size());
1068
1069 }
1070
1071
1072 @Test
1073 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
1074 //NOTE: There is a problem with loading AuditEvents if this test runs
1075 //stand alone or as first (one of the first) in the test suite. For some reason
1076 //the AuditEvent records from the @DataSet are not inserted into the database then,
1077 //while those inserted by the terms dataset are inserted as well as a completely new one.
1078 //This problem for some reason does not happen if not running at first place
1079 public void testGetAuditEventsByTypeWithRestrictions() {
1080 commitAndStartNewTransaction(new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1081
1082 List<String> propertyPaths = new ArrayList<String>();
1083 propertyPaths.add("name");
1084 propertyPaths.add("createdBy");
1085 propertyPaths.add("updatedBy");
1086
1087 List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
1088 criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
1089
1090 int count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1091
1092 List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, criteria,null, null, AuditEventSort.FORWARDS, propertyPaths);
1093 assertNotNull("getAuditEvents should return a list",auditEvents);
1094 assertFalse("the list should not be empty",auditEvents.isEmpty());
1095 assertEquals("There should be one AuditEventRecord in the list",1, auditEvents.size());
1096 }
1097
1098
1099 @Test
1100 @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
1101 // @DataSets({ //for testing only
1102 // @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml"),
1103 // @DataSet("TaxonDaoHibernateImplTest.testFindDeletedAuditEvents.xml")
1104 // })
1105 //NOTE: There is a problem with loading AuditEvents if this test runs
1106 //stand alone or as first (one of the first) in the test suite. For some reason
1107 //the AuditEvent records from the @DataSet are not inserted into the database then,
1108 //while those inserted by the terms dataset are inserted as well as a completely new one.
1109 //This problem for some reason does not happen if not running at first place
1110 public void testGetAuditEventsByTypeWithNoRestrictions() {
1111 printDataSet(System.out, new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1112 commitAndStartNewTransaction(new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1113
1114 List<String> propertyPaths = new ArrayList<String>();
1115 propertyPaths.add("name");
1116 propertyPaths.add("createdBy");
1117 propertyPaths.add("updatedBy");
1118 int count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1119 List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, null,null, null, AuditEventSort.FORWARDS, propertyPaths);
1120 assertNotNull("getAuditEvents should return a list", auditEvents);
1121 assertFalse("the list should not be empty", auditEvents.isEmpty());
1122 assertEquals("There should be thirty eight AuditEventRecords in the list", 38, auditEvents.size());
1123 }
1124
1125
1126 @Test
1127 @DataSet("TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
1128 public void testGetCommonName(){
1129 List<Taxon> commonNameResults = taxonDao.getTaxaByCommonName("common%", null,
1130 MatchMode.BEGINNING, null, null, null, null);
1131
1132 assertNotNull("getTaxaByCommonName should return a list", commonNameResults);
1133 assertFalse("the list should not be empty", commonNameResults.isEmpty());
1134 assertEquals("There should be one Taxon with common name", 1,commonNameResults.size());
1135 assertEquals(" sec. ???", ((TaxonBase)commonNameResults.get(0)).getTitleCache());
1136 }
1137
1138 @Test
1139 @DataSet("TaxonDaoHibernateImplTest.testPropertyPath.xml")
1140 public void testPropertyPath(){
1141 //Test that BeanInitializer also works on HiberanteProxys
1142 Classification c = classificationDao.load(UUID.fromString("4bceea53-893f-4685-8c63-6dcec6e85ab1"));
1143 TaxonNode singleNode = c.getRootNode().getChildNodes().iterator().next();
1144 Taxon taxonProxy = singleNode.getTaxon();
1145 Assert.assertTrue("Object to test should be a proxy ", taxonProxy instanceof HibernateProxy);
1146
1147 List<String> propertyPaths = new ArrayList<String>();
1148 propertyPaths.add("taxonNodes");
1149 Taxon taxon = (Taxon)this.taxonDao.load(
1150 UUID.fromString("4a5bc930-844f-45ec-aea8-dd155e1ab25f"),
1151 propertyPaths);
1152 Assert.assertSame("Returned object should be the same proxy to assure that we ran initialization on this proxy", taxonProxy, taxon);
1153 }
1154
1155 /**
1156 * {@inheritDoc}
1157 */
1158 @Override
1159 // @Test
1160 public void createTestDataSet() throws FileNotFoundException {
1161 // Classification classification = Classification.NewInstance("Test");
1162 // BotanicalName taxonNameBase = null;
1163 // Reference<?> sec = null;
1164 // Taxon taxon = Taxon.NewInstance(taxonNameBase, sec);
1165 // classification.addChildTaxon(taxon, sec, null);
1166 //
1167 // classificationDao.save(classification);
1168 // this.commitAndStartNewTransaction(null);
1169 //
1170 // writeDbUnitDataSetFile(new String[] {
1171 // "CLASSIFICATION", "TAXONNAMEBASE",
1172 // "REFERENCE","TAXONNODE",
1173 // "TAXONBASE","LANGUAGESTRING",
1174 // "HIBERNATE_SEQUENCES" // IMPORTANT!!!
1175 // },
1176 // "testPropertyPath" );
1177 }
1178
1179 }