Project

General

Profile

Download (57.2 KB) Statistics
| Branch: | Tag: | Revision:
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.util.ArrayList;
22
import java.util.HashSet;
23
import java.util.List;
24
import java.util.Set;
25
import java.util.UUID;
26

    
27
import org.apache.log4j.Level;
28
import org.hibernate.Hibernate;
29
import org.hibernate.envers.query.AuditEntity;
30
import org.hibernate.envers.query.criteria.AuditCriterion;
31
import org.hibernate.proxy.HibernateProxy;
32
import org.junit.After;
33
import org.junit.Assert;
34
import org.junit.Before;
35
import org.junit.Test;
36
import org.unitils.dbunit.annotation.DataSet;
37
import org.unitils.dbunit.annotation.ExpectedDataSet;
38
import org.unitils.spring.annotation.SpringBeanByType;
39

    
40
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
41
import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
42
import eu.etaxonomy.cdm.model.common.Marker;
43
import eu.etaxonomy.cdm.model.common.MarkerType;
44
import eu.etaxonomy.cdm.model.location.NamedArea;
45
import eu.etaxonomy.cdm.model.name.NonViralName;
46
import eu.etaxonomy.cdm.model.name.Rank;
47
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
48
import eu.etaxonomy.cdm.model.reference.Reference;
49
import eu.etaxonomy.cdm.model.taxon.Classification;
50
import eu.etaxonomy.cdm.model.taxon.Synonym;
51
import eu.etaxonomy.cdm.model.taxon.SynonymRelationship;
52
import eu.etaxonomy.cdm.model.taxon.SynonymRelationshipType;
53
import eu.etaxonomy.cdm.model.taxon.Taxon;
54
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
55
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
56
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
57
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
58
import eu.etaxonomy.cdm.model.view.AuditEvent;
59
import eu.etaxonomy.cdm.model.view.AuditEventRecord;
60
import eu.etaxonomy.cdm.model.view.context.AuditEventContextHolder;
61
import eu.etaxonomy.cdm.persistence.dao.common.AuditEventSort;
62
import eu.etaxonomy.cdm.persistence.dao.common.IDefinedTermDao;
63
import eu.etaxonomy.cdm.persistence.dao.reference.IReferenceDao;
64
import eu.etaxonomy.cdm.persistence.dao.taxon.IClassificationDao;
65
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonDao;
66
import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
67
import eu.etaxonomy.cdm.persistence.fetch.CdmFetch;
68
import eu.etaxonomy.cdm.persistence.query.GroupByCount;
69
import eu.etaxonomy.cdm.persistence.query.GroupByDate;
70
import eu.etaxonomy.cdm.persistence.query.Grouping;
71
import eu.etaxonomy.cdm.persistence.query.MatchMode;
72
import eu.etaxonomy.cdm.persistence.query.NativeSqlOrderHint;
73
import eu.etaxonomy.cdm.persistence.query.OrderHint;
74
import eu.etaxonomy.cdm.persistence.query.OrderHint.SortOrder;
75
import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
76
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
77

    
78
/**
79
 * @author a.mueller
80
 * @author ben.clark
81
 *
82
 */
