Project

General

Profile

Download (60.3 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.assertTrue;
17
import static org.junit.Assert.fail;
18

    
19
import java.io.FileNotFoundException;
20
import java.util.ArrayList;
21
import java.util.HashSet;
22
import java.util.List;
23
import java.util.Set;
24
import java.util.UUID;
25

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

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

    
71
/**
72
 * @author a.mueller
73
 * @author ben.clark
74
 */
75
public class TaxonDaoHibernateImplTest extends CdmTransactionalIntegrationTest {
76

    
77
    @SpringBeanByType
78
    private ITaxonDao taxonDao;
79

    
80
    @SpringBeanByType
81
    private IClassificationDao classificationDao;
82

    
83
    @SpringBeanByType
84
    private IReferenceDao referenceDao;
85

    
86
    @SpringBeanByType
87
    IDefinedTermDao definedTermDao;
88

    
89
    private UUID uuid;
90
    private UUID sphingidae;
91
    private UUID acherontia;
92
    private UUID rethera;
93
    private UUID retheraSecCdmtest;
94
    private UUID atroposAgassiz; // a Synonym
95
    private UUID atroposLeach; // a Synonym
96
    private UUID acherontiaLachesis;
97

    
98
    private AuditEvent previousAuditEvent;
99
    private AuditEvent mostRecentAuditEvent;
100

    
101
    private UUID northernAmericaUuid;
102
    private UUID southernAmericaUuid;
103
    private UUID antarcticaUuid;
104

    
105
    private UUID classificationUuid;
106

    
107
    private boolean includeUnpublished = true;
108

    
109
    private static final boolean doTaxa = true;
110
    private static final boolean noTaxa = false;
111
    private static final boolean doSynonyms = true;
112
    private static final boolean noSynonyms = false;
113
    private static final boolean doMisapplied = true;
114
    private static final boolean noMisapplied = false;
115
    private static final boolean doCommonNames = true;
116
    private static final boolean noCommonNames = false;
117

    
118

    
119

    
120
    @SuppressWarnings("unused")
121
    private static final String[] TABLE_NAMES = new String[] {
122
        "HOMOTYPICALGROUP", "HOMOTYPICALGROUP_AUD", "REFERENCE", "REFERENCE_AUD", "TAXONBASE", "TAXONBASE_AUD"
123
        , "TAXONNAME", "TAXONNAME_AUD", "TAXONRELATIONSHIP", "TAXONRELATIONSHIP_AUD" };
124

    
125

    
126
    @Before
127
    public void setUp() {
128

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

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

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

    
150
        classificationUuid = UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9");
151
        includeUnpublished = true;
152
    }
153

    
154
    @After
155
    public void tearDown() {
156
        AuditEventContextHolder.clearContext();
157
    }
158

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

    
170
    @Test
171
    @DataSet
172
    public void testGetTaxaByName() {
173

    
174
        includeUnpublished= true;
175
        boolean accepted = true;
176

    
177
        Reference sec = referenceDao.findById(1);
178
        assert sec != null : "sec must exist";
179

    
180
        @SuppressWarnings("rawtypes")
181
        List<TaxonBase> results = taxonDao.getTaxaByName("Aus", includeUnpublished, sec);
182
        assertNotNull("getTaxaByName should return a List", results);
183
        //assertFalse("The list should not be empty", results.isEmpty());
184
        assertEquals(1, results.size());
185

    
186
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, accepted, includeUnpublished, null, null);
187
        assertNotNull("getTaxaByName should return a List", results);
188

    
189
        int numberOfTaxaByName_A = 5;
190

    
191
        //logger.setLevel(Level.DEBUG); //FIXME #######################
192
        if (logger.isDebugEnabled()) {
193
            for (int i = 0; i < results.size(); i++) {
194
                String nameCache = "";
195
                TaxonName taxonName= results.get(i).getName();
196
                nameCache = taxonName.getNameCache();
197
                logger.debug(results.get(i).getClass() + "(" + i +")" +
198
                        ": Name Cache = " + nameCache + ", Title Cache = " + results.get(i).getTitleCache());
199
            }
200
        }
201

    
202
        assertEquals(numberOfTaxaByName_A, results.size());
203

    
204
        includeUnpublished = false;
205
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, accepted, includeUnpublished, null, null);
206
        assertEquals(numberOfTaxaByName_A, results.size());  // no unpublished yet
207

    
208

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

    
211
//		assertEquals(results.get(0).getTitleCache(), "Abies sec. ???");
212
//		assertEquals(results.get(1).getTitleCache(), "Abies Mill.");
213
//		assertEquals(results.get(2).getTitleCache(), "Abies mill. sec. ???");
214
//		assertEquals(results.get(3).getTitleCache(), "Abies alba sec. ???");
215
//		assertEquals(results.get(4).getTitleCache(), "Abies alba Michx. sec. ???");
216
//		assertEquals(results.get(5).getTitleCache(), "Abies alba Mill. sec. ???");
217

    
218
        includeUnpublished = true;
219
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, accepted, includeUnpublished, null, null);
220
        assertNotNull("getTaxaByName should return a List", results);
221
        assertEquals(numberOfTaxaByName_A, results.size());
222

    
223
        results = taxonDao.getTaxaByName("Aus", MatchMode.EXACT, accepted, includeUnpublished, null, null);
224
        assertNotNull("getTaxaByName should return a List", results);
225
        assertEquals("Results list should contain one entity",1,results.size());
226
    }
227

    
228

    
229
    @Test
