Project

General

Profile

Download (58.6 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 String[] TABLE_NAMES = new String[] {
110
        "HOMOTYPICALGROUP", "HOMOTYPICALGROUP_AUD", "REFERENCE", "REFERENCE_AUD", "TAXONBASE", "TAXONBASE_AUD"
111
        , "TAXONNAME", "TAXONNAME_AUD", "TAXONRELATIONSHIP", "TAXONRELATIONSHIP_AUD" };
112

    
113

    
114
    @Before
115
    public void setUp() {
116

    
117
        uuid = UUID.fromString("496b1325-be50-4b0a-9aa2-3ecd610215f2");
118
        sphingidae = UUID.fromString("54e767ee-894e-4540-a758-f906ecb4e2d9");
119
        acherontia = UUID.fromString("c5cc8674-4242-49a4-aada-72d63194f5fa");
120
        acherontiaLachesis = UUID.fromString("b04cc9cb-2b4a-4cc4-a94a-3c93a2158b06");
121
        atroposAgassiz = UUID.fromString("d75b2e3d-7394-4ada-b6a5-93175b8751c1");
122
        atroposLeach =  UUID.fromString("3da4ab34-6c50-4586-801e-732615899b07");
123
        rethera = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
124
        retheraSecCdmtest = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
125

    
126
        previousAuditEvent = new AuditEvent();
127
        previousAuditEvent.setRevisionNumber(1025);
128
        previousAuditEvent.setUuid(UUID.fromString("a680fab4-365e-4765-b49e-768f2ee30cda"));
129
        mostRecentAuditEvent = new AuditEvent();
130
        mostRecentAuditEvent.setRevisionNumber(1026);
131
        mostRecentAuditEvent.setUuid(UUID.fromString("afe8e761-8545-497b-9134-6a6791fc0b0d"));
132
        AuditEventContextHolder.clearContext(); // By default we're in the current view (i.e. view == null)
133

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

    
138
        classificationUuid = UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9");
139
        includeUnpublished = true;
140
    }
141

    
142
    @After
143
    public void tearDown() {
144
        AuditEventContextHolder.clearContext();
145
    }
146

    
147
    /**
148
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#TaxonDaoHibernateImpl()}.
149
     */
150
    @Test
151
    @DataSet
152
    public void testInit() {
153
        logger.warn("testInit()");
154
        assertNotNull("Instance of ITaxonDao expected",taxonDao);
155
        assertNotNull("Instance of IReferenceDao expected",referenceDao);
156
    }
157

    
158
    /**
159
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}.
160
     */
161
    @Test
162
    @DataSet
163
    public void testGetTaxaByName() {
164

    
165
        includeUnpublished= true;
166
        boolean accepted = true;
167

    
168
        Reference sec = referenceDao.findById(1);
169
        assert sec != null : "sec must exist";
170

    
171
        List<TaxonBase> results = taxonDao.getTaxaByName("Aus", includeUnpublished, sec);
172
        assertNotNull("getTaxaByName should return a List", results);
173
        //assertFalse("The list should not be empty", results.isEmpty());
174
        assertEquals(1, results.size());
175

    
176
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, accepted, includeUnpublished, null, null);
177
        assertNotNull("getTaxaByName should return a List", results);
178

    
179
        int numberOfTaxaByName_A = 5;
180

    
181
        //logger.setLevel(Level.DEBUG); //FIXME #######################
182
        if (logger.isDebugEnabled()) {
183
            for (int i = 0; i < results.size(); i++) {
184
                String nameCache = "";
185
                TaxonName taxonName= results.get(i).getName();
186
                nameCache = taxonName.getNameCache();
187
                logger.debug(results.get(i).getClass() + "(" + i +")" +
188
                        ": Name Cache = " + nameCache + ", Title Cache = " + results.get(i).getTitleCache());
189
            }
190
        }
191

    
192
        assertEquals(numberOfTaxaByName_A, results.size());
193

    
194
        includeUnpublished = false;
195
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, accepted, includeUnpublished, null, null);
196
        assertEquals(numberOfTaxaByName_A, results.size());  // no unpublished yet
197

    
198

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

    
201
//		assertEquals(results.get(0).getTitleCache(), "Abies sec. ???");
202
//		assertEquals(results.get(1).getTitleCache(), "Abies Mill.");
203
//		assertEquals(results.get(2).getTitleCache(), "Abies mill. sec. ???");
204
//		assertEquals(results.get(3).getTitleCache(), "Abies alba sec. ???");
205
//		assertEquals(results.get(4).getTitleCache(), "Abies alba Michx. sec. ???");
206
//		assertEquals(results.get(5).getTitleCache(), "Abies alba Mill. sec. ???");
207

    
208
        includeUnpublished = true;
209
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, accepted, includeUnpublished, null, null);
210
        assertNotNull("getTaxaByName should return a List", results);
211
        assertEquals(numberOfTaxaByName_A, results.size());
212

    
213
        results = taxonDao.getTaxaByName("Aus", MatchMode.EXACT, accepted, includeUnpublished, null, null);