83
public class TaxonDaoHibernateImplTest extends CdmTransactionalIntegrationTest {
84

    
85
    @SpringBeanByType
86
    private ITaxonDao taxonDao;
87

    
88
    @SpringBeanByType
89
    private IClassificationDao classificationDao;
90

    
91
    @SpringBeanByType
92
    private IReferenceDao referenceDao;
93

    
94
    @SpringBeanByType
95
    IDefinedTermDao definedTermDao;
96

    
97
    private UUID uuid;
98
    private UUID sphingidae;
99
    private UUID acherontia;
100
    private UUID mimas;
101
    private UUID rethera;
102
    private UUID retheraSecCdmtest;
103
    private UUID atroposAgassiz; // a Synonym
104
    private UUID atroposLeach; // a Synonym
105
    private UUID acherontiaLachesis;
106

    
107
    private AuditEvent previousAuditEvent;
108
    private AuditEvent mostRecentAuditEvent;
109

    
110
    private UUID northernAmericaUuid;
111
    private UUID southernAmericaUuid;
112
    private UUID antarcticaUuid;
113

    
114
    private UUID classificationUuid;
115

    
116
    private static final String[] TABLE_NAMES = new String[] {
117
        "HOMOTYPICALGROUP", "HOMOTYPICALGROUP_AUD", "REFERENCE", "REFERENCE_AUD", "SYNONYMRELATIONSHIP", "SYNONYMRELATIONSHIP_AUD", "TAXONBASE", "TAXONBASE_AUD"
118
        , "TAXONNAMEBASE", "TAXONNAMEBASE_AUD", "TAXONRELATIONSHIP", "TAXONRELATIONSHIP_AUD" };
119

    
120

    
121
    @Before
122
    public void setUp() {
123

    
124
        uuid = UUID.fromString("496b1325-be50-4b0a-9aa2-3ecd610215f2");
125
        sphingidae = UUID.fromString("54e767ee-894e-4540-a758-f906ecb4e2d9");
126
        acherontia = UUID.fromString("c5cc8674-4242-49a4-aada-72d63194f5fa");
127
        acherontiaLachesis = UUID.fromString("b04cc9cb-2b4a-4cc4-a94a-3c93a2158b06");
128
        atroposAgassiz = UUID.fromString("d75b2e3d-7394-4ada-b6a5-93175b8751c1");
129
        atroposLeach =  UUID.fromString("3da4ab34-6c50-4586-801e-732615899b07");
130
        rethera = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
131
        retheraSecCdmtest = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
132
        mimas = UUID.fromString("900052b7-b69c-4e26-a8f0-01c215214c40");
133

    
134
        previousAuditEvent = new AuditEvent();
135
        previousAuditEvent.setRevisionNumber(1025);
136
        previousAuditEvent.setUuid(UUID.fromString("a680fab4-365e-4765-b49e-768f2ee30cda"));
137
        mostRecentAuditEvent = new AuditEvent();
138
        mostRecentAuditEvent.setRevisionNumber(1026);
139
        mostRecentAuditEvent.setUuid(UUID.fromString("afe8e761-8545-497b-9134-6a6791fc0b0d"));
140
        AuditEventContextHolder.clearContext(); // By default we're in the current view (i.e. view == null)
141

    
142
        northernAmericaUuid = UUID.fromString("2757e726-d897-4546-93bd-7951d203bf6f");
143
        southernAmericaUuid = UUID.fromString("6310b3ba-96f4-4855-bb5b-326e7af188ea");
144
        antarcticaUuid = UUID.fromString("791b3aa0-54dd-4bed-9b68-56b4680aad0c");
145

    
146
        classificationUuid = UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9");
147
    }
148

    
149
    @After
150
    public void tearDown() {
151
        AuditEventContextHolder.clearContext();
152
    }
153

    
154
    /**
155
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#TaxonDaoHibernateImpl()}.
156
     */
157
    @Test
158
    @DataSet
159
    public void testInit() {
160
        logger.warn("testInit()");
161
        assertNotNull("Instance of ITaxonDao expected",taxonDao);
162
        assertNotNull("Instance of IReferenceDao expected",referenceDao);
163
    }
164

    
165
    /**
166
     * Test method for
167
     * {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getRootTaxa(eu.etaxonomy.cdm.model.reference.Reference)}
168
     * .
169
     */
170
    @Test
171
    @DataSet
172
    public void testGetRootTaxa() {
173
        Reference sec1 = referenceDao.findById(1);
174
        assert sec1 != null : "sec1 must exist";
175
        Reference sec2 = referenceDao.findById(2);
176
        assert sec2 != null : "sec2 must exist";
177

    
178
        List<Taxon> rootTaxa = taxonDao.getRootTaxa(sec1);
179
        assertNotNull("getRootTaxa should return a List", rootTaxa);
180
        assertFalse("The list should not be empty", rootTaxa.isEmpty());
181
        assertEquals("There should be one root taxon", 1, rootTaxa.size());
182

    
183
        rootTaxa = taxonDao.getRootTaxa(sec1, CdmFetch.FETCH_CHILDTAXA(), true, false);
184
        assertNotNull("getRootTaxa should return a List", rootTaxa);
185
        assertFalse("The list should not be empty", rootTaxa.isEmpty());
186
        assertEquals("There should be one root taxon", 1, rootTaxa.size());
187

    
188
        rootTaxa = taxonDao.getRootTaxa(Rank.GENUS(), sec1, CdmFetch.FETCH_CHILDTAXA(), true, false, null);
189
        assertNotNull("getRootTaxa should return a List", rootTaxa);
190
        assertFalse("The list should not be empty", rootTaxa.isEmpty());
191
        assertEquals("There should be one root taxon", 1, rootTaxa.size());
192

    
193
        rootTaxa = taxonDao.getRootTaxa(Rank.FAMILY(), sec2, CdmFetch.FETCH_CHILDTAXA(), true, false, null);
194
        if (logger.isDebugEnabled()) {
195
            logger.debug("Root taxa rank Family (" + rootTaxa.size() + "):");
196
            for (Taxon taxon : rootTaxa) {
197
                logger.debug(taxon.getTitleCache());
198
            }
199
        }
200
        assertEquals("There should be one root taxon rank Family", 1, rootTaxa.size());
201
        rootTaxa = taxonDao.getRootTaxa(Rank.GENUS(), sec2, CdmFetch.FETCH_CHILDTAXA(), true, false, null);
202
        assertNotNull("getRootTaxa should return a List", rootTaxa);
203
        assertFalse("The list should not be empty", rootTaxa.isEmpty());
204
        if (logger.isDebugEnabled()) {
205
            logger.debug("Root taxa rank Genus (" + rootTaxa.size() + "):");
206
            for (Taxon taxon : rootTaxa) {
207
                logger.debug(taxon.getTitleCache());
208
            }
209
        }
210
        assertEquals("There should be 22 root taxa rank Genus", 22, rootTaxa.size());
211

    
212
        rootTaxa = taxonDao.getRootTaxa(Rank.SPECIES(), sec2, CdmFetch.FETCH_CHILDTAXA(), true, false, null);
213
        if (logger.isDebugEnabled()) {
214
            logger.debug("Root taxa rank Species (" + rootTaxa.size() + "):");
215
            for (Taxon taxon : rootTaxa) {
216
                logger.debug(taxon.getTitleCache());
217
            }
218
        }
219
        assertEquals("There should be 4 root taxa rank Species", 3, rootTaxa.size());
220
    }
221

    
222
    /**
223
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}.
224
     */
225
    @Test
226
    @DataSet
227
    public void testGetTaxaByName() {
228
        Reference sec = referenceDao.findById(1);
229
        assert sec != null : "sec must exist";
230

    
231
        List<TaxonBase> results = taxonDao.getTaxaByName("Aus", sec);
232
        assertNotNull("getTaxaByName should return a List", results);
233
        //assertFalse("The list should not be empty", results.isEmpty());
234
        assertTrue(results.size() == 1);
235

    
236
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, true, null, null);
237
        assertNotNull("getTaxaByName should return a List", results);
238

    
239
        int numberOfTaxaByName_A = 9;
240

    
241
        logger.setLevel(Level.DEBUG); //FIXME #######################
242
        if (logger.isDebugEnabled()) {
243
            for (int i = 0; i < results.size(); i++) {
244
                String nameCache = "";
245
                TaxonNameBase<?,?> taxonNameBase= results.get(i).getName();
246
                nameCache = HibernateProxyHelper.deproxy(taxonNameBase, NonViralName.class).getNameCache();
247
                logger.debug(results.get(i).getClass() + "(" + i +")" +
248
                        ": Name Cache = " + nameCache + ", Title Cache = " + results.get(i).getTitleCache());
249
            }
250
        }
251

    
252
        assertEquals(numberOfTaxaByName_A, results.size());
253

    
254

    
255
        //System.err.println("Species group: " + Rank.SPECIESGROUP().getId() + "Species: " + Rank.SPECIES().getId() + "Section Botany: "+ Rank.SECTION_BOTANY());
256

    
257
//		assertEquals(results.get(0).getTitleCache(), "Abies sec. ???");
258
//		assertEquals(results.get(1).getTitleCache(), "Abies Mill.");
259
//		assertEquals(results.get(2).getTitleCache(), "Abies mill. sec. ???");
260
//		assertEquals(results.get(3).getTitleCache(), "Abies alba sec. ???");
261
//		assertEquals(results.get(4).getTitleCache(), "Abies alba Michx. sec. ???");
262
//		assertEquals(results.get(5).getTitleCache(), "Abies alba Mill. sec. ???");
263

    
264
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, true, null, null);
265
        assertNotNull("getTaxaByName should return a List", results);
266
        assertEquals(numberOfTaxaByName_A, results.size());
267

    
268
        results = taxonDao.getTaxaByName("Aus", MatchMode.EXACT, true, null, null);
269
        assertNotNull("getTaxaByName should return a List", results);
270
        assertEquals("Results list should contain one entity",1,results.size());
271
    }
272

    
273

    
274
    @Test