230
    @DataSet (loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
231
    public void testGetTaxaByNameWithMisappliedNames(){
232

    
233
        Classification classification = classificationDao.load(classificationUuid);
234

    
235
        /* NOTE:
236
         * The testdata contains 3 misapplied names (1. nameCache = Aus, 2. nameCache = Rethera, 3. nameCache = Daphnis),
237
         * two contained in the classification used in this test,
238
         * the other one is not contained in any classification. This later case is the more general situation.
239
         * Misapplied names should be found regardless of whether they are contained in a classification or not.
240
         */
241
        //two accepted taxa starting with R in classification "TestBaum"
242
        @SuppressWarnings("rawtypes")
243
        List<TaxonBase> results = taxonDao.getTaxaByName(doTaxa, noSynonyms, noMisapplied, noCommonNames, false, "R*", classification, MatchMode.BEGINNING,
244
                null, includeUnpublished, null, null, null, null);
245
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
246

    
247
        //three taxa, 2 accepted and 1 misapplied name starting with R
248
        results = taxonDao.getTaxaByName(doTaxa, noSynonyms, doMisapplied, noCommonNames, false, "R*", null, MatchMode.BEGINNING,
249
                null, includeUnpublished, null, null, null, null);
250
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
251

    
252
        //one synonym has no accepted taxon
253
        results = taxonDao.getTaxaByName(doTaxa, doSynonyms, doMisapplied, noCommonNames, false, "A*", null, MatchMode.BEGINNING,
254
                null, includeUnpublished, null, null, null, null);
255
        Assert.assertEquals("There should be 11 Taxa",11, results.size());
256

    
257
        //two accepted taxa in classification and 1 misapplied name with accepted name in classification
258
        results = taxonDao.getTaxaByName(doTaxa, doSynonyms, doMisapplied, noCommonNames, false, "R*", classification, MatchMode.BEGINNING,
259
                null, includeUnpublished, null, null, null, null);
260
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
261
        //same with unpublished
262
        includeUnpublished = false;
263
        results = taxonDao.getTaxaByName(doTaxa, doSynonyms, doMisapplied, noCommonNames, false, "R*", classification, MatchMode.BEGINNING,
264
                null, includeUnpublished, null, null, null, null);
265
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
266
        includeUnpublished = true;
267

    
268

    
269
        //same as above because all taxa, synonyms and misapplied names starting with R are in the classification
270
        results = taxonDao.getTaxaByName(doTaxa, doSynonyms, doMisapplied, noCommonNames, false, "R*", null, MatchMode.BEGINNING,
271
                null, includeUnpublished, null, null, null, null);
272
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
273

    
274
        //find misapplied names with accepted taxon in the classification, the accepted taxa of two misapplied names are in the classification
275
        results = taxonDao.getTaxaByName(noTaxa, noSynonyms, doMisapplied, noCommonNames, false, "*", classification, MatchMode.BEGINNING,
276
                null, includeUnpublished, null, null, null, null);
277
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
278

    
279
        //find misapplied names beginning with R
280
        results = taxonDao.getTaxaByName(noTaxa, noSynonyms, doMisapplied, noCommonNames, false, "R*", null, MatchMode.BEGINNING,
281
                null, includeUnpublished, null, null, null, null);
282
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
283

    
284
        //find all three misapplied names
285
        results = taxonDao.getTaxaByName(noTaxa, noSynonyms, doMisapplied, noCommonNames, false, "*", null, MatchMode.BEGINNING,
286
                null, includeUnpublished, null, null, null, null);
287
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
288

    
289
    }
290
    /**
291
     * Test for all not covered possibilities of searches
292
     */
293
    @Test
294
    @DataSet (loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
295
    public void testGetTaxaByNameVariants(){
296
        @SuppressWarnings("rawtypes")
297
        List<TaxonBase> results = taxonDao.getTaxaByName(noTaxa, noSynonyms, noMisapplied, doCommonNames, false, "c*", null, MatchMode.BEGINNING,
298
                null, includeUnpublished, null, null, null, null);
299
        Assert.assertEquals("There should be 2 Taxa",2, results.size());
300

    
301
        results = taxonDao.getTaxaByName(noTaxa, noSynonyms, doMisapplied, doCommonNames, false, "R*", null, MatchMode.BEGINNING,
302
                null, includeUnpublished, null, null, null, null);
303
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
304

    
305
        results = taxonDao.getTaxaByName(noTaxa, doSynonyms, doMisapplied, doCommonNames, false, "R*", null, MatchMode.BEGINNING,
306
                null, includeUnpublished, null, null, null, null);
307
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
308

    
309
        results = taxonDao.getTaxaByName(noTaxa, doSynonyms, noMisapplied, doCommonNames, false, "c*", null, MatchMode.BEGINNING,
310
                null, includeUnpublished, null, null, null, null);
311
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
312

    
313
        results = taxonDao.getTaxaByName(doTaxa, noSynonyms, noMisapplied, doCommonNames, false, "c*", null, MatchMode.BEGINNING,
314
                null, includeUnpublished, null, null, null, null);
315
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
316

    
317
        Classification classification = classificationDao.load(classificationUuid);
318
        results = taxonDao.getTaxaByName(noTaxa, noSynonyms, noMisapplied, doCommonNames, false, "c*", classification, MatchMode.BEGINNING,
319
                null, includeUnpublished, null, null, null, null);
320
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
321

    
322
        Set<NamedArea> namedAreas = new HashSet<>();
323
        namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
324
        results = taxonDao.getTaxaByName(noTaxa, noSynonyms, noMisapplied, doCommonNames, false, "c*", null, MatchMode.BEGINNING,
325
                namedAreas, includeUnpublished, null, null, null, null);
326
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
327
    }
328

    
329
    /**
330
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}.
331
     */
332
    @Test
333
    @DataSet
334
    public void testGetTaxaByNameForEditor() {
335
        Reference sec = referenceDao.findById(1);
336
        assert sec != null : "sec must exist";
337

    
338
        @SuppressWarnings("rawtypes")
339
        List<UuidAndTitleCache<? extends IdentifiableEntity>> results = taxonDao.getTaxaByNameForEditor(
340
                doTaxa, doSynonyms, noMisapplied, noCommonNames, false, includeUnpublished, "Acher", null, MatchMode.BEGINNING, null, null);
341
        assertNotNull("getTaxaByName should return a List", results);
342
        assertFalse("The list should not be empty", results.isEmpty());
343
        assertEquals(4, results.size());
344

    
345

    
346
        results = taxonDao.getTaxaByNameForEditor(doTaxa, doSynonyms, noMisapplied, noCommonNames, false,includeUnpublished, "A",null, MatchMode.BEGINNING, null, null);
347
        assertNotNull("getTaxaByName should return a List", results);
348
        assertEquals(7, results.size());
349

    
350

    
351
        results = taxonDao.getTaxaByNameForEditor(doTaxa, noSynonyms, noMisapplied, noCommonNames, false, includeUnpublished, "A", null, MatchMode.BEGINNING, null, null);
352
        assertNotNull("getTaxaByName should return a List", results);
353
        assertEquals(5, results.size());
354
        assertEquals(results.get(0).getType(), Taxon.class);
355

    
356
        results = taxonDao.getTaxaByNameForEditor(noTaxa, doSynonyms, noMisapplied, noCommonNames, false, includeUnpublished, "A", null, MatchMode.BEGINNING, null, null);
357
        assertNotNull("getTaxaByName should return a List", results);
358
        assertEquals(2, results.size());
359
        assertEquals(results.get(0).getType(), Synonym.class);
360

    
361
        results = taxonDao.getTaxaByNameForEditor(doTaxa, doSynonyms, noMisapplied, noCommonNames, false,includeUnpublished, "Aus", null, MatchMode.EXACT, null, null);
362
        assertNotNull("getTaxaByName should return a List", results);
363
        assertEquals("Results list should contain one entity",1,results.size());
364

    
365
        results = taxonDao.getTaxaByNameForEditor(doTaxa, doSynonyms, doMisapplied, noCommonNames, false, includeUnpublished, "A", null, MatchMode.BEGINNING, null, null);
366
        assertNotNull("getTaxaByName should return a List", results);
367
        assertEquals("Results list should contain one entity", 8, results.size());
368

    
369
        //TODO: test the search for misapplied names
370

    
371
    }
372

    
373

    
374
    /**
375
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}
376
     * restricting the search by a set of Areas.
377
     */
378
    @Test
379
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
380
    public void testGetTaxaByNameAndArea() {
381

    
382
        Set<NamedArea> namedAreas = new HashSet<>();
383
        namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
384
        //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
385
        //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
386

    
387
        Classification taxonmicTree = classificationDao.findByUuid(classificationUuid);
388

    
389
        // prepare some synonym relation ships for some tests
390
        Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
391
        Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
392
        taxonRethera.addSynonym(synAtroposAgassiz, SynonymType.SYNONYM_OF());
393
//        logger.warn("addSynonym(..)");
394

    
395
        Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
396
        Taxon taxonRetheraSecCdmTest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
397
        taxonRetheraSecCdmTest.addSynonym(synAtroposLeach, SynonymType.SYNONYM_OF());
398
        this.taxonDao.save(taxonRetheraSecCdmTest);
399

    
400
        Taxon test = (Taxon)this.taxonDao.findByUuid(retheraSecCdmtest);
401
//        Set<Synonym> synonyms3 = test.getSynonyms();
402
        // 1. searching for a taxon (Rethera)
403
        //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
404

    
405
        @SuppressWarnings("rawtypes")
406
        List<TaxonBase> results = taxonDao.getTaxaByName(doTaxa, noSynonyms, noMisapplied, noCommonNames, false, "Rethera", null, MatchMode.BEGINNING, namedAreas,
407
                includeUnpublished, null, null, null, null);
408
        assertNotNull("getTaxaByName should return a List", results);
409
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
410

    
411
        results = taxonDao.getTaxaByName(noTaxa, noSynonyms, noMisapplied, doCommonNames, false, "com*", null, MatchMode.BEGINNING, namedAreas,
412
                includeUnpublished, null, null, null, null);
413
            assertNotNull("getTaxaByName should return a List", results);
414
            assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
415

    
416
        // 2. searching for a taxon (Rethera) contained in a specific classification
417
        results = taxonDao.getTaxaByName(doTaxa, noSynonyms, noMisapplied, noCommonNames, false, "Rethera", taxonmicTree, MatchMode.BEGINNING, namedAreas,
418
                includeUnpublished, null, null, null, null);
419
        assertNotNull("getTaxaByName should return a List", results);
420
        assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
421

    
422

    
423
        // 3. searching for Synonyms
424
        results = taxonDao.getTaxaByName(noTaxa, doSynonyms, noMisapplied, noCommonNames, false, "Atropo", null, MatchMode.ANYWHERE, null,
425
                includeUnpublished, null, null, null, null);
426
        assertNotNull("getTaxaByName should return a List", results);
427
        /*System.err.println(results.get(0).getTitleCache() + " - " +results.get(1).getTitleCache() + " - " +results.get(2).getTitleCache() );
428

    
429

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

    
434
        // 4. searching for Synonyms
435
        results = taxonDao.getTaxaByName(noTaxa, doSynonyms, noMisapplied, noCommonNames, false,"Atropo", null, MatchMode.BEGINNING, null,
436
                includeUnpublished, null, null, null, null);
437
        assertNotNull("getTaxaByName should return a List", results);
438
        assertTrue("expected to find three taxa but found "+results.size(), results.size() == 3);
439

    
440

    
441
        // 5. searching for a Synonyms and Taxa
442
        results = taxonDao.getTaxaByName(doTaxa, doSynonyms, noMisapplied, noCommonNames, false,"A", null, MatchMode.BEGINNING, namedAreas,
443
                includeUnpublished, null, null, null, null);
444
        //only five taxa have a distribution
445
        assertNotNull("getTaxaByName should return a List", results);
446
        assertTrue("expected to find 8 taxa but found "+results.size(), results.size() == 8);
447
    }
448

    
449

    
450
    /**
451
     * 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)}
452
     * restricting the search by a set of Areas.
453
     */
454
    @Test
455
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
456
    public void testFindByNameTitleCache() {
457

    
458
        Set<NamedArea> namedAreas = new HashSet<>();
459
        namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
460
        //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
461
        //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
462

    
463
        Classification classification = classificationDao.findByUuid(classificationUuid);
464

    
465
        // prepare some synonym relation ships for some tests
466
        Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
467
        Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
468
        taxonRethera.addSynonym(synAtroposAgassiz, SynonymType.SYNONYM_OF());
469
        logger.warn("addSynonym(..)");
470
        this.taxonDao.clear();
471
        Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
472
        Taxon taxonRetheraSecCdmtest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
473
        taxonRetheraSecCdmtest.addSynonym(synAtroposLeach, SynonymType.SYNONYM_OF());
474
        this.taxonDao.clear();
475
        // 1. searching for a taxon (Rethera)
476
        //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
477

    
478
        @SuppressWarnings("rawtypes")
479
        List<TaxonBase> results = taxonDao.findByNameTitleCache(true, false, includeUnpublished, "Rethera Rothschild & Jordan, 1903", null, MatchMode.EXACT, namedAreas,
480
                null, null, null, null);
481
        assertNotNull("getTaxaByName should return a List", results);
482
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
483

    
484
        // 2. searching for a taxon (Rethera) contained in a specific classification
485
        results = taxonDao.findByNameTitleCache(true, false, includeUnpublished, "Rethera Rothschild & Jordan, 1903", classification, MatchMode.EXACT, namedAreas,
486
                null, null, null, null);
487
        assertNotNull("getTaxaByName should return a List", results);
488
        assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
489

    
490

    
491
        // 3. searching for Synonyms
492
        results = taxonDao.findByNameTitleCache(false, true, includeUnpublished, "*Atropo", null, MatchMode.ANYWHERE, null,
493
                null, null, null, null);
494
        assertNotNull("getTaxaByName should return a List", results);
495
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
496

    
497
        // 4. searching for Synonyms
498
        results = taxonDao.findByNameTitleCache(false, true, includeUnpublished, "Atropo", null, MatchMode.BEGINNING, null,
499
                null, null, null, null);
500
        assertNotNull("getTaxaByName should return a List", results);
501
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
502

    
503

    
504
        // 5. searching for a Synonyms and Taxa
505
        //   attache a synonym first
506
        Synonym syn = (Synonym)taxonDao.findByUuid(this.atroposLeach);
507
        Taxon tax = (Taxon) taxonDao.findByUuid(rethera);
508
        tax.addSynonym(syn, SynonymType.HETEROTYPIC_SYNONYM_OF());
509

    
510
        taxonDao.save(tax);
511
        results = taxonDao.findByNameTitleCache(true, true, includeUnpublished, "A", null, MatchMode.BEGINNING, namedAreas,
512
                null, null, null, null);
513
        assertNotNull("getTaxaByName should return a List", results);
514
        assertTrue("expected to find 8 taxa but found "+results.size(), results.size() == 8);
515
    }
516

    
517
    @Test
518
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
519
    public void testTaxonNameInTwoClassifications(){
520
        List<String> propertyPaths = new ArrayList<>();
521
        propertyPaths.add("taxonNodes");
522
        @SuppressWarnings("rawtypes")
523
        List<TaxonBase> taxa = taxonDao.getTaxaByName(doTaxa, doSynonyms, noMisapplied, noCommonNames, false,"P", null, MatchMode.BEGINNING,
524
                null, includeUnpublished, null, null, null, null);
525
        Taxon taxon = (Taxon)taxa.get(0);
526
        Set<TaxonNode> nodes = taxon.getTaxonNodes();
527
        assertTrue(nodes.size() == 1);
528
        //assertNotNull(taxa);
529
        //assertTrue(taxa.size() > 0);
530
    }
531

    
532
    @Test
533
    @DataSet
534
    public void testFindByUuid() {
535
        Taxon taxon = (Taxon)taxonDao.findByUuid(uuid);
536
        assertNotNull("findByUuid should return a taxon", taxon);
537
        assertFalse("findByUuid should not return a taxon with it's name initialized",Hibernate.isInitialized(taxon.getName()));
538
    }
539

    
540
    @Test
541
    @DataSet
542
    public void testLoad() {
543
        List<String> propertyPaths = new ArrayList<>();
544
        propertyPaths.add("name");
545
        propertyPaths.add("sec");
546
        Taxon taxon = (Taxon)taxonDao.load(uuid, propertyPaths);
547
        assertNotNull("findByUuid should return a taxon",taxon);
548
        assertTrue("load should return a taxon with it's name initialized, given that the property was specified in the method",Hibernate.isInitialized(taxon.getName()));
549
        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()));
550
    }
551

    
552
    @Test
553
    @DataSet
554
    public void testCountTaxonRelationshipsByTaxon()	{
555
        Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
556
        assert taxon != null : "taxon must exist";
557

    
558
        long numberOfRelatedTaxa = taxonDao.countTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
559
                includeUnpublished, TaxonRelationship.Direction.relatedTo);
560
        assertEquals("countTaxonRelationships should return 8", 8, numberOfRelatedTaxa);
561
    }