214
        assertNotNull("getTaxaByName should return a List", results);
215
        assertEquals("Results list should contain one entity",1,results.size());
216
    }
217

    
218

    
219
    @Test
220
    @DataSet (loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
221
    public void testGetTaxaByNameWithMisappliedNames(){
222

    
223
        Classification classification = classificationDao.load(classificationUuid);
224

    
225
        /* NOTE:
226
         * The testdata contains 3 misapplied names (1. nameCache = Aus, 2. nameCache = Rethera, 3. nameCache = Daphnis), two contained in the classification used in this test,
227
         * the other one is not contained in any classification. This latter case is the more general situation.
228
         * Misapplied names should be found regardless of whether they are contained in a classification or not.
229
         */
230
        //two accepted taxa starting with R in classification "TestBaum"
231
        List<TaxonBase> results = taxonDao.getTaxaByName(true, false, false, false, false, "R*", classification, MatchMode.BEGINNING,
232
                null, includeUnpublished, null, null, null, null);
233
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
234

    
235
        //three taxa, 2 accepted and 1 misapplied name starting with R
236
        results = taxonDao.getTaxaByName(true, false, true, false, false, "R*", null, MatchMode.BEGINNING,
237
                null, includeUnpublished, null, null, null, null);
238
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
239

    
240
        //one synonym has no accepted taxon
241
        results = taxonDao.getTaxaByName(true, true, true, false, false, "A*", null, MatchMode.BEGINNING,
242
                null, includeUnpublished, null, null, null, null);
243
        Assert.assertEquals("There should be 11 Taxa",11, results.size());
244

    
245
        //two accepted taxa in classification and 1 misapplied name with accepted name in classification
246
        results = taxonDao.getTaxaByName(true, true, true, false, false, "R*", classification, MatchMode.BEGINNING,
247
                null, includeUnpublished, null, null, null, null);
248
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
249
        //same with unpublished
250
        includeUnpublished = false;
251
        results = taxonDao.getTaxaByName(true, true, true, false, false, "R*", classification, MatchMode.BEGINNING,
252
                null, includeUnpublished, null, null, null, null);
253
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
254
        includeUnpublished = true;
255

    
256

    
257
        //same as above because all taxa, synonyms and misapplied names starting with R are in the classification
258
        results = taxonDao.getTaxaByName(true, true, true, false, false, "R*", null, MatchMode.BEGINNING,
259
                null, includeUnpublished, null, null, null, null);
260
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
261

    
262
        //find misapplied names with accepted taxon in the classification, the accepted taxa of two misapplied names are in the classification
263
        results = taxonDao.getTaxaByName(false, false, true, false, false, "*", classification, MatchMode.BEGINNING,
264
                null, includeUnpublished, null, null, null, null);
265
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
266

    
267
        //find misapplied names beginning with R
268
        results = taxonDao.getTaxaByName(false, false, true, false, false, "R*", null, MatchMode.BEGINNING,
269
                null, includeUnpublished, null, null, null, null);
270
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
271

    
272
        //find all three misapplied names
273
        results = taxonDao.getTaxaByName(false, false, true, false, false, "*", null, MatchMode.BEGINNING,
274
                null, includeUnpublished, null, null, null, null);
275
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
276

    
277
    }
278
    /**
279
     * Test for all not covered possibilities of searches
280
     */
281
    @Test
282
    @DataSet (loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
283
    public void testGetTaxaByNameVariants(){
284
        List<TaxonBase> results = taxonDao.getTaxaByName(false, false, false, true, false, "c*", null, MatchMode.BEGINNING,
285
                null, includeUnpublished, null, null, null, null);
286
        Assert.assertEquals("There should be 2 Taxa",2, results.size());
287

    
288
        results = taxonDao.getTaxaByName(false, false, true, true, false, "R*", null, MatchMode.BEGINNING,
289
                null, includeUnpublished, null, null, null, null);
290
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
291

    
292
        results = taxonDao.getTaxaByName(false, true, true, true, false, "R*", null, MatchMode.BEGINNING,
293
                null, includeUnpublished, null, null, null, null);
294
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
295

    
296
        results = taxonDao.getTaxaByName(false, true, false, true, false, "c*", null, MatchMode.BEGINNING,
297
                null, includeUnpublished, null, null, null, null);
298
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
299

    
300
        results = taxonDao.getTaxaByName(true, false, false, true, false, "c*", null, MatchMode.BEGINNING,
301
                null, includeUnpublished, null, null, null, null);
302
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
303
        Classification classification = classificationDao.load(classificationUuid);
304
        results = taxonDao.getTaxaByName(false, false, false, true, false, "c*", classification, MatchMode.BEGINNING,
305
                null, includeUnpublished, null, null, null, null);
306
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
307
        Set<NamedArea> namedAreas = new HashSet<>();
308
        namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
309
        results = taxonDao.getTaxaByName(false, false, false, true, false, "c*", null, MatchMode.BEGINNING,
310
                namedAreas, includeUnpublished, null, null, null, null);
311
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
312
    }
313

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

    
323
        List<UuidAndTitleCache<IdentifiableEntity>> results = taxonDao.getTaxaByNameForEditor(true, true, false,false, false, includeUnpublished, "Acher", null, MatchMode.BEGINNING, null, null);
324
        assertNotNull("getTaxaByName should return a List", results);
325
        assertFalse("The list should not be empty", results.isEmpty());
326
        assertEquals(4, results.size());
327

    
328

    
329
        results = taxonDao.getTaxaByNameForEditor(true, true, false, false,false,includeUnpublished, "A",null, MatchMode.BEGINNING, null, null);
330
        assertNotNull("getTaxaByName should return a List", results);
331
        assertEquals(7, results.size());
332

    
333

    
334
        results = taxonDao.getTaxaByNameForEditor(true, false,false, false,false, includeUnpublished, "A", null,MatchMode.BEGINNING, null, null);
335
        assertNotNull("getTaxaByName should return a List", results);
336
        assertEquals(5, results.size());
337
        assertEquals(results.get(0).getType(), Taxon.class);
338

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

    
344
        results = taxonDao.getTaxaByNameForEditor(true, true,false,false,false,includeUnpublished, "Aus", null,MatchMode.EXACT,  null, null);
345
        assertNotNull("getTaxaByName should return a List", results);
346
        assertEquals("Results list should contain one entity",1,results.size());
347

    
348
        results = taxonDao.getTaxaByNameForEditor(true, true,true,false,false,includeUnpublished, "A", null,MatchMode.BEGINNING,  null, null);
349
        assertNotNull("getTaxaByName should return a List", results);
350
        assertEquals("Results list should contain one entity", 8, results.size());
351

    
352
        //TODO: test the search for misapplied names
353

    
354
    }
355

    
356

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

    
365
        Set<NamedArea> namedAreas = new HashSet<>();
366
        namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
367
        //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
368
        //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
369

    
370
        Classification taxonmicTree = classificationDao.findByUuid(classificationUuid);
371

    
372
        // prepare some synonym relation ships for some tests
373
        Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
374
        Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
375
        taxonRethera.addSynonym(synAtroposAgassiz, SynonymType.SYNONYM_OF());
376
        logger.warn("addSynonym(..)");
377

    
378
        Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
379
        Taxon taxonRetheraSecCdmtest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
380
        taxonRetheraSecCdmtest.addSynonym(synAtroposLeach, SynonymType.SYNONYM_OF());
381
        this.taxonDao.save(taxonRetheraSecCdmtest);
382

    
383
        Taxon test = (Taxon)this.taxonDao.findByUuid(retheraSecCdmtest);
384
//        Set<Synonym> synonyms3 = test.getSynonyms();
385
        // 1. searching for a taxon (Rethera)
386
        //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
387

    
388
        List<TaxonBase> results = taxonDao.getTaxaByName(true,false, false, false, false,"Rethera", null, MatchMode.BEGINNING, namedAreas,
389
                includeUnpublished, null, null, null, null);
390
        assertNotNull("getTaxaByName should return a List", results);
391
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
392

    
393
        results = taxonDao.getTaxaByName(false,false, false, true, false, "com*", null, MatchMode.BEGINNING, namedAreas,
394
                includeUnpublished, null, null, null, null);
395
            assertNotNull("getTaxaByName should return a List", results);
396
            assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
397

    
398
        // 2. searching for a taxon (Rethera) contained in a specific classification
399
        results = taxonDao.getTaxaByName(true, false, false, false, false, "Rethera", taxonmicTree, MatchMode.BEGINNING, namedAreas,
400
                includeUnpublished, null, 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, false, false, "Atropo", null, MatchMode.ANYWHERE, null,
407
                includeUnpublished, null, 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, false, false,"Atropo", null, MatchMode.BEGINNING, null,
418
                includeUnpublished, null, 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
        results = taxonDao.getTaxaByName(true, true, false, false, false,"A", null, MatchMode.BEGINNING, namedAreas,
425
                includeUnpublished, null, null, null, null);
426
        //only five taxa have a distribution
427
        assertNotNull("getTaxaByName should return a List", results);
428
        assertTrue("expected to find 8 taxa but found "+results.size(), results.size() == 8);
429
    }
430

    
431

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

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

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

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

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

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

    
471

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

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

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

    
485

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

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

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

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

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

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

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

    
544
    @Test
545
    @DataSet
546
    public void testCountTaxaByName() {
547
        long numberOfTaxa = taxonDao.countTaxaByName(true, false, false, false,false, "A", null, MatchMode.BEGINNING, null, includeUnpublished);
548
        assertEquals(5, numberOfTaxa);
549
        numberOfTaxa = taxonDao.countTaxaByName(true, false, false, false, false,"Smerinthus kindermannii", null, MatchMode.EXACT, null, includeUnpublished);
550
        assertEquals(1, numberOfTaxa);
551
        numberOfTaxa = taxonDao.countTaxaByName(false, true, false, false, false,"A", null, MatchMode.BEGINNING, null, includeUnpublished);
552
        assertEquals(2, numberOfTaxa);
553
        numberOfTaxa = taxonDao.countTaxaByName(true, true, false, false, false,"A", null, MatchMode.BEGINNING, null, includeUnpublished);
554
        assertEquals(7, numberOfTaxa);
555
        numberOfTaxa = taxonDao.countTaxaByName(true, true, false, false,false, "Aasfwerfwf fffe", null, MatchMode.BEGINNING, null, includeUnpublished);
556
        assertEquals(0, numberOfTaxa);
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<>();
570
        propertyPaths.add("fromTaxon");
571
        propertyPaths.add("fromTaxon.name");
572
        List<OrderHint> orderHints = new ArrayList<>();
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
        long count = taxonDao.countTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
578
                includeUnpublished, TaxonRelationship.Direction.relatedTo);
579
        assertEquals("Count should return 8 (related taxa)", 8, count);
580

    
581
        List<TaxonRelationship> relatedTaxa = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
582
                includeUnpublished, null, null, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
583
        assertNotNull("getRelatedTaxa should return a List",relatedTaxa);
584
        assertEquals("getRelatedTaxa should return all 8 related taxa", 8, relatedTaxa.size());
585
        assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon()));