275
    @DataSet (loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
276
    public void testGetTaxaByNameWithMisappliedNames(){
277

    
278
        Classification classification = classificationDao.load(classificationUuid);
279

    
280
        /* NOTE:
281
         * The testdata contains 3 misapplied names (1. nameCache = Aus, 2. nameCache = Rethera, 3. nameCache = Daphnis), two contained in the classification used in this test,
282
         * the other one is not contained in any classification. This latter case is the more general situation.
283
         * Misapplied names should be found regardless of whether they are contained in a classification or not.
284
         */
285
        //two accepted taxa starting with R in classification "TestBaum"
286
        List<TaxonBase> results = taxonDao.getTaxaByName(true, false, false, "R*", classification, MatchMode.BEGINNING, null, null, null, null);
287
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
288

    
289
        //three taxa, 2 accepted and 1 misapplied name starting with R
290
        results = taxonDao.getTaxaByName(true, false, true, "R*", null, MatchMode.BEGINNING, null, null, null, null);
291
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
292

    
293
        //one synonym is not in a synonymrelationship
294
        results = taxonDao.getTaxaByName(true, true, true, "A*", null, MatchMode.BEGINNING, null, null, null, null);
295
        Assert.assertEquals("There should be 11 Taxa",11, results.size());
296

    
297
        //two accepted taxa in classification and 1 misapplied name with accepted name in classification
298
        results = taxonDao.getTaxaByName(true, true, true, "R*", classification, MatchMode.BEGINNING, null, null, null, null);
299
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
300

    
301
        //same as above because all taxa, synonyms and misapplied names starting with R are in the classification
302
        results = taxonDao.getTaxaByName(true, true, true, "R*", null, MatchMode.BEGINNING, null, null, null, null);
303
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
304

    
305
        //find misapplied names with accepted taxon in the classification, the accepted taxa of two misapplied names are in the classification
306
        results = taxonDao.getTaxaByName(false, false, true, "*", classification, MatchMode.BEGINNING, null, null, null, null);
307
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
308

    
309
        //find misapplied names beginning with R
310
        results = taxonDao.getTaxaByName(false, false, true, "R*", null, MatchMode.BEGINNING, null, null, null, null);
311
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
312

    
313
        //find all three misapplied names
314
        results = taxonDao.getTaxaByName(false, false, true, "*", null, MatchMode.BEGINNING, null, null, null, null);
315
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
316

    
317
    }
318

    
319
    /**
320
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}.
321
     */
322
    @Test
323
    @DataSet
324
    public void testGetTaxaByNameForEditor() {
325
        Reference sec = referenceDao.findById(1);
326
        assert sec != null : "sec must exist";
327

    
328
        List<UuidAndTitleCache<IdentifiableEntity>> results = taxonDao.getTaxaByNameForEditor(true, true, false,false,"Mand", null, MatchMode.BEGINNING, null);
329
        assertNotNull("getTaxaByName should return a List", results);
330
        //assertFalse("The list should not be empty", results.isEmpty());
331
        assertTrue(results.size() == 5);
332

    
333

    
334
        results = taxonDao.getTaxaByNameForEditor(true, true, false, false,"A",null, MatchMode.BEGINNING, null);
335
        assertNotNull("getTaxaByName should return a List", results);
336
        assertEquals(results.size(), 12);
337

    
338

    
339
        results = taxonDao.getTaxaByNameForEditor(true, false,false, false,"A", null,MatchMode.BEGINNING, null);
340
        assertNotNull("getTaxaByName should return a List", results);
341
        assertTrue(results.size() == 9);
342
        assertEquals(results.get(0).getType(), Taxon.class);
343

    
344
        results = taxonDao.getTaxaByNameForEditor(false, true,false,false, "A", null,MatchMode.BEGINNING, null);
345
        assertNotNull("getTaxaByName should return a List", results);
346
        assertTrue(results.size() == 3);
347
        assertEquals(results.get(0).getType(), Synonym.class);
348

    
349
        results = taxonDao.getTaxaByNameForEditor(true, true,false,false,"Aus", null,MatchMode.EXACT,  null);
350
        assertNotNull("getTaxaByName should return a List", results);
351
        assertEquals("Results list should contain one entity",1,results.size());
352

    
353
        results = taxonDao.getTaxaByNameForEditor(true, true,true,false,"A", null,MatchMode.BEGINNING,  null);
354
        assertNotNull("getTaxaByName should return a List", results);
355
        assertEquals("Results list should contain one entity",15,results.size());
356

    
357
        //TODO: test the search for misapplied names
358

    
359
    }
360

    
361

    
362
    /**
363
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}
364
     * restricting the search by a set of Areas.
365
     */
366
    @Test
367
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
368
    public void testGetTaxaByNameAndArea() {
369

    
370
        Set<NamedArea> namedAreas = new HashSet<NamedArea>();
371
        namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
372
        //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
373
        //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
374

    
375
        Classification taxonmicTree = classificationDao.findByUuid(classificationUuid);
376

    
377
        // prepare some synonym relation ships for some tests
378
        Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
379
        Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
380
        taxonRethera.addSynonym(synAtroposAgassiz, SynonymRelationshipType.SYNONYM_OF());
381
        logger.warn("addSynonym(..)");
382
        //this.taxonDao.clear();
383
        Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
384
        Taxon taxonRetheraSecCdmtest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
385
        taxonRetheraSecCdmtest.addSynonym(synAtroposLeach, SynonymRelationshipType.SYNONYM_OF());
386
        this.taxonDao.save(taxonRetheraSecCdmtest);
387
        //this.taxonDao.clear();
388
        Taxon test = (Taxon)this.taxonDao.findByUuid(retheraSecCdmtest);
389
        Set<Synonym> synonyms = test.getSynonyms();
390
        // 1. searching for a taxon (Rethera)
391
        //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
392

    
393
        List<TaxonBase> results = taxonDao.getTaxaByName(true,false, false, "Rethera", null, MatchMode.BEGINNING, namedAreas,
394
            null, null, null);
395
        assertNotNull("getTaxaByName should return a List", results);
396
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
397

    
398
        // 2. searching for a taxon (Rethera) contained in a specific classification
399
        results = taxonDao.getTaxaByName(true, false, false, "Rethera", taxonmicTree, MatchMode.BEGINNING, namedAreas,
400
            null, null, null);
401
        assertNotNull("getTaxaByName should return a List", results);
402
        assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
403

    
404

    
405
        // 3. searching for Synonyms
406
        results = taxonDao.getTaxaByName(false, true, false, "Atropo", null, MatchMode.ANYWHERE, null,
407
            null, null, null);
408
        assertNotNull("getTaxaByName should return a List", results);
409
        /*System.err.println(results.get(0).getTitleCache() + " - " +results.get(1).getTitleCache() + " - " +results.get(2).getTitleCache() );
410

    
411

    
412
        System.err.println(((Synonym)results.get(0)).getAcceptedTaxa().contains(taxonRethera)+ " - " +((Synonym)results.get(1)).getAcceptedTaxa().contains(taxonRethera)+ " - "  +((Synonym)results.get(2)).getAcceptedTaxa().contains(taxonRethera)+ " - "  );
413
        */
414
        assertTrue("expected to find three taxa but found "+results.size(), results.size() == 3);
415

    
416
        // 4. searching for Synonyms
417
        results = taxonDao.getTaxaByName(false, true, false, "Atropo", null, MatchMode.BEGINNING, null,
418
            null, null, null);
419
        assertNotNull("getTaxaByName should return a List", results);
420
        assertTrue("expected to find three taxa but found "+results.size(), results.size() == 3);
421

    
422

    
423
        // 5. searching for a Synonyms and Taxa
424
        //   create a synonym relationship first
425
        results = taxonDao.getTaxaByName(true, true, false, "A", null, MatchMode.BEGINNING, namedAreas,
426
            null, null, null);
427
        //only five taxa have a distribution
428
        assertNotNull("getTaxaByName should return a List", results);
429
        assertTrue("expected to find 7 taxa but found "+results.size(), results.size() == 8);
430
    }
431

    
432

    
433
    /**
434
     * 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)}
435
     * restricting the search by a set of Areas.
436
     */
437
    @Test
438
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
439
    public void testFindByNameTitleCache() {
440

    
441
        Set<NamedArea> namedAreas = new HashSet<NamedArea>();
442
        namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
443
        //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
444
        //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
445

    
446
        Classification classification = classificationDao.findByUuid(classificationUuid);
447

    
448
        // prepare some synonym relation ships for some tests
449
        Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
450
        Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
451
        taxonRethera.addSynonym(synAtroposAgassiz, SynonymRelationshipType.SYNONYM_OF());
452
        logger.warn("addSynonym(..)");
453
        this.taxonDao.clear();
454
        Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
455
        Taxon taxonRetheraSecCdmtest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
456
        taxonRetheraSecCdmtest.addSynonym(synAtroposLeach, SynonymRelationshipType.SYNONYM_OF());
457
        this.taxonDao.clear();
458
        // 1. searching for a taxon (Rethera)
459
        //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
460

    
461
        List<TaxonBase> results = taxonDao.findByNameTitleCache(true, false, "Rethera Rothschild & Jordan, 1903", null, MatchMode.EXACT, namedAreas,
462
            null, null, null);
463
        assertNotNull("getTaxaByName should return a List", results);
464
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
465

    
466
        // 2. searching for a taxon (Rethera) contained in a specific classification
467
        results = taxonDao.findByNameTitleCache(true, false, "Rethera Rothschild & Jordan, 1903", classification, MatchMode.EXACT, namedAreas,
468
            null, null, null);
469
        assertNotNull("getTaxaByName should return a List", results);
470
        assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
471

    
472

    
473
        // 3. searching for Synonyms
474
        results = taxonDao.findByNameTitleCache(false, true, "*Atropo", null, MatchMode.ANYWHERE, null,
475
            null, null, null);
476
        assertNotNull("getTaxaByName should return a List", results);
477

    
478
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
479

    
480
        // 4. searching for Synonyms
481
        results = taxonDao.findByNameTitleCache(false, true, "Atropo", null, MatchMode.BEGINNING, null,
482
            null, null, null);
483
        assertNotNull("getTaxaByName should return a List", results);
484
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
485

    
486

    
487
        // 5. searching for a Synonyms and Taxa
488
        //   create a synonym relationship first
489
        Synonym syn = (Synonym)taxonDao.findByUuid(this.atroposLeach);
490
        Taxon tax = (Taxon) taxonDao.findByUuid(rethera);
491
        tax.addSynonym(syn, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
492

    
493
        taxonDao.save(tax);
494
        results = taxonDao.findByNameTitleCache(true, true, "A", null, MatchMode.BEGINNING, namedAreas,
495
            null, null, null);
496
        assertNotNull("getTaxaByName should return a List", results);
497
        assertTrue("expected to find 8 taxa but found "+results.size(), results.size() == 8);
498
    }
499

    
500
    @Test
501
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
502
    public void testTaxonNameInTwoClassifications(){
503
        int numberOfClassifications = classificationDao.count();
504
        List<String> propertyPaths = new ArrayList<String>();
505
        propertyPaths.add("taxonNodes");
506
        List<TaxonBase> taxa = taxonDao.getTaxaByName(true, true, false, "P", null, MatchMode.BEGINNING, null, null, null, null);
507
        Taxon taxon = (Taxon)taxa.get(0);
508
        Set<TaxonNode> nodes = taxon.getTaxonNodes();
509
        assertTrue(nodes.size() == 1);
510
        //assertNotNull(taxa);
511
        //assertTrue(taxa.size() > 0);
512
    }
513

    
514
    @Test
515
    @DataSet
516
    public void testFindByUuid() {
517
        Taxon taxon = (Taxon)taxonDao.findByUuid(uuid);
518
        assertNotNull("findByUuid should return a taxon",taxon);
519
        assertFalse("findByUuid should not return a taxon with it's name initialized",Hibernate.isInitialized(taxon.getName()));
520
    }
521

    
522
    @Test
523
    @DataSet
524
    public void testLoad() {
525
        List<String> propertyPaths = new ArrayList<String>();
526
        propertyPaths.add("name");
527
        propertyPaths.add("sec");
528
        Taxon taxon = (Taxon)taxonDao.load(uuid, propertyPaths);
529
        assertNotNull("findByUuid should return a taxon",taxon);
530
        assertTrue("load should return a taxon with it's name initialized, given that the property was specified in the method",Hibernate.isInitialized(taxon.getName()));
531
        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()));
532
    }