562

    
563
    @Test
564
    @DataSet
565
    public void testCountTaxaByName() {
566
        long numberOfTaxa = taxonDao.countTaxaByName(true, false, false, false,false, "A", null, MatchMode.BEGINNING, null, includeUnpublished);
567
        assertEquals(5, numberOfTaxa);
568
        numberOfTaxa = taxonDao.countTaxaByName(true, false, false, false, false,"Smerinthus kindermannii", null, MatchMode.EXACT, null, includeUnpublished);
569
        assertEquals(1, numberOfTaxa);
570
        numberOfTaxa = taxonDao.countTaxaByName(false, true, false, false, false,"A", null, MatchMode.BEGINNING, null, includeUnpublished);
571
        assertEquals(2, numberOfTaxa);
572
        numberOfTaxa = taxonDao.countTaxaByName(true, true, false, false, false,"A", null, MatchMode.BEGINNING, null, includeUnpublished);
573
        assertEquals(7, numberOfTaxa);
574
        numberOfTaxa = taxonDao.countTaxaByName(true, true, false, false,false, "Aasfwerfwf fffe", null, MatchMode.BEGINNING, null, includeUnpublished);
575
        assertEquals(0, numberOfTaxa);
576
//	FIXME implement test for search in specific classification
577
//		Reference reference = referenceDao.findByUuid(UUID.fromString("596b1325-be50-4b0a-9aa2-3ecd610215f2"));
578
//		numberOfTaxa = taxonDao.countTaxaByName("A*", MatchMode.BEGINNING, SelectMode.ALL, null, null);
579
//		assertEquals(numberOfTaxa, 2);
580
    }