586
        assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon().getName()));
587

    
588
        assertEquals("Acherontia should appear first in the list of related taxa", relatedTaxa.get(0).getFromTaxon().getTitleCache(), "Acherontia Laspeyres, 1809 sec. cate-sphingidae.org");
589
        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());
590
    }
591

    
592
    @Test
593
    @DataSet
594
    public void testGetRelatedTaxaPaged()	{
595
        Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
596
        assert taxon != null : "taxon must exist";
597

    
598
        List<String> propertyPaths = new ArrayList<>();
599
        propertyPaths.add("fromTaxon");
600
        propertyPaths.add("fromTaxon.name");
601

    
602
        List<OrderHint> orderHints = new ArrayList<>();
603
        orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
604

    
605
        int pageSize = 3;
606
        List<TaxonRelationship> firstPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
607
                includeUnpublished, pageSize, 0, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
608
        List<TaxonRelationship> secondPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
609
                includeUnpublished, pageSize, 1, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
610
        List<TaxonRelationship> thirdPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
611
                includeUnpublished, pageSize, 2, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
612

    
613
        assertNotNull("getRelatedTaxa: 3, 0 should return a List",firstPage);
614
        assertEquals("getRelatedTaxa: 3, 0 should return a List with 3 elements", pageSize,firstPage.size());
615
        assertNotNull("getRelatedTaxa: 3, 1 should return a List",secondPage);
616
        assertEquals("getRelatedTaxa: 3, 1 should return a List with 3 elements", pageSize, secondPage.size());
617
        assertNotNull("getRelatedTaxa: 3, 2 should return a List",thirdPage);
618
        assertEquals("getRelatedTaxa: 3, 2 should return a List with 2 elements", 2, thirdPage.size());
619
    }