533

    
534
    @Test
535
    @DataSet
536
    public void testCountTaxonRelationships()	{
537
        Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
538
        assert taxon != null : "taxon must exist";
539

    
540
        int numberOfRelatedTaxa = taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo);
541
        assertEquals("countTaxonRelationships should return 23", 23, numberOfRelatedTaxa);
542
    }
543

    
544
    @Test
545
    @DataSet
546
    public void testCountTaxaByName() {
547
        long numberOfTaxa = taxonDao.countTaxaByName(true, false, false, "A", null, MatchMode.BEGINNING, null);
548
        assertEquals(numberOfTaxa, 9);
549
        numberOfTaxa = taxonDao.countTaxaByName(true, false, false, "Aus aus", null, MatchMode.EXACT, null);
550
        assertEquals(numberOfTaxa, 1);
551
        numberOfTaxa = taxonDao.countTaxaByName(false, true, false, "A", null, MatchMode.BEGINNING, null);
552
        assertEquals(numberOfTaxa, 3);
553
        numberOfTaxa = taxonDao.countTaxaByName(true, true, false, "A", null, MatchMode.BEGINNING, null);
554
        assertEquals(numberOfTaxa,12);
555
        numberOfTaxa = taxonDao.countTaxaByName(true, true, false, "Aasfwerfwf fffe", null, MatchMode.BEGINNING, null);
556
        assertEquals(numberOfTaxa, 0);
557
//	FIXME implement test for search in specific classification
558
//		Reference reference = referenceDao.findByUuid(UUID.fromString("596b1325-be50-4b0a-9aa2-3ecd610215f2"));
559
//		numberOfTaxa = taxonDao.countTaxaByName("A*", MatchMode.BEGINNING, SelectMode.ALL, null, null);
560
//		assertEquals(numberOfTaxa, 2);
561
    }