581

    
582
    @Test
583
    @DataSet
584
    public void testRelatedTaxa() {
585
        Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
586
        assert taxon != null : "taxon must exist";
587

    
588
        List<String> propertyPaths = new ArrayList<>();
589
        propertyPaths.add("fromTaxon");
590
        propertyPaths.add("fromTaxon.name");
591
        List<OrderHint> orderHints = new ArrayList<>();
592
        orderHints.add(new OrderHint("relatedFrom.name.genusOrUninomial", SortOrder.ASCENDING));
593
        orderHints.add(new OrderHint("relatedFrom.name.specificEpithet", SortOrder.ASCENDING));
594
        orderHints.add(new OrderHint("relatedFrom.name.infraSpecificEpithet", SortOrder.ASCENDING));
595

    
596
        long count = taxonDao.countTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
597
                includeUnpublished, TaxonRelationship.Direction.relatedTo);
598
        assertEquals("Count should return 8 (related taxa)", 8, count);
599

    
600
        List<TaxonRelationship> relatedTaxa = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
601
                includeUnpublished, null, null, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
602
        assertNotNull("getRelatedTaxa should return a List",relatedTaxa);
603
        assertEquals("getRelatedTaxa should return all 8 related taxa", 8, relatedTaxa.size());
604
        assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon()));
605
        assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon().getName()));
606

    
607
        assertEquals("Acherontia should appear first in the list of related taxa", relatedTaxa.get(0).getFromTaxon().getTitleCache(), "Acherontia Laspeyres, 1809 sec. cate-sphingidae.org");
608
        assertEquals("Sphingonaepiopsis should appear last in the list of related taxa", "Sphingonaepiopsis Wallengren, 1858 sec. cate-sphingidae.org", relatedTaxa.get(relatedTaxa.size()-1).getFromTaxon().getTitleCache());
609
    }
610

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

    
617
        List<String> propertyPaths = new ArrayList<>();
618
        propertyPaths.add("fromTaxon");
619
        propertyPaths.add("fromTaxon.name");
620

    
621
        List<OrderHint> orderHints = new ArrayList<>();