620

    
621
    @Test
622
    @DataSet
623
    public void testCountSynonyms() {
624
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
625
        assert taxon != null : "taxon must exist";
626

    
627
        long numberOfRelatedSynonym = taxonDao.countSynonyms(taxon,null);
628
        assertEquals("countSynonyms should return 3", 3, numberOfRelatedSynonym);
629
    }
630

    
631
    @Test
632
    @DataSet
633
    public void testGetSynonyms()	{
634
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
635
        assert taxon != null : "taxon must exist";
636
        List<String> propertyPaths = new ArrayList<String>();
637
        propertyPaths.add("synonym");
638
        propertyPaths.add("synonym.name");
639

    
640
        List<OrderHint> orderHints = new ArrayList<>();
641
        orderHints.add(new OrderHint("titleCache", SortOrder.ASCENDING));
642

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

    
645
        assertNotNull("getSynonyms should return a List", synonyms);
646
        assertEquals("getSynonyms should return 3 synonyms", 3, synonyms.size());
647
        assertTrue("getSynonyms should return synonym objects with the synonym initialized", Hibernate.isInitialized(synonyms.get(0)));
648
    }
649

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

    
656
        long numberOfTaxonomicSynonyms = taxonDao.countSynonyms(taxon, SynonymType.HETEROTYPIC_SYNONYM_OF());
657
        assertEquals("countSynonyms should return 4", 3, numberOfTaxonomicSynonyms);
658
    }
659

    
660
    @Test
661
    @DataSet
662
    public void testSynonymsByType() {
663
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
664
        assert taxon != null : "taxon must exist";
665

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

    
668
        assertNotNull("getSynonyms should return a List", synonyms);
669
        assertEquals("getSynonyms should return 4 Synonyms", 3, synonyms.size());
670
    }
671

    
672
    @Test
673
    @DataSet