562

    
563
    @Test
564
    @DataSet
565
    public void testRelatedTaxa() {
566
        Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
567
        assert taxon != null : "taxon must exist";
568

    
569
        List<String> propertyPaths = new ArrayList<String>();
570
        propertyPaths.add("fromTaxon");
571
        propertyPaths.add("fromTaxon.name");
572
        List<OrderHint> orderHints = new ArrayList<OrderHint>();
573
        orderHints.add(new OrderHint("relatedFrom.name.genusOrUninomial", SortOrder.ASCENDING));
574
        orderHints.add(new OrderHint("relatedFrom.name.specificEpithet", SortOrder.ASCENDING));
575
        orderHints.add(new OrderHint("relatedFrom.name.infraSpecificEpithet", SortOrder.ASCENDING));
576

    
577
        List<TaxonRelationship> relatedTaxa = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
578
        assertNotNull("getRelatedTaxa should return a List",relatedTaxa);
579
        assertEquals("getRelatedTaxa should return all 23 related taxa",relatedTaxa.size(),23);
580
        assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon()));
581
        assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon().getName()));
582

    
583
        assertEquals("Acherontia should appear first in the list of related taxa", relatedTaxa.get(0).getFromTaxon().getTitleCache(), "Acherontia Laspeyres, 1809 sec. cate-sphingidae.org");
584
        assertEquals("Sphingonaepiopsis should appear last in the list of related taxa", relatedTaxa.get(22).getFromTaxon().getTitleCache(), "Sphinx Linnaeus, 1758 sec. cate-sphingidae.org");
585
    }
586

    
587
    @Test
588
    @DataSet
589
    public void testGetRelatedTaxaPaged()	{
590
        Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
591
        assert taxon != null : "taxon must exist";
592

    
593
        List<String> propertyPaths = new ArrayList<String>();
594
        propertyPaths.add("fromTaxon");
595
        propertyPaths.add("fromTaxon.name");
596

    
597
        List<OrderHint> orderHints = new ArrayList<OrderHint>();
598
        orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
599

    
600
        List<TaxonRelationship> firstPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), 10, 0, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
601
        List<TaxonRelationship> secondPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),10, 1, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
602
        List<TaxonRelationship> thirdPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), 10, 2, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
603

    
604
        assertNotNull("getRelatedTaxa: 10, 0 should return a List",firstPage);
605
        assertEquals("getRelatedTaxa: 10, 0 should return a List with 10 elements",10,firstPage.size());
606
        assertNotNull("getRelatedTaxa: 10, 1 should return a List",secondPage);
607
        assertEquals("getRelatedTaxa: 10, 1 should return a List with 10 elements",secondPage.size(),10);
608
        assertNotNull("getRelatedTaxa: 10, 2 should return a List",thirdPage);
609
        assertEquals("getRelatedTaxa: 10, 2 should return a List with 3 elements",thirdPage.size(),3);
610
    }
611

    
612
    @Test
613
    @DataSet
614
    public void testCountSynonymRelationships() {
615
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
616
        assert taxon != null : "taxon must exist";
617

    
618
        int numberOfSynonymRelationships = taxonDao.countSynonyms(taxon,null);
619
        assertEquals("countSynonymRelationships should return 5",5,numberOfSynonymRelationships);
620
    }
621

    
622
    @Test
623
    @DataSet
624
    public void testSynonymRelationships()	{
625
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
626
        assert taxon != null : "taxon must exist";
627
        List<String> propertyPaths = new ArrayList<String>();
628
        propertyPaths.add("synonym");
629
        propertyPaths.add("synonym.name");
630

    
631
        List<OrderHint> orderHints = new ArrayList<OrderHint>();
632
        orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
633

    
634
        List<SynonymRelationship> synonyms = taxonDao.getSynonyms(taxon, null, null, null,orderHints,propertyPaths);
635

    
636
        assertNotNull("getSynonyms should return a List",synonyms);
637
        assertEquals("getSynonyms should return 5 SynonymRelationship entities",synonyms.size(),5);
638
        assertTrue("getSynonyms should return SynonymRelationship objects with the synonym initialized",Hibernate.isInitialized(synonyms.get(0).getSynonym()));
639
    }
640

    
641
    @Test
642
    @DataSet
643
    public void testCountSynonymRelationshipsByType()	{
644
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
645
        assert taxon != null : "taxon must exist";
646

    
647
        int numberOfTaxonomicSynonyms = taxonDao.countSynonyms(taxon, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
648
        assertEquals("countSynonyms should return 4",numberOfTaxonomicSynonyms, 4);
649
    }
650

    
651
    @Test
652
    @DataSet
653
    public void testSynonymRelationshipsByType() {
654
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
655
        assert taxon != null : "taxon must exist";
656

    
657
        List<SynonymRelationship> synonyms = taxonDao.getSynonyms(taxon, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF(), null, null,null,null);
658

    
659
        assertNotNull("getSynonyms should return a List",synonyms);
660
        assertEquals("getSynonyms should return 4 SynonymRelationship entities",synonyms.size(),4);
661
    }
662

    
663
    @Test
664
    @DataSet
665
    public void testPageSynonymRelationships(){
666
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
667
        assert taxon != null : "taxon must exist";
668

    
669
        List<SynonymRelationship> firstPage = taxonDao.getSynonyms(taxon, null, 4, 0,null,null);
670
        List<SynonymRelationship> secondPage = taxonDao.getSynonyms(taxon, null, 4, 1,null,null);
671

    
672
        assertNotNull("getSynonyms: 4, 0 should return a List",firstPage);
673
        assertEquals("getSynonyms: 4, 0 should return 4 SynonymRelationships", 4,firstPage.size());
674
        assertNotNull("getSynonyms: 4, 1 should return a List",secondPage);
675
        assertEquals("getSynonyms: 4, 1 should return 1 SynonymRelationship", 1, secondPage.size());
676
    }
677

    
678
    @Test
679
    @DataSet("TaxonNodeDaoHibernateImplTest.xml")
680
    public void testListAcceptedTaxaFor()  {
681
        UUID acheontitia_ciprosus = UUID.fromString("3ef145f7-bd92-4a64-8afd-2b8203e00e02");
682

    
683
        Synonym synonym = (Synonym)taxonDao.findByUuid(acheontitia_ciprosus);
684
        assertNotNull("synonym must exist", synonym);
685

    
686
        List<Taxon> list = taxonDao.listAcceptedTaxaFor(synonym, null, 4, 0, null, null);
687
        assertNotNull("listAcceptedTaxaFor should return a List");
688
        assertEquals("listAcceptedTaxaFor should return 2 Taxa", 2,  list.size());
689

    
690
        Classification classification = classificationDao.load(classificationUuid);
691
        assertNotNull("classification must exist", classification);
692

    
693
        list = taxonDao.listAcceptedTaxaFor(synonym, classification, 4, 0, null, null);
694
        assertNotNull("listAcceptedTaxaFor should return a List");
695
        assertEquals("listAcceptedTaxaFor should return 1 Taxa", 1,  list.size());
696
    }
697

    
698

    
699
    @Test
700
    @DataSet
701
    public void testGetTaxonMatchingUninomial() {
702
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class, "Smerinthus", "*", "*", "*",null,null,null);
703

    
704
        assertNotNull("findTaxaByName should return a List", result);
705
        assertEquals("findTaxaByName should return two Taxa",2,result.size());
706
        assertEquals("findTaxaByName should return a Taxon with id 5",5,result.get(0).getId());
707
    }