622
        orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
623

    
624
        int pageSize = 3;
625
        List<TaxonRelationship> firstPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
626
                includeUnpublished, pageSize, 0, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
627
        List<TaxonRelationship> secondPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
628
                includeUnpublished, pageSize, 1, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
629
        List<TaxonRelationship> thirdPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
630
                includeUnpublished, pageSize, 2, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
631

    
632
        assertNotNull("getRelatedTaxa: 3, 0 should return a List",firstPage);
633
        assertEquals("getRelatedTaxa: 3, 0 should return a List with 3 elements", pageSize,firstPage.size());
634
        assertNotNull("getRelatedTaxa: 3, 1 should return a List",secondPage);
635
        assertEquals("getRelatedTaxa: 3, 1 should return a List with 3 elements", pageSize, secondPage.size());
636
        assertNotNull("getRelatedTaxa: 3, 2 should return a List",thirdPage);
637
        assertEquals("getRelatedTaxa: 3, 2 should return a List with 2 elements", 2, thirdPage.size());
638
    }
639

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

    
646
        long numberOfRelatedSynonym = taxonDao.countSynonyms(taxon,null);
647
        assertEquals("countSynonyms should return 3", 3, numberOfRelatedSynonym);
648
    }
649

    
650
    @Test
651
    @DataSet
652
    public void testGetSynonyms()	{
653
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
654
        assert taxon != null : "taxon must exist";
655
        List<String> propertyPaths = new ArrayList<String>();
656
        propertyPaths.add("synonym");
657
        propertyPaths.add("synonym.name");
658

    
659
        List<OrderHint> orderHints = new ArrayList<>();
660
        orderHints.add(new OrderHint("titleCache", SortOrder.ASCENDING));
661

    
662
        List<Synonym> synonyms = taxonDao.getSynonyms(taxon, null, null, null,orderHints,propertyPaths);
663

    
664
        assertNotNull("getSynonyms should return a List", synonyms);
665
        assertEquals("getSynonyms should return 3 synonyms", 3, synonyms.size());
666
        assertTrue("getSynonyms should return synonym objects with the synonym initialized", Hibernate.isInitialized(synonyms.get(0)));
667
    }
668

    
669
    @Test
670
    @DataSet
671
    public void testCountSynonymsByType()	{
672
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
673
        assert taxon != null : "taxon must exist";
674

    
675
        long numberOfTaxonomicSynonyms = taxonDao.countSynonyms(taxon, SynonymType.HETEROTYPIC_SYNONYM_OF());
676
        assertEquals("countSynonyms should return 4", 3, numberOfTaxonomicSynonyms);
677
    }
678

    
679
    @Test
680
    @DataSet
681
    public void testSynonymsByType() {
682
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
683
        assert taxon != null : "taxon must exist";
684

    
685
        List<Synonym> synonyms = taxonDao.getSynonyms(taxon, SynonymType.HETEROTYPIC_SYNONYM_OF(), null, null,null,null);
686

    
687
        assertNotNull("getSynonyms should return a List", synonyms);
688
        assertEquals("getSynonyms should return 4 Synonyms", 3, synonyms.size());
689
    }
690

    
691
    @Test
692
    @DataSet
693
    public void testPageSynonyms(){
694
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
695
        assert taxon != null : "taxon must exist";
696

    
697
        int pageSize = 2;
698
        List<Synonym> firstPage = taxonDao.getSynonyms(taxon, null, pageSize, 0,null,null);
699
        List<Synonym> secondPage = taxonDao.getSynonyms(taxon, null, pageSize, 1,null,null);
700

    
701
        assertNotNull("getSynonyms: 2, 0 should return a List",firstPage);
702
        assertEquals("getSynonyms: 2, 0 should return 2 synonyms", pageSize,firstPage.size());
703
        assertNotNull("getSynonyms: 2, 1 should return a List",secondPage);
704
        assertEquals("getSynonyms: 2, 1 should return 1 synonym", 1, secondPage.size());
705
    }
706

    
707
    @Test
708
    @DataSet
709
    public void testCountTaxonRelationships() {
710
        long count = taxonDao.countTaxonRelationships(null);
711
        assertEquals("There should be 11 relationships", 11, count);
712

    
713
        Set<TaxonRelationshipType> types = new HashSet<>();
714
        count = taxonDao.countTaxonRelationships(types);
715
        assertEquals("Empty filter should return empty result", 0, count);
716

    
717
        types.add(TaxonRelationshipType.CONGRUENT_TO());
718
        count = taxonDao.countTaxonRelationships(types);
719
        assertEquals("There should be no congruent relationship", 0, count);
720

    
721
        types.add(TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN());
722
        count = taxonDao.countTaxonRelationships(types);
723
        assertEquals("There should be 11 tax included relationships", 11, count);
724
    }
725

    
726
    @Test
727
    @DataSet
728
    public void testlistTaxonRelationships() {
729
        List<TaxonRelationship> rels = taxonDao.getTaxonRelationships(null, null, null, null, null);
730
        assertEquals("There should be 11 relationships", 11, rels.size());
731

    
732
        rels = taxonDao.getTaxonRelationships(null, 2, 3, null, null);
733
        assertEquals("There should be 11 relationships", 2, rels.size());
734

    
735
        Set<TaxonRelationshipType> types = new HashSet<>();
736
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
737
        assertEquals("Empty filter should return empty result", 0, rels.size());
738

    
739
        types.add(TaxonRelationshipType.CONGRUENT_TO());
740
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
741
        assertEquals("There should be no congruent relationship", 0, rels.size());
742

    
743
        types.add(TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN());
744
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
745
        assertEquals("There should be 11 tax included relationships", 11, rels.size());
746
    }
747

    
748
    @Test
749
    @DataSet("TaxonNodeDaoHibernateImplTest.xml")
750
    public void testListAcceptedTaxaFor()  {
751
        UUID acheontitia_ciprosus = UUID.fromString("3ef145f7-bd92-4a64-8afd-2b8203e00e02");
752

    
753
        Synonym synonym = (Synonym)taxonDao.findByUuid(acheontitia_ciprosus);
754
        assertNotNull("synonym must exist", synonym);
755

    
756
        Taxon taxon = taxonDao.acceptedTaxonFor(synonym, null, null);
757
        assertNotNull("listAcceptedTaxaFor should return a taxon", taxon);
758

    
759
        Classification classification = classificationDao.load(classificationUuid);
760
        assertNotNull("classification must exist", classification);
761

    
762
        taxon = taxonDao.acceptedTaxonFor(synonym, classification, null);
763
        assertNull("listAcceptedTaxaFor should return not taxon due to classification filter", taxon);
764
    }