674
    public void testPageSynonyms(){
675
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
676
        assert taxon != null : "taxon must exist";
677

    
678
        int pageSize = 2;
679
        List<Synonym> firstPage = taxonDao.getSynonyms(taxon, null, pageSize, 0,null,null);
680
        List<Synonym> secondPage = taxonDao.getSynonyms(taxon, null, pageSize, 1,null,null);
681

    
682
        assertNotNull("getSynonyms: 2, 0 should return a List",firstPage);
683
        assertEquals("getSynonyms: 2, 0 should return 2 synonyms", pageSize,firstPage.size());
684
        assertNotNull("getSynonyms: 2, 1 should return a List",secondPage);
685
        assertEquals("getSynonyms: 2, 1 should return 1 synonym", 1, secondPage.size());
686
    }
687

    
688
    @Test
689
    @DataSet
690
    public void testCountTaxonRelationships() {
691
        long count = taxonDao.countTaxonRelationships(null);
692
        assertEquals("There should be 11 relationships", 11, count);
693

    
694
        Set<TaxonRelationshipType> types = new HashSet<>();
695
        count = taxonDao.countTaxonRelationships(types);
696
        assertEquals("Empty filter should return empty result", 0, count);
697

    
698
        types.add(TaxonRelationshipType.CONGRUENT_TO());
699
        count = taxonDao.countTaxonRelationships(types);
700
        assertEquals("There should be no congruent relationship", 0, count);
701

    
702
        types.add(TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN());
703
        count = taxonDao.countTaxonRelationships(types);
704
        assertEquals("There should be 11 tax included relationships", 11, count);
705
    }
706

    
707
    @Test
708
    @DataSet
709
    public void testlistTaxonRelationships() {
710
        List<TaxonRelationship> rels = taxonDao.getTaxonRelationships(null, null, null, null, null);
711
        assertEquals("There should be 11 relationships", 11, rels.size());
712

    
713
        rels = taxonDao.getTaxonRelationships(null, 2, 3, null, null);
714
        assertEquals("There should be 11 relationships", 2, rels.size());
715

    
716
        Set<TaxonRelationshipType> types = new HashSet<>();
717
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
718
        assertEquals("Empty filter should return empty result", 0, rels.size());
719

    
720
        types.add(TaxonRelationshipType.CONGRUENT_TO());
721
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
722
        assertEquals("There should be no congruent relationship", 0, rels.size());
723

    
724
        types.add(TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN());
725
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
726
        assertEquals("There should be 11 tax included relationships", 11, rels.size());
727
    }
728

    
729
    @Test
730
    @DataSet("TaxonNodeDaoHibernateImplTest.xml")
731
    public void testListAcceptedTaxaFor()  {
732
        UUID acheontitia_ciprosus = UUID.fromString("3ef145f7-bd92-4a64-8afd-2b8203e00e02");
733

    
734
        Synonym synonym = (Synonym)taxonDao.findByUuid(acheontitia_ciprosus);
735
        assertNotNull("synonym must exist", synonym);
736

    
737
        Taxon taxon = taxonDao.acceptedTaxonFor(synonym, null, null);
738
        assertNotNull("listAcceptedTaxaFor should return a taxon", taxon);
739

    
740
        Classification classification = classificationDao.load(classificationUuid);
741
        assertNotNull("classification must exist", classification);
742

    
743
        taxon = taxonDao.acceptedTaxonFor(synonym, classification, null);
744
        assertNull("listAcceptedTaxaFor should return not taxon due to classification filter", taxon);
745
    }
746

    
747

    
748
    @Test
749
    @DataSet
750
    public void testGetTaxonMatchingUninomial() {
751
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class, "Smerinthus", "*", "*", "*","*",null,null,null);
752

    
753
        assertNotNull("findTaxaByName should return a List", result);
754
        assertEquals("findTaxaByName should return two Taxa",2,result.size());
755
        assertEquals("findTaxaByName should return a Taxon with id 5",5,result.get(0).getId());
756
    }
757

    
758
    @Test
759
    @DataSet
760
    public void testGetTaxonMatchingSpeciesBinomial() {
761
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class, "Smerinthus", null, "kindermannii", null,"*",null,null,null);
762

    
763
        assertNotNull("findTaxaByName should return a List", result);
764
        assertEquals("findTaxaByName should return one Taxon",1,result.size());
765
        assertEquals("findTaxaByName should return a Taxon with id 8",8,result.get(0).getId());
766
    }
767

    
768
    @Test
769
    @DataSet
770
    public void testGetTaxonMatchingTrinomial() {
771
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Cryptocoryne", null,"purpurea","borneoensis","*",null,null,null);
772

    
773
        assertNotNull("findTaxaByName should return a List", result);
774
        assertEquals("findTaxaByName should return one Taxon",1,result.size());
775
        assertEquals("findTaxaByName should return a Taxon with id 38",38,result.get(0).getId());
776
    }
777

    
778
    @Test
779
    @DataSet
780
    public void testNegativeMatch() {
781
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Acherontia", null,"atropos","dehli",null,null,null,null);
782

    
783
        assertNotNull("findTaxaByName should return a List", result);
784
        assertTrue("findTaxaByName should return an empty List",result.isEmpty());
785
    }