708

    
709
    @Test
710
    @DataSet
711
    public void testGetTaxonMatchingSpeciesBinomial() {
712
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Smerinthus", null, "kindermannii", null,null,null,null);
713

    
714
        assertNotNull("findTaxaByName should return a List", result);
715
        assertEquals("findTaxaByName should return one Taxon",1,result.size());
716
        assertEquals("findTaxaByName should return a Taxon with id 8",8,result.get(0).getId());
717
    }
718

    
719
    @Test
720
    @DataSet
721
    public void testGetTaxonMatchingTrinomial() {
722
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Cryptocoryne", null,"purpurea","borneoensis",null,null,null);
723

    
724
        assertNotNull("findTaxaByName should return a List", result);
725
        assertEquals("findTaxaByName should return one Taxon",1,result.size());
726
        assertEquals("findTaxaByName should return a Taxon with id 38",38,result.get(0).getId());
727
    }
728

    
729
    @Test
730
    @DataSet
731
    public void testNegativeMatch() {
732
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Acherontia", null,"atropos","dehli",null,null,null);
733

    
734
        assertNotNull("findTaxaByName should return a List", result);
735
        assertTrue("findTaxaByName should return an empty List",result.isEmpty());
736
    }
737

    
738
    @Test
739
    @DataSet
740
    public void testCountAllTaxa() {
741
        int numberOfTaxa = taxonDao.count(Taxon.class);
742
        assertEquals("count should return 33 taxa",33, numberOfTaxa);
743
    }
744

    
745
    @Test
746
    @DataSet
747
    public void testListAllTaxa() {
748
        List<Taxon> taxa = taxonDao.list(Taxon.class,100, 0);
749
        assertNotNull("list should return a List",taxa);
750
        assertEquals("list should return 33 taxa",33, taxa.size());
751
    }
752

    
753
    @Test
754
    @DataSet
755
   // @ExpectedDataSet
756
    public void testDelete() {
757
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
758
        assert taxon != null : "taxon must exist";
759
        taxonDao.delete(taxon);
760
        taxon = (Taxon)taxonDao.findByUuid(acherontia);
761
        assert taxon == null : "taxon must not exist";
762
        setComplete();
763
        endTransaction();
764
//        try {
765
//            printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
766
//        } catch (FileNotFoundException e) {
767
//            e.printStackTrace();
768
//        }
769
    }
770

    
771
    @Test
772
    @DataSet
773
   // @ExpectedDataSet("TaxonDaoHibernateImplTest.testDelete-result.xml")
774
    public void testDeleteWithMarker() {
775
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
776
        taxon.addMarker(Marker.NewInstance(MarkerType.IS_DOUBTFUL(), true));
777
        taxonDao.save(taxon);
778
        assert taxon != null : "taxon must exist";
779

    
780
        taxonDao.delete(taxon);
781
        commitAndStartNewTransaction(null);
782
        taxon = (Taxon)taxonDao.findByUuid(acherontia);
783
        assert taxon == null : "taxon must not exist";
784
        setComplete();
785
        endTransaction();
786
//        try {
787
//            printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
788
//        } catch (FileNotFoundException e) {
789
//            e.printStackTrace();
790
//        }
791
    }
792

    
793
    @Test
794
    @DataSet
795
    public void testDeleteWithChildren() {
796
        Taxon taxonWithChildren = (Taxon)taxonDao.findByUuid(mimas);
797
        assert taxonWithChildren != null : "taxon must exist";
798
        assertEquals(taxonWithChildren.getTaxonomicChildrenCount(), 2);
799
        Taxon parent = (Taxon)taxonDao.findByUuid(sphingidae);
800
        assertSame(taxonWithChildren.getTaxonomicParent(), parent);
801
        assertEquals(parent.getTaxonomicChildrenCount(), 204);
802
        taxonDao.delete(taxonWithChildren);
803
        assertEquals(parent.getTaxonomicChildrenCount(), 203);
804
    }
805

    
806
    @Test
807
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
808
    public void testFindDeleted() {
809
        TaxonBase<?> taxon = taxonDao.findByUuid(acherontia);
810
        assertNull("findByUuid should return null in this view", taxon);
811
        assertFalse("exist should return false in this view",taxonDao.exists(acherontia));
812
    }
813

    
814
    @Test
815
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
816
    public void testFindDeletedInPreviousView() {
817
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
818
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
819
        assertNotNull("findByUuid should return a taxon in this view",taxon);
820
        assertTrue("exists should return true in this view", taxonDao.exists(acherontia));
821

    
822
        try{
823
            assertEquals("There should be 3 relations to this taxon in this view",3,taxon.getRelationsToThisTaxon().size());
824
        } catch(Exception e) {
825
            fail("We should not experience any problems initializing proxies with envers");
826
        }
827
    }
828

    
829
    @Test
830
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
831
    public void testGetAuditEvents() {
832
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
833
        assert taxon != null : "taxon cannot be null";
834

    
835
        List<String> propertyPaths = new ArrayList<String>();
836
        propertyPaths.add("name");
837
        propertyPaths.add("createdBy");
838
        propertyPaths.add("updatedBy");
839

    
840
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,null,propertyPaths);
841
        assertNotNull("getAuditEvents should return a list",auditEvents);
842
        assertFalse("the list should not be empty",auditEvents.isEmpty());
843
        assertEquals("There should be two AuditEventRecords in the list",2, auditEvents.size());
844
    }
845

    
846
    @Test
847
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
848
    public void testGetAuditEventsFromNow() {
849
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
850
        TaxonBase<?> taxon =  taxonDao.findByUuid(sphingidae);
851
        assert taxon != null : "taxon cannot be null";
852

    
853
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,AuditEventSort.FORWARDS,null);
854
        assertNotNull("getAuditEvents should return a list",auditEvents);
855
        assertFalse("the list should not be empty",auditEvents.isEmpty());
856
        assertEquals("There should be one audit event in the list",1,auditEvents.size());
857
    }
858

    
859
    @Test
860
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
861
    public void testCountAuditEvents() {
862
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
863
        assert taxon != null : "taxon cannot be null";
864

    
865
        int numberOfAuditEvents = taxonDao.countAuditEvents(taxon,null);
866
        assertEquals("countAuditEvents should return 2",numberOfAuditEvents,2);
867
    }