765

    
766

    
767
    @Test
768
    @DataSet
769
    public void testGetTaxonMatchingUninomial() {
770
        @SuppressWarnings("rawtypes")
771
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class, "Smerinthus", "*", "*", "*","*",null,null,null);
772

    
773
        assertNotNull("findTaxaByName should return a List", result);
774
        assertEquals("findTaxaByName should return two Taxa",2,result.size());
775
        assertEquals("findTaxaByName should return a Taxon with id 5",5,result.get(0).getId());
776
    }
777

    
778
    @Test
779
    @DataSet
780
    public void testGetTaxonMatchingSpeciesBinomial() {
781
        @SuppressWarnings("rawtypes")
782
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class, "Smerinthus", null, "kindermannii", null,"*",null,null,null);
783

    
784
        assertNotNull("findTaxaByName should return a List", result);
785
        assertEquals("findTaxaByName should return one Taxon",1,result.size());
786
        assertEquals("findTaxaByName should return a Taxon with id 8",8,result.get(0).getId());
787
    }
788

    
789
    @Test
790
    @DataSet
791
    public void testGetTaxonMatchingTrinomial() {
792
        @SuppressWarnings("rawtypes")
793
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Cryptocoryne", null,"purpurea","borneoensis","*",null,null,null);
794

    
795
        assertNotNull("findTaxaByName should return a List", result);
796
        assertEquals("findTaxaByName should return one Taxon",1,result.size());
797
        assertEquals("findTaxaByName should return a Taxon with id 38",38,result.get(0).getId());
798
    }
799

    
800
    @Test
801
    @DataSet
802
    public void testNegativeMatch() {
803
        @SuppressWarnings("rawtypes")
804
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Acherontia", null,"atropos","dehli",null,null,null,null);
805

    
806
        assertNotNull("findTaxaByName should return a List", result);
807
        assertTrue("findTaxaByName should return an empty List",result.isEmpty());
808
    }
809

    
810
    @Test
811
    @DataSet
812
    public void testCountAllTaxa() {
813
        long numberOfTaxa = taxonDao.count(Taxon.class);
814
        assertEquals("count should return 14 taxa", 14, numberOfTaxa);
815
    }
816

    
817
    @Test
818
    @DataSet
819
    public void testListAllTaxa() {
820
        List<Taxon> taxa = taxonDao.list(Taxon.class,100, 0);
821
        assertNotNull("list should return a List", taxa);
822
        assertEquals("list should return 14 taxa", 14, taxa.size());
823
    }
824

    
825
    @Test
826
    @DataSet
827
   // @ExpectedDataSet
828
    public void testDelete() {
829
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
830
        assert taxon != null : "taxon must exist";
831
        taxonDao.delete(taxon);
832
        taxon = (Taxon)taxonDao.findByUuid(acherontia);
833
        assert taxon == null : "taxon must not exist";
834
        setComplete();
835
        endTransaction();
836
//        try {
837
//            printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
838
//        } catch (FileNotFoundException e) {
839
//            e.printStackTrace();
840
//        }
841
    }
842

    
843
    @Test
844
    @DataSet
845
    @ExpectedDataSet("TaxonDaoHibernateImplTest.testDelete-result.xml")
846
    public void testDeleteWithMarker() {
847
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
848
        taxon.addMarker(Marker.NewInstance(MarkerType.IS_DOUBTFUL(), true));
849
        taxonDao.save(taxon);
850
        assert taxon != null : "taxon must exist";
851

    
852
        taxonDao.delete(taxon);
853
        commitAndStartNewTransaction(null);
854
        taxon = (Taxon)taxonDao.findByUuid(acherontia);
855
        assert taxon == null : "taxon must not exist";
856
        setComplete();
857
        endTransaction();
858
//        try {
859
//            printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
860
//        } catch (FileNotFoundException e) {
861
//            e.printStackTrace();
862
//        }
863
    }
864

    
865
    @Test
866
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
867
    public void testFindDeleted() {
868
        TaxonBase<?> taxon = taxonDao.findByUuid(acherontia);
869
        assertNull("findByUuid should return null in this view", taxon);
870
        assertFalse("exist should return false in this view",taxonDao.exists(acherontia));
871
    }
872

    
873
    @Test
874
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
875
    public void testFindDeletedInPreviousView() {
876
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
877
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
878
        assertNotNull("findByUuid should return a taxon in this view",taxon);
879
        assertTrue("exists should return true in this view", taxonDao.exists(acherontia));
880

    
881
        try{
882
            assertEquals("There should be 3 relations to this taxon in this view",3,taxon.getRelationsToThisTaxon().size());
883
        } catch(Exception e) {
884
            fail("We should not experience any problems initializing proxies with envers");
885
        }
886
    }
887

    
888
    @Test
889
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
890
    public void testGetAuditEvents() {
891
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
892
        assert taxon != null : "taxon cannot be null";
893

    
894
        List<String> propertyPaths = new ArrayList<>();
895
        propertyPaths.add("name");
896
        propertyPaths.add("createdBy");
897
        propertyPaths.add("updatedBy");
898

    
899
        @SuppressWarnings("rawtypes")
900
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,null,propertyPaths);
901
        assertNotNull("getAuditEvents should return a list",auditEvents);
902
        assertFalse("the list should not be empty",auditEvents.isEmpty());
903
        assertEquals("There should be two AuditEventRecords in the list",2, auditEvents.size());
904
    }
905

    
906
    @Test
907
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
908
    public void testGetAuditEventsFromNow() {
909
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
910
        TaxonBase<?> taxon =  taxonDao.findByUuid(sphingidae);
911
        assert taxon != null : "taxon cannot be null";
912

    
913
        @SuppressWarnings("rawtypes")
914
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,AuditEventSort.FORWARDS,null);
915
        assertNotNull("getAuditEvents should return a list",auditEvents);
916
        assertFalse("the list should not be empty",auditEvents.isEmpty());
917
        assertEquals("There should be one audit event in the list",1,auditEvents.size());
918
    }
919

    
920
    @Test
921
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
922
    public void testCountAuditEvents() {
923
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
924
        assert taxon != null : "taxon cannot be null";
925

    
926
        long numberOfAuditEvents = taxonDao.countAuditEvents(taxon, null);
927
        assertEquals("countAuditEvents should return 2",numberOfAuditEvents,2);
928
    }
929

    
930
    @Test