786

    
787
    @Test
788
    @DataSet
789
    public void testCountAllTaxa() {
790
        long numberOfTaxa = taxonDao.count(Taxon.class);
791
        assertEquals("count should return 14 taxa", 14, numberOfTaxa);
792
    }
793

    
794
    @Test
795
    @DataSet
796
    public void testListAllTaxa() {
797
        List<Taxon> taxa = taxonDao.list(Taxon.class,100, 0);
798
        assertNotNull("list should return a List", taxa);
799
        assertEquals("list should return 14 taxa", 14, taxa.size());
800
    }
801

    
802
    @Test
803
    @DataSet
804
   // @ExpectedDataSet
805
    public void testDelete() {
806
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
807
        assert taxon != null : "taxon must exist";
808
        taxonDao.delete(taxon);
809
        taxon = (Taxon)taxonDao.findByUuid(acherontia);
810
        assert taxon == null : "taxon must not exist";
811
        setComplete();
812
        endTransaction();
813
//        try {
814
//            printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
815
//        } catch (FileNotFoundException e) {
816
//            e.printStackTrace();
817
//        }
818
    }
819

    
820
    @Test
821
    @DataSet
822
    @ExpectedDataSet("TaxonDaoHibernateImplTest.testDelete-result.xml")
823
    public void testDeleteWithMarker() {
824
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
825
        taxon.addMarker(Marker.NewInstance(MarkerType.IS_DOUBTFUL(), true));
826
        taxonDao.save(taxon);
827
        assert taxon != null : "taxon must exist";
828

    
829
        taxonDao.delete(taxon);
830
        commitAndStartNewTransaction(null);
831
        taxon = (Taxon)taxonDao.findByUuid(acherontia);
832
        assert taxon == null : "taxon must not exist";
833
        setComplete();
834
        endTransaction();
835
//        try {
836
//            printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
837
//        } catch (FileNotFoundException e) {
838
//            e.printStackTrace();
839
//        }
840
    }
841

    
842
    @Test
843
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
844
    public void testFindDeleted() {
845
        TaxonBase<?> taxon = taxonDao.findByUuid(acherontia);
846
        assertNull("findByUuid should return null in this view", taxon);
847
        assertFalse("exist should return false in this view",taxonDao.exists(acherontia));
848
    }
849

    
850
    @Test
851
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
852
    public void testFindDeletedInPreviousView() {
853
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
854
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
855
        assertNotNull("findByUuid should return a taxon in this view",taxon);
856
        assertTrue("exists should return true in this view", taxonDao.exists(acherontia));
857

    
858
        try{
859
            assertEquals("There should be 3 relations to this taxon in this view",3,taxon.getRelationsToThisTaxon().size());
860
        } catch(Exception e) {
861
            fail("We should not experience any problems initializing proxies with envers");
862
        }
863
    }
864

    
865
    @Test
866
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
867
    public void testGetAuditEvents() {
868
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
869
        assert taxon != null : "taxon cannot be null";
870

    
871
        List<String> propertyPaths = new ArrayList<>();
872
        propertyPaths.add("name");
873
        propertyPaths.add("createdBy");
874
        propertyPaths.add("updatedBy");
875

    
876
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,null,propertyPaths);
877
        assertNotNull("getAuditEvents should return a list",auditEvents);
878
        assertFalse("the list should not be empty",auditEvents.isEmpty());
879
        assertEquals("There should be two AuditEventRecords in the list",2, auditEvents.size());
880
    }
881

    
882
    @Test
883
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
884
    public void testGetAuditEventsFromNow() {
885
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
886
        TaxonBase<?> taxon =  taxonDao.findByUuid(sphingidae);
887
        assert taxon != null : "taxon cannot be null";
888

    
889
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,AuditEventSort.FORWARDS,null);
890
        assertNotNull("getAuditEvents should return a list",auditEvents);
891
        assertFalse("the list should not be empty",auditEvents.isEmpty());
892
        assertEquals("There should be one audit event in the list",1,auditEvents.size());
893
    }
894

    
895
    @Test
896
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
897
    public void testCountAuditEvents() {
898
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
899
        assert taxon != null : "taxon cannot be null";
900

    
901
        long numberOfAuditEvents = taxonDao.countAuditEvents(taxon, null);
902
        assertEquals("countAuditEvents should return 2",numberOfAuditEvents,2);
903
    }
904

    
905
    @Test