868

    
869
    @Test
870
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
871
    public void getPreviousAuditEvent() {
872
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
873
        assert taxon != null : "taxon cannot be null";
874

    
875
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getPreviousAuditEvent(taxon);
876
        assertNotNull("getPreviousAuditEvent should not return null as there is at least one audit event prior to the current one",auditEvent);
877
    }
878

    
879
    @Test
880
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
881
    public void getPreviousAuditEventAtBeginning() {
882
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
883
        TaxonBase taxon = taxonDao.findByUuid(sphingidae);
884
        assert taxon != null : "taxon cannot be null";
885

    
886
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getPreviousAuditEvent(taxon);
887
        assertNull("getPreviousAuditEvent should return null if we're at the first audit event anyway",auditEvent);
888
    }
889

    
890
    @Test
891
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
892
    public void getNextAuditEvent() {
893
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
894
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
895
        assert taxon != null : "taxon cannot be null";
896

    
897
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getNextAuditEvent(taxon);
898
        assertNotNull("getNextAuditEvent should not return null as there is at least one audit event after the current one",auditEvent);
899
    }
900

    
901
    @Test
902
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
903
    public void getNextAuditEventAtEnd() {
904
        AuditEventContextHolder.getContext().setAuditEvent(mostRecentAuditEvent);
905
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
906
        assert taxon != null : "taxon cannot be null";
907

    
908
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getNextAuditEvent(taxon);
909
        assertNull("getNextAuditEvent should return null as there no more audit events after the current one",auditEvent);
910
    }
911

    
912
    @Test
913
    @DataSet
914
    @ExpectedDataSet
915
    public void testAddChild() throws Exception {
916
        Taxon parent = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
917
        assert parent != null : "taxon cannot be null";
918
        Taxon child = Taxon.NewInstance(null, null);
919
        child.setTitleCache("Acherontia lachesis diehli Eitschberger, 2003", true);
920
        child.addTaxonRelation(parent, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),null, null);
921
        taxonDao.save(child);
922
        setComplete();
923
        endTransaction();
924
    }
925

    
926
    @Test
927
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
928
    public void testFind() {
929
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
930
        assert taxon != null : "taxon cannot be null";
931

    
932
        assertEquals("getTaxonomicChildrenCount should return 1 in this view",1,taxon.getTaxonomicChildrenCount());
933
        assertEquals("getRelationsToThisTaxon should contain 1 TaxonRelationship in this view",1,taxon.getRelationsToThisTaxon().size());
934
    }
935

    
936
    @Test
937
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
938
    public void testFindInPreviousView() {
939
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
940
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
941
        assert taxon != null : "taxon cannot be null";
942

    
943
        assertEquals("getTaxonomicChildrenCount should return 0 in this view",0,taxon.getTaxonomicChildrenCount());
944
        assertTrue("getRelationsToThisTaxon should contain 0 TaxonRelationship in this view",taxon.getRelationsToThisTaxon().isEmpty());
945
    }
946

    
947
    @Test
948
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
949
    public void testGetRelations() {
950
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
951
        assert taxon != null : "taxon cannot be null";
952

    
953
        List<String> propertyPaths = new ArrayList<String>();
954
         propertyPaths.add("fromTaxon");
955
         propertyPaths.add("fromTaxon.name");
956

    
957
         List<OrderHint> orderHints = new ArrayList<OrderHint>();
958
         orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
959

    
960
        List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
961
        assertNotNull("getRelatedTaxa should return a list", taxonRelations);
962
        assertEquals("there should be one TaxonRelationship in the list in the current view",1,taxonRelations.size());
963
        assertTrue("TaxonRelationship.relatedFrom should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon()));
964
        assertTrue("TaxonRelationship.relatedFrom.name should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon().getName()));
965
    }
966

    
967
    @Test
968
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
969
    public void testCountRelations() {
970
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
971
        assert taxon != null : "taxon cannot be null";
972
        assertEquals("countRelatedTaxa should return 1 in the current view",1, taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo));
973
    }
974

    
975
    @Test
976
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
977
    public void testGetRelationsInPreviousView() {
978
       AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
979
       Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
980
       assert taxon != null : "taxon cannot be null";
981

    
982
       List<String> propertyPaths = new ArrayList<String>();
983
       propertyPaths.add("relatedFrom");
984
       propertyPaths.add("relatedFrom.name");
985

    
986
       List<OrderHint> orderHints = new ArrayList<OrderHint>();
987
       orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
988

    
989
       List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
990
       assertNotNull("getRelatedTaxa should return a list",taxonRelations);
991
       assertTrue("there should be no TaxonRelationships in the list in the prior view",taxonRelations.isEmpty());
992
    }
993

    
994
    @Test
995
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
996
    public void testCountRelationsInPreviousView() {
997
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
998
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
999
        assert taxon != null : "taxon cannot be null";
1000
        assertEquals("countRelatedTaxa should return 0 in the current view",0, taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo));
1001
    }
1002

    
1003
    @Test
1004
    @DataSet
1005
    public void testGroupTaxa() {
1006
        List<Grouping> groups = new ArrayList<Grouping>();
1007
        groups.add(new GroupByCount("count",SortOrder.DESCENDING));
1008
        groups.add(new Grouping("name.genusOrUninomial", "genus", "n", SortOrder.ASCENDING));
1009
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1010
        System.out.println("count\tname.genuOrUninomial");
1011
        for(Object[] result : results) {
1012
            System.out.println(result[0] + "\t" + result[1]);
1013
        }
1014
    }
1015

    
1016
    @Test
1017
    @DataSet
1018
    public void testGroupTaxaByClass() {
1019
        List<Grouping> groups = new ArrayList<Grouping>();
1020
        groups.add(new GroupByCount("count",SortOrder.DESCENDING));
1021
        groups.add(new Grouping("class", "class",null, SortOrder.ASCENDING));
1022
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1023
        System.out.println("count\tclass");
1024
        for(Object[] result : results) {
1025
            System.out.println(result[0] + "\t" + result[1]);
1026
        }
1027
    }
1028

    
1029
    @Test
1030
    @DataSet
1031
    public void testNativeSQLOrder() {
1032
        List<OrderHint> orderHints = new ArrayList<OrderHint>();
1033
        orderHints.add(new NativeSqlOrderHint("case when {alias}.titleCache like 'C%' then 0 else 1 end",SortOrder.ASCENDING));
1034

    
1035
        List<TaxonBase> results = taxonDao.list(null, null, orderHints);
1036
        System.out.println("native SQL order");
1037
        for(TaxonBase<?> result : results) {
1038
            System.out.println(result.getTitleCache());
1039
        }
1040
    }
1041

    
1042
    @Test
1043
    @DataSet