931
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
932
    public void getPreviousAuditEvent() {
933
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
934
        assert taxon != null : "taxon cannot be null";
935

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

    
940
    @Test
941
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
942
    public void getPreviousAuditEventAtBeginning() {
943
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
944
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
945
        assert taxon != null : "taxon cannot be null";
946

    
947
        @SuppressWarnings("rawtypes")
948
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getPreviousAuditEvent(taxon);
949
        assertNull("getPreviousAuditEvent should return null if we're at the first audit event anyway",auditEvent);
950
    }
951

    
952
    @Test
953
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
954
    public void getNextAuditEvent() {
955
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
956
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
957
        assert taxon != null : "taxon cannot be null";
958

    
959
        @SuppressWarnings("rawtypes")
960
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getNextAuditEvent(taxon);
961
        assertNotNull("getNextAuditEvent should not return null as there is at least one audit event after the current one",auditEvent);
962
    }
963

    
964
    @Test
965
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
966
    public void getNextAuditEventAtEnd() {
967
        AuditEventContextHolder.getContext().setAuditEvent(mostRecentAuditEvent);
968
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
969
        assert taxon != null : "taxon cannot be null";
970

    
971
        @SuppressWarnings("rawtypes")
972
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getNextAuditEvent(taxon);
973
        assertNull("getNextAuditEvent should return null as there no more audit events after the current one",auditEvent);
974
    }
975

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

    
982
       assertEquals("getRelationsToThisTaxon should contain 1 TaxonRelationship in this view",1,taxon.getRelationsToThisTaxon().size());
983
    }
984

    
985
    @Test
986
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
987
    public void testFindInPreviousView() {
988
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
989
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
990
        assert taxon != null : "taxon cannot be null";
991

    
992
        assertTrue("getRelationsToThisTaxon should contain 0 TaxonRelationship in this view",taxon.getRelationsToThisTaxon().isEmpty());
993
    }
994

    
995
    @Test