906
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
907
    public void getPreviousAuditEvent() {
908
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
909
        assert taxon != null : "taxon cannot be null";
910

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

    
915
    @Test
916
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
917
    public void getPreviousAuditEventAtBeginning() {
918
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
919
        TaxonBase taxon = taxonDao.findByUuid(sphingidae);
920
        assert taxon != null : "taxon cannot be null";
921

    
922
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getPreviousAuditEvent(taxon);
923
        assertNull("getPreviousAuditEvent should return null if we're at the first audit event anyway",auditEvent);
924
    }
925

    
926
    @Test
927
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
928
    public void getNextAuditEvent() {
929
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
930
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
931
        assert taxon != null : "taxon cannot be null";
932

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

    
937
    @Test
938
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
939
    public void getNextAuditEventAtEnd() {
940
        AuditEventContextHolder.getContext().setAuditEvent(mostRecentAuditEvent);
941
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
942
        assert taxon != null : "taxon cannot be null";
943

    
944
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getNextAuditEvent(taxon);
945
        assertNull("getNextAuditEvent should return null as there no more audit events after the current one",auditEvent);
946
    }
947

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

    
954
       assertEquals("getRelationsToThisTaxon should contain 1 TaxonRelationship in this view",1,taxon.getRelationsToThisTaxon().size());
955
    }
956

    
957
    @Test
958
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
959
    public void testFindInPreviousView() {
960
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
961
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
962
        assert taxon != null : "taxon cannot be null";
963

    
964
        assertTrue("getRelationsToThisTaxon should contain 0 TaxonRelationship in this view",taxon.getRelationsToThisTaxon().isEmpty());
965
    }
966

    
967
    @Test
968
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
969
    public void testGetRelations() {
970
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
971
        assert taxon != null : "taxon cannot be null";
972

    
973
        List<String> propertyPaths = new ArrayList<>();
974
         propertyPaths.add("fromTaxon");
975
         propertyPaths.add("fromTaxon.name");
976

    
977
         List<OrderHint> orderHints = new ArrayList<>();
978
         orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
979

    
980
        List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
981
                includeUnpublished, null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
982
        assertNotNull("getRelatedTaxa should return a list", taxonRelations);
983
        assertEquals("there should be one TaxonRelationship in the list in the current view",1,taxonRelations.size());
984
        assertTrue("TaxonRelationship.relatedFrom should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon()));
985
        assertTrue("TaxonRelationship.relatedFrom.name should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon().getName()));
986
    }
987

    
988
    @Test
989
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
990
    public void testCountRelations() {
991
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
992
        assert taxon != null : "taxon cannot be null";
993
        assertEquals("countRelatedTaxa should return 1 in the current view",1, taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
994
                includeUnpublished, TaxonRelationship.Direction.relatedTo));
995
    }
996

    
997
    @Test
998
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
999
    public void testGetRelationsInPreviousView() {
1000
       AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
1001
       Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
1002
       assert taxon != null : "taxon cannot be null";
1003

    
1004
       List<String> propertyPaths = new ArrayList<String>();
1005
       propertyPaths.add("relatedFrom");
1006
       propertyPaths.add("relatedFrom.name");
1007

    
1008
       List<OrderHint> orderHints = new ArrayList<>();
1009
       orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
1010

    
1011
       List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),
1012
               includeUnpublished, null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
1013
       assertNotNull("getRelatedTaxa should return a list",taxonRelations);
1014
       assertTrue("there should be no TaxonRelationships in the list in the prior view",taxonRelations.isEmpty());
1015
    }
1016

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

    
1028
    @Test
1029
    @DataSet
1030
    public void testGroupTaxa() {
1031
        List<Grouping> groups = new ArrayList<>();
1032
        groups.add(new GroupByCount("count",SortOrder.DESCENDING));
1033
        groups.add(new Grouping("name.genusOrUninomial", "genus", "n", SortOrder.ASCENDING));
1034
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1035
        if(logger.isTraceEnabled()){
1036
            System.out.println("count\tname.genuOrUninomial");
1037
            for(Object[] result : results) {
1038
                System.out.println(result[0] + "\t" + result[1]);
1039
            }
1040
        }
1041
    }
1042

    
1043
    @Test
1044
    @DataSet
1045
    public void testGroupTaxaByClass() {
1046
        List<Grouping> groups = new ArrayList<>();
1047
        groups.add(new GroupByCount("count",SortOrder.DESCENDING));
1048
        groups.add(new Grouping("class", "class",null, SortOrder.ASCENDING));
1049
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1050
        if(logger.isTraceEnabled()){
1051
            System.out.println("count\tclass");
1052
            for(Object[] result : results) {
1053
                System.out.println(result[0] + "\t" + result[1]);
1054
            }
1055
        }
1056
    }
1057

    
1058
    @Test
1059
    @DataSet
1060
    public void testNativeSQLOrder() {
1061
        List<OrderHint> orderHints = new ArrayList<>();
1062
        orderHints.add(new NativeSqlOrderHint("case when {alias}.titleCache like 'C%' then 0 else 1 end",SortOrder.ASCENDING));
1063

    
1064
        List<TaxonBase> results = taxonDao.list(null, null, orderHints);
1065
        if(logger.isTraceEnabled()){
1066
            System.out.println("native SQL order");
1067
            for(TaxonBase<?> result : results) {
1068
                System.out.println(result.getTitleCache());
1069
            }
1070
        }
1071
    }
1072

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

    
1088

    
1089

    
1090

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

    
1101
        List<String> propertyPaths = new ArrayList<>();
1102
        propertyPaths.add("name");
1103
        propertyPaths.add("createdBy");
1104
        propertyPaths.add("updatedBy");
1105

    
1106
        List<AuditCriterion> criteria = new ArrayList<>();
1107
        criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
1108

    
1109
        long count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1110

    
1111
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, criteria,null, null, AuditEventSort.FORWARDS, propertyPaths);
1112
        assertNotNull("getAuditEvents should return a list",auditEvents);