1044
    public void testGroupByDateTaxa() {
1045
        List<Grouping> groups = new ArrayList<Grouping>();
1046
        groups.add(new GroupByCount("count",null));
1047
        groups.add(new GroupByDate("created", "dateGroup", SortOrder.ASCENDING, GroupByDate.Resolution.MONTH));
1048
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1049
        System.out.println("count\tyear\tmonth");
1050
        for(Object[] result : results) {
1051
            System.out.println(result[0] + "\t" + result[1] + "\t" + result[2]);
1052
        }
1053
    }
1054

    
1055
    @Test
1056
    @DataSet ("TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
1057
    public final void testGetTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(){
1058
        Classification classification = classificationDao.findByUuid(classificationUuid);
1059
        List<UuidAndTitleCache<TaxonNode>> result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, null, null, null);
1060
        assertNotNull(result);
1061
        assertEquals(5, result.size());
1062

    
1063
        //test exclude
1064
        UUID excludeUUID = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
1065
        List<UUID> excludeUUids = new ArrayList<UUID>();
1066
        excludeUUids.add(excludeUUID);
1067
        result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, excludeUUids, null, null);
1068
        assertEquals(4, result.size());
1069

    
1070
        //test limit
1071
        int limit = 2;
1072
        result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, null, limit, null);
1073
        assertEquals(2, result.size());
1074

    
1075
        //test pattern
1076
        String pattern = "*Rothschi*";
1077
        result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, null, 2, pattern);
1078
        assertNotNull(result);
1079
        assertEquals(1, result.size());
1080
        assertEquals("0b5846e5-b8d2-4ca9-ac51-099286ea4adc", result.get(0).getUuid().toString());
1081

    
1082
    }
1083

    
1084

    
1085
    @Test
1086
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
1087
    //NOTE: There is a problem with loading AuditEvents if this test runs
1088
    //stand alone or as first (one of the first) in the test suite. For some reason
1089
    //the AuditEvent records from the @DataSet are not inserted into the database then,
1090
    //while those inserted by the terms dataset are inserted as well as a completely new one.
1091
    //This problem for some reason does not happen if not running at first place
1092
    public void testGetAuditEventsByTypeWithRestrictions() {
1093
        commitAndStartNewTransaction(new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1094

    
1095
        List<String> propertyPaths = new ArrayList<String>();
1096
        propertyPaths.add("name");
1097
        propertyPaths.add("createdBy");
1098
        propertyPaths.add("updatedBy");
1099

    
1100
        List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
1101
        criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
1102

    
1103
        int count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1104

    
1105
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, criteria,null, null, AuditEventSort.FORWARDS, propertyPaths);
1106
        assertNotNull("getAuditEvents should return a list",auditEvents);
1107
        assertFalse("the list should not be empty",auditEvents.isEmpty());
1108
        assertEquals("There should be one AuditEventRecord in the list",1, auditEvents.size());
1109
    }
1110

    
1111

    
1112
    @Test
1113
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
1114
//    @DataSets({  //for testing only
1115
//        @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml"),
1116
//        @DataSet("TaxonDaoHibernateImplTest.testFindDeletedAuditEvents.xml")
1117
//    })
1118
    //NOTE: There is a problem with loading AuditEvents if this test runs
1119
    //stand alone or as first (one of the first) in the test suite. For some reason
1120
    //the AuditEvent records from the @DataSet are not inserted into the database then,
1121
    //while those inserted by the terms dataset are inserted as well as a completely new one.
1122
    //This problem for some reason does not happen if not running at first place
1123
    public void testGetAuditEventsByTypeWithNoRestrictions() {
1124
        printDataSet(System.out, new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1125
        commitAndStartNewTransaction(new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1126

    
1127
        List<String> propertyPaths = new ArrayList<String>();
1128
        propertyPaths.add("name");
1129
        propertyPaths.add("createdBy");
1130
        propertyPaths.add("updatedBy");
1131
        int count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1132
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, null,null, null, AuditEventSort.FORWARDS, propertyPaths);
1133
        assertNotNull("getAuditEvents should return a list", auditEvents);
1134
        assertFalse("the list should not be empty", auditEvents.isEmpty());
1135
        assertEquals("There should be thirty eight AuditEventRecords in the list", 38, auditEvents.size());
1136
    }
1137

    
1138

    
1139
    @Test
1140
    @DataSet("TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
1141
    public void testGetCommonName(){
1142
       List<Taxon> commonNameResults = taxonDao.getTaxaByCommonName("common%", null,
1143
                MatchMode.BEGINNING, null, null, null, null);
1144

    
1145
        assertNotNull("getTaxaByCommonName should return a list", commonNameResults);
1146
        assertFalse("the list should not be empty", commonNameResults.isEmpty());
1147
        assertEquals("There should be one Taxon with common name", 1,commonNameResults.size());
1148
        assertEquals(" sec. ???", ((TaxonBase)commonNameResults.get(0)).getTitleCache());
1149
    }
1150

    
1151
    @Test
1152
    @DataSet("TaxonDaoHibernateImplTest.testPropertyPath.xml")
1153
    public void testPropertyPath(){
1154
        //Test that BeanInitializer also works on HiberanteProxys
1155
        Classification c = classificationDao.load(UUID.fromString("4bceea53-893f-4685-8c63-6dcec6e85ab1"));
1156
        TaxonNode singleNode = c.getRootNode().getChildNodes().iterator().next();
1157
        Taxon taxonProxy = singleNode.getTaxon();
1158
        Assert.assertTrue("Object to test should be a proxy ", taxonProxy instanceof HibernateProxy);
1159

    
1160
        List<String> propertyPaths = new ArrayList<String>();
1161
        propertyPaths.add("taxonNodes");
1162
        Taxon taxon = (Taxon)this.taxonDao.load(
1163
                UUID.fromString("4a5bc930-844f-45ec-aea8-dd155e1ab25f"),
1164
                propertyPaths);
1165
        Assert.assertSame("Returned object should be the same proxy to assure that we ran initialization on this proxy", taxonProxy, taxon);
1166
    }
1167

    
1168
    /**
1169
     * {@inheritDoc}
1170
     */
1171
    @Override
1172
//    @Test
1173
    public void createTestDataSet() throws FileNotFoundException {
1174
//        Classification classification  = Classification.NewInstance("Test");
1175
//        BotanicalName taxonNameBase = null;
1176
//        Reference sec = null;
1177
//        Taxon taxon = Taxon.NewInstance(taxonNameBase, sec);
1178
//        classification.addChildTaxon(taxon, sec, null);
1179
//
1180
//        classificationDao.save(classification);
1181
//        this.commitAndStartNewTransaction(null);
1182
//
1183
//        writeDbUnitDataSetFile(new String[] {
1184
//                "CLASSIFICATION", "TAXONNAMEBASE",
1185
//                "REFERENCE","TAXONNODE",
1186
//                "TAXONBASE","LANGUAGESTRING",
1187
//                "HIBERNATE_SEQUENCES" // IMPORTANT!!!
1188
//                },
1189
//                "testPropertyPath" );
1190
    }
1191

    
1192
}
(3-3/4)