996
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
997
    public void testGetRelations() {
998
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
999
        assert taxon != null : "taxon cannot be null";
1000

    
1001
        List<String> propertyPaths = new ArrayList<>();
1002
         propertyPaths.add("fromTaxon");
1003
         propertyPaths.add("fromTaxon.name");
1004

    
1005
         List<OrderHint> orderHints = new ArrayList<>();
1006
         orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
1007

    
1008
        List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
1009
                includeUnpublished, null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
1010
        assertNotNull("getRelatedTaxa should return a list", taxonRelations);
1011
        assertEquals("there should be one TaxonRelationship in the list in the current view",1,taxonRelations.size());
1012
        assertTrue("TaxonRelationship.relatedFrom should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon()));
1013
        assertTrue("TaxonRelationship.relatedFrom.name should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon().getName()));
1014
    }
1015

    
1016
    @Test
1017
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
1018
    public void testCountRelations() {
1019
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
1020
        assert taxon != null : "taxon cannot be null";
1021
        assertEquals("countRelatedTaxa should return 1 in the current view",1, taxonDao.countTaxonRelationships(
1022
                taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
1023
                includeUnpublished, TaxonRelationship.Direction.relatedTo));
1024
    }
1025

    
1026
    @Test
1027
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
1028
    public void testGetRelationsInPreviousView() {
1029
       AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
1030
       Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
1031
       assert taxon != null : "taxon cannot be null";
1032

    
1033
       List<String> propertyPaths = new ArrayList<String>();
1034
       propertyPaths.add("relatedFrom");
1035
       propertyPaths.add("relatedFrom.name");
1036

    
1037
       List<OrderHint> orderHints = new ArrayList<>();
1038
       orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
1039

    
1040
       List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
1041
               includeUnpublished, null, null, orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
1042
       assertNotNull("getRelatedTaxa should return a list",taxonRelations);
1043
       assertTrue("there should be no TaxonRelationships in the list in the prior view", taxonRelations.isEmpty());
1044
    }
1045

    
1046
    @Test
1047
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
1048
    public void testCountRelationsInPreviousView() {
1049
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
1050
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
1051
        assert taxon != null : "taxon cannot be null";
1052
        assertEquals("countRelatedTaxa should return 0 in the current view",0,
1053
                taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
1054
                        includeUnpublished, TaxonRelationship.Direction.relatedTo));
1055
    }
1056

    
1057
    @Test
1058
    @DataSet
1059
    public void testGroupTaxa() {
1060
        List<Grouping> groups = new ArrayList<>();
1061
        groups.add(new GroupByCount("count",SortOrder.DESCENDING));
1062
        groups.add(new Grouping("name.genusOrUninomial", "genus", "n", SortOrder.ASCENDING));
1063
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1064
        if(logger.isTraceEnabled()){
1065
            System.out.println("count\tname.genuOrUninomial");
1066
            for(Object[] result : results) {
1067
                System.out.println(result[0] + "\t" + result[1]);
1068
            }
1069
        }
1070
    }
1071

    
1072
    @Test
1073
    @DataSet
1074
    public void testGroupTaxaByClass() {
1075
        List<Grouping> groups = new ArrayList<>();
1076
        groups.add(new GroupByCount("count",SortOrder.DESCENDING));
1077
        groups.add(new Grouping("class", "class",null, SortOrder.ASCENDING));
1078
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1079
        if(logger.isTraceEnabled()){
1080
            System.out.println("count\tclass");
1081
            for(Object[] result : results) {
1082
                System.out.println(result[0] + "\t" + result[1]);
1083
            }
1084
        }
1085
    }
1086

    
1087
    @Test
1088
    @DataSet
1089
    public void testNativeSQLOrder() {
1090
        List<OrderHint> orderHints = new ArrayList<>();
1091
        orderHints.add(new NativeSqlOrderHint("case when {alias}.titleCache like 'C%' then 0 else 1 end",SortOrder.ASCENDING));
1092

    
1093
        @SuppressWarnings("rawtypes")
1094
        List<TaxonBase> results = taxonDao.list(null, null, orderHints);
1095
        if(logger.isTraceEnabled()){
1096
            System.out.println("native SQL order");
1097
            for(TaxonBase<?> result : results) {
1098
                System.out.println(result.getTitleCache());
1099
            }
1100
        }
1101
    }
1102

    
1103
    @Test
1104
    @DataSet
1105
    public void testGroupByDateTaxa() {
1106
        List<Grouping> groups = new ArrayList<>();
1107
        groups.add(new GroupByCount("count",null));
1108
        groups.add(new GroupByDate("created", "dateGroup", SortOrder.ASCENDING, GroupByDate.Resolution.MONTH));
1109
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1110
        if(logger.isTraceEnabled()){
1111
            System.out.println("count\tyear\tmonth");
1112
            for(Object[] result : results) {
1113
                System.out.println(result[0] + "\t" + result[1] + "\t" + result[2]);
1114
            }
1115
        }
1116
    }
1117

    
1118

    
1119

    
1120

    
1121
    @Test
1122
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
1123
    //NOTE: There is a problem with loading AuditEvents if this test runs
1124
    //stand alone or as first (one of the first) in the test suite. For some reason
1125
    //the AuditEvent records from the @DataSet are not inserted into the database then,
1126
    //while those inserted by the terms dataset are inserted as well as a completely new one.
1127
    //This problem for some reason does not happen if not running at first place
1128
    public void testGetAuditEventsByTypeWithRestrictions() {
1129
        commitAndStartNewTransaction(new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1130

    
1131
        List<String> propertyPaths = new ArrayList<>();
1132
        propertyPaths.add("name");
1133
        propertyPaths.add("createdBy");
1134
        propertyPaths.add("updatedBy");
1135

    
1136
        List<AuditCriterion> criteria = new ArrayList<>();
1137
        criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
1138

    
1139
        long count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1140

    
1141
        @SuppressWarnings("rawtypes")
1142
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, criteria,null, null, AuditEventSort.FORWARDS, propertyPaths);
1143
        assertNotNull("getAuditEvents should return a list",auditEvents);
1144
        assertFalse("the list should not be empty",auditEvents.isEmpty());
1145
        assertEquals("There should be one AuditEventRecord in the list",1, auditEvents.size());
1146
    }
1147

    
1148

    
1149
    @Test
1150
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
1151
//    @DataSets({  //for testing only
1152
//        @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml"),
1153
//        @DataSet("TaxonDaoHibernateImplTest.testFindDeletedAuditEvents.xml")
1154
//    })
1155
    //NOTE: There is a problem with loading AuditEvents if this test runs
1156
    //stand alone or as first (one of the first) in the test suite. For some reason
1157
    //the AuditEvent records from the @DataSet are not inserted into the database then,
1158
    //while those inserted by the terms dataset are inserted as well as a completely new one.
1159
    //This problem for some reason does not happen if not running at first place
1160
    public void testGetAuditEventsByTypeWithNoRestrictions() {
1161
//        printDataSet(System.out, new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1162
        commitAndStartNewTransaction(new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1163

    
1164
        List<String> propertyPaths = new ArrayList<>();
1165
        propertyPaths.add("name");
1166
        propertyPaths.add("createdBy");
1167
        propertyPaths.add("updatedBy");
1168
        long count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1169
        @SuppressWarnings("rawtypes")
1170
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, null,null, null, AuditEventSort.FORWARDS, propertyPaths);
1171
        assertNotNull("getAuditEvents should return a list", auditEvents);
1172
        assertFalse("the list should not be empty", auditEvents.isEmpty());
1173
        assertEquals("There should be thirty eight AuditEventRecords in the list", 2, auditEvents.size());
1174
    }
1175

    
1176

    
1177
    @Test
1178
    @DataSet("TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
1179
    public void testGetCommonName(){
1180
       List<Taxon> commonNameResults = taxonDao.getTaxaByCommonName("common%", null,
1181
                MatchMode.BEGINNING, null, null, null, null);
1182

    
1183
        assertNotNull("getTaxaByCommonName should return a list", commonNameResults);
1184
        assertFalse("the list should not be empty", commonNameResults.isEmpty());
1185
        assertEquals("There should be two taxa with common name", 2,commonNameResults.size());
1186

    
1187
        @SuppressWarnings("rawtypes")
1188
        List<UuidAndTitleCache<IdentifiableEntity>> list = taxonDao.getTaxaByCommonNameForEditor(
1189
                "common%", null, MatchMode.BEGINNING, null);
1190

    
1191
        assertNotNull("getTaxaByCommonName should return a list", list);
1192
        assertFalse("the list should not be empty", list.isEmpty());
1193
        assertEquals("There should be two Taxon with common name", 2,list.size());
1194

    
1195
    }
1196

    
1197
    @Test
1198
    @DataSet
1199
    public void testGetTitleCache(){
1200
        UUID uuid = UUID.fromString("7b8b5cb3-37ba-4dba-91ac-4c6ffd6ac331");
1201
        String titleCache = taxonDao.getTitleCache(uuid, false);
1202
        Assert.assertEquals("Acherontia styx Westwood, 1847 sec. cate-sphingidae.org", titleCache);
1203
        titleCache = taxonDao.getTitleCache(uuid, true);
1204
        Assert.assertEquals("Acherontia styxx Westwood, 1847 sec. cate-sphingidae.org", titleCache);
1205
   }
1206

    
1207

    
1208
    @Test
1209
    @DataSet("TaxonDaoHibernateImplTest.testPropertyPath.xml")
1210
    public void testPropertyPath(){
1211
        //Test that BeanInitializer also works on HiberanteProxys
1212
        Classification c = classificationDao.load(UUID.fromString("4bceea53-893f-4685-8c63-6dcec6e85ab1"));
1213
        TaxonNode singleNode = c.getRootNode().getChildNodes().iterator().next();
1214
        Taxon taxonProxy = singleNode.getTaxon();
1215
        Assert.assertTrue("Object to test should be a proxy ", taxonProxy instanceof HibernateProxy);
1216

    
1217
        List<String> propertyPaths = new ArrayList<>();
1218
        propertyPaths.add("taxonNodes");
1219
        Taxon taxon = (Taxon)this.taxonDao.load(
1220
                UUID.fromString("4a5bc930-844f-45ec-aea8-dd155e1ab25f"),
1221
                propertyPaths);
1222
        Assert.assertSame("Returned object should be the same proxy to assure that we ran initialization on this proxy", taxonProxy, taxon);
1223
    }
1224

    
1225

    
1226
    /**
1227
     * {@inheritDoc}
1228
     */
1229
    @Override
1230
//    @Test
1231
    public void createTestDataSet() throws FileNotFoundException {
1232
//        Classification classification  = Classification.NewInstance("Test");
1233
//        BotanicalName TaxonName = null;
1234
//        Reference sec = null;
1235
//        Taxon taxon = Taxon.NewInstance(taxonName, sec);
1236
//        classification.addChildTaxon(taxon, sec, null);
1237
//
1238
//        classificationDao.save(classification);
1239
//        this.commitAndStartNewTransaction(null);
1240
//
1241
//        writeDbUnitDataSetFile(new String[] {
1242
//                "CLASSIFICATION", "TAXONNAME",
1243
//                "REFERENCE","TAXONNODE",
1244
//                "TAXONBASE","LANGUAGESTRING",
1245
//                "HIBERNATE_SEQUENCES" // IMPORTANT!!!
1246
//                },
1247
//                "testPropertyPath" );
1248
    }
1249

    
1250
}
(3-3/5)