1113
        assertFalse("the list should not be empty",auditEvents.isEmpty());
1114
        assertEquals("There should be one AuditEventRecord in the list",1, auditEvents.size());
1115
    }
1116

    
1117

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

    
1133
        List<String> propertyPaths = new ArrayList<>();
1134
        propertyPaths.add("name");
1135
        propertyPaths.add("createdBy");
1136
        propertyPaths.add("updatedBy");
1137
        long count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1138
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, null,null, null, AuditEventSort.FORWARDS, propertyPaths);
1139
        assertNotNull("getAuditEvents should return a list", auditEvents);
1140
        assertFalse("the list should not be empty", auditEvents.isEmpty());
1141
        assertEquals("There should be thirty eight AuditEventRecords in the list", 2, auditEvents.size());
1142
    }
1143

    
1144

    
1145
    @Test
1146
    @DataSet("TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
1147
    public void testGetCommonName(){
1148
       List<Taxon> commonNameResults = taxonDao.getTaxaByCommonName("common%", null,
1149
                MatchMode.BEGINNING, null, null, null, null);
1150

    
1151
        assertNotNull("getTaxaByCommonName should return a list", commonNameResults);
1152
        assertFalse("the list should not be empty", commonNameResults.isEmpty());
1153
        assertEquals("There should be two taxa with common name", 2,commonNameResults.size());
1154

    
1155
        List<UuidAndTitleCache<IdentifiableEntity>> list = taxonDao.getTaxaByCommonNameForEditor("common%", null, MatchMode.BEGINNING, null);
1156

    
1157
        assertNotNull("getTaxaByCommonName should return a list", commonNameResults);
1158
        assertFalse("the list should not be empty", commonNameResults.isEmpty());
1159
        assertEquals("There should be two Taxon with common name", 2,commonNameResults.size());
1160

    
1161
    }
1162

    
1163
    @Test
1164
    @DataSet
1165
    public void testGetTitleCache(){
1166
        UUID uuid = UUID.fromString("7b8b5cb3-37ba-4dba-91ac-4c6ffd6ac331");
1167
        String titleCache = taxonDao.getTitleCache(uuid, false);
1168
        Assert.assertEquals("Acherontia styx Westwood, 1847 sec. cate-sphingidae.org", titleCache);
1169
        titleCache = taxonDao.getTitleCache(uuid, true);
1170
        Assert.assertEquals("Acherontia styxx Westwood, 1847 sec. cate-sphingidae.org", titleCache);
1171
   }
1172

    
1173

    
1174
    @Test
1175
    @DataSet("TaxonDaoHibernateImplTest.testPropertyPath.xml")
1176
    public void testPropertyPath(){
1177
        //Test that BeanInitializer also works on HiberanteProxys
1178
        Classification c = classificationDao.load(UUID.fromString("4bceea53-893f-4685-8c63-6dcec6e85ab1"));
1179
        TaxonNode singleNode = c.getRootNode().getChildNodes().iterator().next();
1180
        Taxon taxonProxy = singleNode.getTaxon();
1181
        Assert.assertTrue("Object to test should be a proxy ", taxonProxy instanceof HibernateProxy);
1182

    
1183
        List<String> propertyPaths = new ArrayList<>();
1184
        propertyPaths.add("taxonNodes");
1185
        Taxon taxon = (Taxon)this.taxonDao.load(
1186
                UUID.fromString("4a5bc930-844f-45ec-aea8-dd155e1ab25f"),
1187
                propertyPaths);
1188
        Assert.assertSame("Returned object should be the same proxy to assure that we ran initialization on this proxy", taxonProxy, taxon);
1189
    }
1190

    
1191

    
1192
    /**
1193
     * {@inheritDoc}
1194
     */
1195
    @Override
1196
//    @Test
1197
    public void createTestDataSet() throws FileNotFoundException {
1198
//        Classification classification  = Classification.NewInstance("Test");
1199
//        BotanicalName TaxonName = null;
1200
//        Reference sec = null;
1201
//        Taxon taxon = Taxon.NewInstance(taxonName, sec);
1202
//        classification.addChildTaxon(taxon, sec, null);
1203
//
1204
//        classificationDao.save(classification);
1205
//        this.commitAndStartNewTransaction(null);
1206
//
1207
//        writeDbUnitDataSetFile(new String[] {
1208
//                "CLASSIFICATION", "TAXONNAME",
1209
//                "REFERENCE","TAXONNODE",
1210
//                "TAXONBASE","LANGUAGESTRING",
1211
//                "HIBERNATE_SEQUENCES" // IMPORTANT!!!
1212
//                },
1213
//                "testPropertyPath" );
1214
    }
1215

    
1216
}
(3-3/5)