Project

General

Profile

Download (57.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.apache.log4j.Level;
27
import org.hibernate.Hibernate;
28
import org.hibernate.envers.query.AuditEntity;
29
import org.hibernate.envers.query.criteria.AuditCriterion;
30
import org.hibernate.proxy.HibernateProxy;
31
import org.junit.After;
32
import org.junit.Assert;
33
import org.junit.Before;
34
import org.junit.Test;
35
import org.unitils.dbunit.annotation.DataSet;
36
import org.unitils.dbunit.annotation.ExpectedDataSet;
37
import org.unitils.spring.annotation.SpringBeanByType;
38

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

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

    
78
    @SpringBeanByType
79
    private ITaxonDao taxonDao;
80

    
81
    @SpringBeanByType
82
    private IClassificationDao classificationDao;
83

    
84
    @SpringBeanByType
85
    private IReferenceDao referenceDao;
86

    
87
    @SpringBeanByType
88
    IDefinedTermDao definedTermDao;
89

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

    
99
    private AuditEvent previousAuditEvent;
100
    private AuditEvent mostRecentAuditEvent;
101

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

    
106
    private UUID classificationUuid;
107

    
108
    private static final String[] TABLE_NAMES = new String[] {
109
        "HOMOTYPICALGROUP", "HOMOTYPICALGROUP_AUD", "REFERENCE", "REFERENCE_AUD", "TAXONBASE", "TAXONBASE_AUD"
110
        , "TAXONNAME", "TAXONNAME_AUD", "TAXONRELATIONSHIP", "TAXONRELATIONSHIP_AUD" };
111

    
112

    
113
    @Before
114
    public void setUp() {
115

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

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

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

    
137
        classificationUuid = UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9");
138
    }
139

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

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

    
156
    /**
157
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}.
158
     */
159
    @Test
160
    @DataSet
161
    public void testGetTaxaByName() {
162
        Reference sec = referenceDao.findById(1);
163
        assert sec != null : "sec must exist";
164

    
165
        List<TaxonBase> results = taxonDao.getTaxaByName("Aus", sec);
166
        assertNotNull("getTaxaByName should return a List", results);
167
        //assertFalse("The list should not be empty", results.isEmpty());
168
        assertEquals(1, results.size());
169

    
170
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, true, null, null);
171
        assertNotNull("getTaxaByName should return a List", results);
172

    
173
        int numberOfTaxaByName_A = 5;
174

    
175
        logger.setLevel(Level.DEBUG); //FIXME #######################
176
        if (logger.isDebugEnabled()) {
177
            for (int i = 0; i < results.size(); i++) {
178
                String nameCache = "";
179
                TaxonName taxonName= results.get(i).getName();
180
                nameCache = taxonName.getNameCache();
181
                logger.debug(results.get(i).getClass() + "(" + i +")" +
182
                        ": Name Cache = " + nameCache + ", Title Cache = " + results.get(i).getTitleCache());
183
            }
184
        }
185

    
186
        assertEquals(numberOfTaxaByName_A, results.size());
187

    
188

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

    
191
//		assertEquals(results.get(0).getTitleCache(), "Abies sec. ???");
192
//		assertEquals(results.get(1).getTitleCache(), "Abies Mill.");
193
//		assertEquals(results.get(2).getTitleCache(), "Abies mill. sec. ???");
194
//		assertEquals(results.get(3).getTitleCache(), "Abies alba sec. ???");
195
//		assertEquals(results.get(4).getTitleCache(), "Abies alba Michx. sec. ???");
196
//		assertEquals(results.get(5).getTitleCache(), "Abies alba Mill. sec. ???");
197

    
198
        results = taxonDao.getTaxaByName("A*", MatchMode.BEGINNING, true, null, null);
199
        assertNotNull("getTaxaByName should return a List", results);
200
        assertEquals(numberOfTaxaByName_A, results.size());
201

    
202
        results = taxonDao.getTaxaByName("Aus", MatchMode.EXACT, true, null, null);
203
        assertNotNull("getTaxaByName should return a List", results);
204
        assertEquals("Results list should contain one entity",1,results.size());
205
    }
206

    
207

    
208
    @Test
209
    @DataSet (loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
210
    public void testGetTaxaByNameWithMisappliedNames(){
211

    
212
        Classification classification = classificationDao.load(classificationUuid);
213

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

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

    
227
        //one synonym has no accepted taxon
228
        results = taxonDao.getTaxaByName(true, true, true, false, false, "A*", null, MatchMode.BEGINNING, null, null, null, null, null);
229
        Assert.assertEquals("There should be 11 Taxa",11, results.size());
230

    
231
        //two accepted taxa in classification and 1 misapplied name with accepted name in classification
232
        results = taxonDao.getTaxaByName(true, true, true, false, false, "R*", classification, MatchMode.BEGINNING, null, null, null, null, null);
233
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
234

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

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

    
243
        //find misapplied names beginning with R
244
        results = taxonDao.getTaxaByName(false, false, true, false, false, "R*", null, MatchMode.BEGINNING, null, null, null, null, null);
245
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
246

    
247
        //find all three misapplied names
248
        results = taxonDao.getTaxaByName(false, false, true, false, false, "*", null, MatchMode.BEGINNING, null, null, null, null, null);
249
        Assert.assertEquals("There should be 3 Taxa", 3, results.size());
250

    
251
    }
252
    /**
253
     * Test for all not covered possibilities of searches
254
     */
255
    @Test
256
    @DataSet (loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
257
    public void testGetTaxaByNameVariants(){
258
        List<TaxonBase> results = taxonDao.getTaxaByName(false, false, false, true, false, "c*", null, MatchMode.BEGINNING, null, null, null, null, null);
259
        Assert.assertEquals("There should be 2 Taxa",2, results.size());
260

    
261
        results = taxonDao.getTaxaByName(false, false, true, true, false, "R*", null, MatchMode.BEGINNING, null, null, null, null, null);
262
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
263

    
264
        results = taxonDao.getTaxaByName(false, true, true, true, false, "R*", null, MatchMode.BEGINNING, null, null, null, null, null);
265
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
266

    
267
        results = taxonDao.getTaxaByName(false, true, false, true, false, "c*", null, MatchMode.BEGINNING, null, null, null, null, null);
268
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
269

    
270
        results = taxonDao.getTaxaByName(true, false, false, true, false, "c*", null, MatchMode.BEGINNING, null, null, null, null, null);
271
        Assert.assertEquals("There should be 2 Taxa", 2, results.size());
272
        Classification classification = classificationDao.load(classificationUuid);
273
        results = taxonDao.getTaxaByName(false, false, false, true, false, "c*", classification, MatchMode.BEGINNING, null, null, null, null, null);
274
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
275
        Set<NamedArea> namedAreas = new HashSet<>();
276
        namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
277
        results = taxonDao.getTaxaByName(false, false, false, true, false, "c*", null, MatchMode.BEGINNING, namedAreas, null, null, null, null);
278
        Assert.assertEquals("There should be 1 Taxa", 1, results.size());
279
    }
280

    
281
    /**
282
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}.
283
     */
284
    @Test
285
    @DataSet
286
    public void testGetTaxaByNameForEditor() {
287
        Reference sec = referenceDao.findById(1);
288
        assert sec != null : "sec must exist";
289

    
290
        List<UuidAndTitleCache<IdentifiableEntity>> results = taxonDao.getTaxaByNameForEditor(true, true, false,false, false, "Acher", null, MatchMode.BEGINNING, null, null);
291
        assertNotNull("getTaxaByName should return a List", results);
292
        assertFalse("The list should not be empty", results.isEmpty());
293
        assertEquals(4, results.size());
294

    
295

    
296
        results = taxonDao.getTaxaByNameForEditor(true, true, false, false,false,"A",null, MatchMode.BEGINNING, null, null);
297
        assertNotNull("getTaxaByName should return a List", results);
298
        assertEquals(7, results.size());
299

    
300

    
301
        results = taxonDao.getTaxaByNameForEditor(true, false,false, false,false, "A", null,MatchMode.BEGINNING, null, null);
302
        assertNotNull("getTaxaByName should return a List", results);
303
        assertEquals(5, results.size());
304
        assertEquals(results.get(0).getType(), Taxon.class);
305

    
306
        results = taxonDao.getTaxaByNameForEditor(false, true,false,false, false,"A", null,MatchMode.BEGINNING, null, null);
307
        assertNotNull("getTaxaByName should return a List", results);
308
        assertEquals(2, results.size());
309
        assertEquals(results.get(0).getType(), Synonym.class);
310

    
311
        results = taxonDao.getTaxaByNameForEditor(true, true,false,false,false,"Aus", null,MatchMode.EXACT,  null, null);
312
        assertNotNull("getTaxaByName should return a List", results);
313
        assertEquals("Results list should contain one entity",1,results.size());
314

    
315
        results = taxonDao.getTaxaByNameForEditor(true, true,true,false,false,"A", null,MatchMode.BEGINNING,  null, null);
316
        assertNotNull("getTaxaByName should return a List", results);
317
        assertEquals("Results list should contain one entity", 8, results.size());
318

    
319
        //TODO: test the search for misapplied names
320

    
321
    }
322

    
323

    
324
    /**
325
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.taxon.TaxonDaoHibernateImpl#getTaxaByName(java.lang.String, eu.etaxonomy.cdm.model.reference.Reference)}
326
     * restricting the search by a set of Areas.
327
     */
328
    @Test
329
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
330
    public void testGetTaxaByNameAndArea() {
331

    
332
        Set<NamedArea> namedAreas = new HashSet<>();
333
        namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
334
        //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
335
        //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
336

    
337
        Classification taxonmicTree = classificationDao.findByUuid(classificationUuid);
338

    
339
        // prepare some synonym relation ships for some tests
340
        Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
341
        Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
342
        taxonRethera.addSynonym(synAtroposAgassiz, SynonymType.SYNONYM_OF());
343
        logger.warn("addSynonym(..)");
344

    
345
        Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
346
        Taxon taxonRetheraSecCdmtest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
347
        taxonRetheraSecCdmtest.addSynonym(synAtroposLeach, SynonymType.SYNONYM_OF());
348
        this.taxonDao.save(taxonRetheraSecCdmtest);
349

    
350
        Taxon test = (Taxon)this.taxonDao.findByUuid(retheraSecCdmtest);
351
//        Set<Synonym> synonyms3 = test.getSynonyms();
352
        // 1. searching for a taxon (Rethera)
353
        //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
354

    
355
        List<TaxonBase> results = taxonDao.getTaxaByName(true,false, false, false, false,"Rethera", null, MatchMode.BEGINNING, namedAreas,
356
            null, null, null, null);
357
        assertNotNull("getTaxaByName should return a List", results);
358
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
359

    
360
        results = taxonDao.getTaxaByName(false,false, false, true, false,"com*", null, MatchMode.BEGINNING, namedAreas,
361
                null, null, null, null);
362
            assertNotNull("getTaxaByName should return a List", results);
363
            assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
364

    
365
        // 2. searching for a taxon (Rethera) contained in a specific classification
366
        results = taxonDao.getTaxaByName(true, false, false, false, false,"Rethera", taxonmicTree, MatchMode.BEGINNING, namedAreas,
367
            null, null, null, null);
368
        assertNotNull("getTaxaByName should return a List", results);
369
        assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
370

    
371

    
372
        // 3. searching for Synonyms
373
        results = taxonDao.getTaxaByName(false, true, false, false, false,"Atropo", null, MatchMode.ANYWHERE, null,
374
            null, null, null, null);
375
        assertNotNull("getTaxaByName should return a List", results);
376
        /*System.err.println(results.get(0).getTitleCache() + " - " +results.get(1).getTitleCache() + " - " +results.get(2).getTitleCache() );
377

    
378

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

    
383
        // 4. searching for Synonyms
384
        results = taxonDao.getTaxaByName(false, true, false, false, false,"Atropo", null, MatchMode.BEGINNING, null,
385
            null, null, null, null);
386
        assertNotNull("getTaxaByName should return a List", results);
387
        assertTrue("expected to find three taxa but found "+results.size(), results.size() == 3);
388

    
389

    
390
        // 5. searching for a Synonyms and Taxa
391
        results = taxonDao.getTaxaByName(true, true, false, false, false,"A", null, MatchMode.BEGINNING, namedAreas,
392
            null, null, null, null);
393
        //only five taxa have a distribution
394
        assertNotNull("getTaxaByName should return a List", results);
395
        assertTrue("expected to find 8 taxa but found "+results.size(), results.size() == 8);
396
    }
397

    
398

    
399
    /**
400
     * 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)}
401
     * restricting the search by a set of Areas.
402
     */
403
    @Test
404
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
405
    public void testFindByNameTitleCache() {
406

    
407
        Set<NamedArea> namedAreas = new HashSet<NamedArea>();
408
        namedAreas.add((NamedArea)definedTermDao.load(northernAmericaUuid));
409
        //namedAreas.add((NamedArea)definedTermDao.load(southernAmericaUuid));
410
        //namedAreas.add((NamedArea)definedTermDao.load(antarcticaUuid));
411

    
412
        Classification classification = classificationDao.findByUuid(classificationUuid);
413

    
414
        // prepare some synonym relation ships for some tests
415
        Synonym synAtroposAgassiz = (Synonym)taxonDao.findByUuid(atroposAgassiz);
416
        Taxon taxonRethera = (Taxon)taxonDao.findByUuid(rethera);
417
        taxonRethera.addSynonym(synAtroposAgassiz, SynonymType.SYNONYM_OF());
418
        logger.warn("addSynonym(..)");
419
        this.taxonDao.clear();
420
        Synonym synAtroposLeach = (Synonym)taxonDao.findByUuid(atroposLeach);
421
        Taxon taxonRetheraSecCdmtest = (Taxon)taxonDao.findByUuid(retheraSecCdmtest);
422
        taxonRetheraSecCdmtest.addSynonym(synAtroposLeach, SynonymType.SYNONYM_OF());
423
        this.taxonDao.clear();
424
        // 1. searching for a taxon (Rethera)
425
        //long numberOfTaxa = taxonDao.countTaxaByName(Taxon.class, "Rethera", null, MatchMode.BEGINNING, namedAreas);
426

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

    
432
        // 2. searching for a taxon (Rethera) contained in a specific classification
433
        results = taxonDao.findByNameTitleCache(true, false, "Rethera Rothschild & Jordan, 1903", classification, MatchMode.EXACT, namedAreas,
434
            null, null, null, null);
435
        assertNotNull("getTaxaByName should return a List", results);
436
        assertTrue("expected to find one taxon but found "+results.size(), results.size() == 1);
437

    
438

    
439
        // 3. searching for Synonyms
440
        results = taxonDao.findByNameTitleCache(false, true, "*Atropo", null, MatchMode.ANYWHERE, null,
441
            null, null, null, null);
442
        assertNotNull("getTaxaByName should return a List", results);
443

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

    
446
        // 4. searching for Synonyms
447
        results = taxonDao.findByNameTitleCache(false, true, "Atropo", null, MatchMode.BEGINNING, null,
448
            null, null, null, null);
449
        assertNotNull("getTaxaByName should return a List", results);
450
        assertTrue("expected to find two taxa but found "+results.size(), results.size() == 2);
451

    
452

    
453
        // 5. searching for a Synonyms and Taxa
454
        //   attache a synonym first
455
        Synonym syn = (Synonym)taxonDao.findByUuid(this.atroposLeach);
456
        Taxon tax = (Taxon) taxonDao.findByUuid(rethera);
457
        tax.addSynonym(syn, SynonymType.HETEROTYPIC_SYNONYM_OF());
458

    
459
        taxonDao.save(tax);
460
        results = taxonDao.findByNameTitleCache(true, true, "A", null, MatchMode.BEGINNING, namedAreas,
461
            null, null, null, null);
462
        assertNotNull("getTaxaByName should return a List", results);
463
        assertTrue("expected to find 8 taxa but found "+results.size(), results.size() == 8);
464
    }
465

    
466
    @Test
467
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
468
    public void testTaxonNameInTwoClassifications(){
469
        int numberOfClassifications = classificationDao.count();
470
        List<String> propertyPaths = new ArrayList<>();
471
        propertyPaths.add("taxonNodes");
472
        List<TaxonBase> taxa = taxonDao.getTaxaByName(true, true, false, false, false,"P", null, MatchMode.BEGINNING, null, null, null, null, null);
473
        Taxon taxon = (Taxon)taxa.get(0);
474
        Set<TaxonNode> nodes = taxon.getTaxonNodes();
475
        assertTrue(nodes.size() == 1);
476
        //assertNotNull(taxa);
477
        //assertTrue(taxa.size() > 0);
478
    }
479

    
480
    @Test
481
    @DataSet
482
    public void testFindByUuid() {
483
        Taxon taxon = (Taxon)taxonDao.findByUuid(uuid);
484
        assertNotNull("findByUuid should return a taxon", taxon);
485
        assertFalse("findByUuid should not return a taxon with it's name initialized",Hibernate.isInitialized(taxon.getName()));
486
    }
487

    
488
    @Test
489
    @DataSet
490
    public void testLoad() {
491
        List<String> propertyPaths = new ArrayList<>();
492
        propertyPaths.add("name");
493
        propertyPaths.add("sec");
494
        Taxon taxon = (Taxon)taxonDao.load(uuid, propertyPaths);
495
        assertNotNull("findByUuid should return a taxon",taxon);
496
        assertTrue("load should return a taxon with it's name initialized, given that the property was specified in the method",Hibernate.isInitialized(taxon.getName()));
497
        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()));
498
    }
499

    
500
    @Test
501
    @DataSet
502
    public void testCountTaxonRelationshipsByTaxon()	{
503
        Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
504
        assert taxon != null : "taxon must exist";
505

    
506
        int numberOfRelatedTaxa = taxonDao.countTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo);
507
        assertEquals("countTaxonRelationships should return 8", 8, numberOfRelatedTaxa);
508
    }
509

    
510
    @Test
511
    @DataSet
512
    public void testCountTaxaByName() {
513
        long numberOfTaxa = taxonDao.countTaxaByName(true, false, false, false,false, "A", null, MatchMode.BEGINNING, null);
514
        assertEquals(5, numberOfTaxa);
515
        numberOfTaxa = taxonDao.countTaxaByName(true, false, false, false, false,"Smerinthus kindermannii", null, MatchMode.EXACT, null);
516
        assertEquals(1, numberOfTaxa);
517
        numberOfTaxa = taxonDao.countTaxaByName(false, true, false, false, false,"A", null, MatchMode.BEGINNING, null);
518
        assertEquals(2, numberOfTaxa);
519
        numberOfTaxa = taxonDao.countTaxaByName(true, true, false, false, false,"A", null, MatchMode.BEGINNING, null);
520
        assertEquals(7, numberOfTaxa);
521
        numberOfTaxa = taxonDao.countTaxaByName(true, true, false, false,false, "Aasfwerfwf fffe", null, MatchMode.BEGINNING, null);
522
        assertEquals(0, numberOfTaxa);
523
//	FIXME implement test for search in specific classification
524
//		Reference reference = referenceDao.findByUuid(UUID.fromString("596b1325-be50-4b0a-9aa2-3ecd610215f2"));
525
//		numberOfTaxa = taxonDao.countTaxaByName("A*", MatchMode.BEGINNING, SelectMode.ALL, null, null);
526
//		assertEquals(numberOfTaxa, 2);
527
    }
528

    
529
    @Test
530
    @DataSet
531
    public void testRelatedTaxa() {
532
        Taxon taxon = (Taxon)taxonDao.findByUuid(sphingidae);
533
        assert taxon != null : "taxon must exist";
534

    
535
        List<String> propertyPaths = new ArrayList<>();
536
        propertyPaths.add("fromTaxon");
537
        propertyPaths.add("fromTaxon.name");
538
        List<OrderHint> orderHints = new ArrayList<>();
539
        orderHints.add(new OrderHint("relatedFrom.name.genusOrUninomial", SortOrder.ASCENDING));
540
        orderHints.add(new OrderHint("relatedFrom.name.specificEpithet", SortOrder.ASCENDING));
541
        orderHints.add(new OrderHint("relatedFrom.name.infraSpecificEpithet", SortOrder.ASCENDING));
542

    
543
        List<TaxonRelationship> relatedTaxa = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
544
        assertNotNull("getRelatedTaxa should return a List",relatedTaxa);
545
        assertEquals("getRelatedTaxa should return all 8 related taxa", 8, relatedTaxa.size());
546
        assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon()));
547
        assertTrue("getRelatedTaxa should return TaxonRelationship objects with the relatedFrom taxon initialized",Hibernate.isInitialized(relatedTaxa.get(0).getFromTaxon().getName()));
548

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

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

    
559
        List<String> propertyPaths = new ArrayList<>();
560
        propertyPaths.add("fromTaxon");
561
        propertyPaths.add("fromTaxon.name");
562

    
563
        List<OrderHint> orderHints = new ArrayList<>();
564
        orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
565

    
566
        int pageSize = 3;
567
        List<TaxonRelationship> firstPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), pageSize, 0, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
568
        List<TaxonRelationship> secondPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(),pageSize, 1, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
569
        List<TaxonRelationship> thirdPage = taxonDao.getTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), pageSize, 2, orderHints,propertyPaths, TaxonRelationship.Direction.relatedTo);
570

    
571
        assertNotNull("getRelatedTaxa: 3, 0 should return a List",firstPage);
572
        assertEquals("getRelatedTaxa: 3, 0 should return a List with 3 elements", pageSize,firstPage.size());
573
        assertNotNull("getRelatedTaxa: 3, 1 should return a List",secondPage);
574
        assertEquals("getRelatedTaxa: 3, 1 should return a List with 3 elements", pageSize, secondPage.size());
575
        assertNotNull("getRelatedTaxa: 3, 2 should return a List",thirdPage);
576
        assertEquals("getRelatedTaxa: 3, 2 should return a List with 2 elements", 2, thirdPage.size());
577
    }
578

    
579
    @Test
580
    @DataSet
581
    public void testCountSynonyms() {
582
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
583
        assert taxon != null : "taxon must exist";
584

    
585
        long numberOfRelatedSynonym = taxonDao.countSynonyms(taxon,null);
586
        assertEquals("countSynonyms should return 3", 3, numberOfRelatedSynonym);
587
    }
588

    
589
    @Test
590
    @DataSet
591
    public void testGetSynonyms()	{
592
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
593
        assert taxon != null : "taxon must exist";
594
        List<String> propertyPaths = new ArrayList<String>();
595
        propertyPaths.add("synonym");
596
        propertyPaths.add("synonym.name");
597

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

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

    
603
        assertNotNull("getSynonyms should return a List", synonyms);
604
        assertEquals("getSynonyms should return 3 synonyms", 3, synonyms.size());
605
        assertTrue("getSynonyms should return synonym objects with the synonym initialized", Hibernate.isInitialized(synonyms.get(0)));
606
    }
607

    
608
    @Test
609
    @DataSet
610
    public void testCountSynonymsByType()	{
611
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
612
        assert taxon != null : "taxon must exist";
613

    
614
        long numberOfTaxonomicSynonyms = taxonDao.countSynonyms(taxon, SynonymType.HETEROTYPIC_SYNONYM_OF());
615
        assertEquals("countSynonyms should return 4", 3, numberOfTaxonomicSynonyms);
616
    }
617

    
618
    @Test
619
    @DataSet
620
    public void testSynonymsByType() {
621
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
622
        assert taxon != null : "taxon must exist";
623

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

    
626
        assertNotNull("getSynonyms should return a List", synonyms);
627
        assertEquals("getSynonyms should return 4 Synonyms", 3, synonyms.size());
628
    }
629

    
630
    @Test
631
    @DataSet
632
    public void testPageSynonyms(){
633
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
634
        assert taxon != null : "taxon must exist";
635

    
636
        int pageSize = 2;
637
        List<Synonym> firstPage = taxonDao.getSynonyms(taxon, null, pageSize, 0,null,null);
638
        List<Synonym> secondPage = taxonDao.getSynonyms(taxon, null, pageSize, 1,null,null);
639

    
640
        assertNotNull("getSynonyms: 2, 0 should return a List",firstPage);
641
        assertEquals("getSynonyms: 2, 0 should return 2 synonyms", pageSize,firstPage.size());
642
        assertNotNull("getSynonyms: 2, 1 should return a List",secondPage);
643
        assertEquals("getSynonyms: 2, 1 should return 1 synonym", 1, secondPage.size());
644
    }
645

    
646
    @Test
647
    @DataSet
648
    public void testCountTaxonRelationships() {
649
        long count = taxonDao.countTaxonRelationships(null);
650
        assertEquals("There should be 11 relationships", 11, count);
651

    
652
        Set<TaxonRelationshipType> types = new HashSet<>();
653
        count = taxonDao.countTaxonRelationships(types);
654
        assertEquals("Empty filter should return empty result", 0, count);
655

    
656
        types.add(TaxonRelationshipType.CONGRUENT_TO());
657
        count = taxonDao.countTaxonRelationships(types);
658
        assertEquals("There should be no congruent relationship", 0, count);
659

    
660
        types.add(TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN());
661
        count = taxonDao.countTaxonRelationships(types);
662
        assertEquals("There should be 11 tax included relationships", 11, count);
663
    }
664

    
665
    @Test
666
    @DataSet
667
    public void testlistTaxonRelationships() {
668
        List<TaxonRelationship> rels = taxonDao.getTaxonRelationships(null, null, null, null, null);
669
        assertEquals("There should be 11 relationships", 11, rels.size());
670

    
671
        rels = taxonDao.getTaxonRelationships(null, 2, 3, null, null);
672
        assertEquals("There should be 11 relationships", 2, rels.size());
673

    
674
        Set<TaxonRelationshipType> types = new HashSet<>();
675
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
676
        assertEquals("Empty filter should return empty result", 0, rels.size());
677

    
678
        types.add(TaxonRelationshipType.CONGRUENT_TO());
679
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
680
        assertEquals("There should be no congruent relationship", 0, rels.size());
681

    
682
        types.add(TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN());
683
        rels = taxonDao.getTaxonRelationships(types, null, null, null, null);
684
        assertEquals("There should be 11 tax included relationships", 11, rels.size());
685
    }
686

    
687
    @Test
688
    @DataSet("TaxonNodeDaoHibernateImplTest.xml")
689
    public void testListAcceptedTaxaFor()  {
690
        UUID acheontitia_ciprosus = UUID.fromString("3ef145f7-bd92-4a64-8afd-2b8203e00e02");
691

    
692
        Synonym synonym = (Synonym)taxonDao.findByUuid(acheontitia_ciprosus);
693
        assertNotNull("synonym must exist", synonym);
694

    
695
        Taxon taxon = taxonDao.acceptedTaxonFor(synonym, null, null);
696
        assertNotNull("listAcceptedTaxaFor should return a taxon", taxon);
697

    
698
        Classification classification = classificationDao.load(classificationUuid);
699
        assertNotNull("classification must exist", classification);
700

    
701
        taxon = taxonDao.acceptedTaxonFor(synonym, classification, null);
702
        assertNull("listAcceptedTaxaFor should return not taxon due to classification filter", taxon);
703
    }
704

    
705

    
706
    @Test
707
    @DataSet
708
    public void testGetTaxonMatchingUninomial() {
709
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class, "Smerinthus", "*", "*", "*","*",null,null,null);
710

    
711
        assertNotNull("findTaxaByName should return a List", result);
712
        assertEquals("findTaxaByName should return two Taxa",2,result.size());
713
        assertEquals("findTaxaByName should return a Taxon with id 5",5,result.get(0).getId());
714
    }
715

    
716
    @Test
717
    @DataSet
718
    public void testGetTaxonMatchingSpeciesBinomial() {
719
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class, "Smerinthus", null, "kindermannii", null,"*",null,null,null);
720

    
721
        assertNotNull("findTaxaByName should return a List", result);
722
        assertEquals("findTaxaByName should return one Taxon",1,result.size());
723
        assertEquals("findTaxaByName should return a Taxon with id 8",8,result.get(0).getId());
724
    }
725

    
726
    @Test
727
    @DataSet
728
    public void testGetTaxonMatchingTrinomial() {
729
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Cryptocoryne", null,"purpurea","borneoensis","*",null,null,null);
730

    
731
        assertNotNull("findTaxaByName should return a List", result);
732
        assertEquals("findTaxaByName should return one Taxon",1,result.size());
733
        assertEquals("findTaxaByName should return a Taxon with id 38",38,result.get(0).getId());
734
    }
735

    
736
    @Test
737
    @DataSet
738
    public void testNegativeMatch() {
739
        List<TaxonBase> result = taxonDao.findTaxaByName(Taxon.class,"Acherontia", null,"atropos","dehli",null,null,null,null);
740

    
741
        assertNotNull("findTaxaByName should return a List", result);
742
        assertTrue("findTaxaByName should return an empty List",result.isEmpty());
743
    }
744

    
745
    @Test
746
    @DataSet
747
    public void testCountAllTaxa() {
748
        int numberOfTaxa = taxonDao.count(Taxon.class);
749
        assertEquals("count should return 14 taxa", 14, numberOfTaxa);
750
    }
751

    
752
    @Test
753
    @DataSet
754
    public void testListAllTaxa() {
755
        List<Taxon> taxa = taxonDao.list(Taxon.class,100, 0);
756
        assertNotNull("list should return a List", taxa);
757
        assertEquals("list should return 14 taxa", 14, taxa.size());
758
    }
759

    
760
    @Test
761
    @DataSet
762
   // @ExpectedDataSet
763
    public void testDelete() {
764
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
765
        assert taxon != null : "taxon must exist";
766
        taxonDao.delete(taxon);
767
        taxon = (Taxon)taxonDao.findByUuid(acherontia);
768
        assert taxon == null : "taxon must not exist";
769
        setComplete();
770
        endTransaction();
771
//        try {
772
//            printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
773
//        } catch (FileNotFoundException e) {
774
//            e.printStackTrace();
775
//        }
776
    }
777

    
778
    @Test
779
    @DataSet
780
    @ExpectedDataSet("TaxonDaoHibernateImplTest.testDelete-result.xml")
781
    public void testDeleteWithMarker() {
782
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
783
        taxon.addMarker(Marker.NewInstance(MarkerType.IS_DOUBTFUL(), true));
784
        taxonDao.save(taxon);
785
        assert taxon != null : "taxon must exist";
786

    
787
        taxonDao.delete(taxon);
788
        commitAndStartNewTransaction(null);
789
        taxon = (Taxon)taxonDao.findByUuid(acherontia);
790
        assert taxon == null : "taxon must not exist";
791
        setComplete();
792
        endTransaction();
793
//        try {
794
//            printDataSet(new FileOutputStream("test.xml"), TABLE_NAMES);
795
//        } catch (FileNotFoundException e) {
796
//            e.printStackTrace();
797
//        }
798
    }
799

    
800
    @Test
801
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
802
    public void testFindDeleted() {
803
        TaxonBase<?> taxon = taxonDao.findByUuid(acherontia);
804
        assertNull("findByUuid should return null in this view", taxon);
805
        assertFalse("exist should return false in this view",taxonDao.exists(acherontia));
806
    }
807

    
808
    @Test
809
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
810
    public void testFindDeletedInPreviousView() {
811
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
812
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontia);
813
        assertNotNull("findByUuid should return a taxon in this view",taxon);
814
        assertTrue("exists should return true in this view", taxonDao.exists(acherontia));
815

    
816
        try{
817
            assertEquals("There should be 3 relations to this taxon in this view",3,taxon.getRelationsToThisTaxon().size());
818
        } catch(Exception e) {
819
            fail("We should not experience any problems initializing proxies with envers");
820
        }
821
    }
822

    
823
    @Test
824
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
825
    public void testGetAuditEvents() {
826
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
827
        assert taxon != null : "taxon cannot be null";
828

    
829
        List<String> propertyPaths = new ArrayList<>();
830
        propertyPaths.add("name");
831
        propertyPaths.add("createdBy");
832
        propertyPaths.add("updatedBy");
833

    
834
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,null,propertyPaths);
835
        assertNotNull("getAuditEvents should return a list",auditEvents);
836
        assertFalse("the list should not be empty",auditEvents.isEmpty());
837
        assertEquals("There should be two AuditEventRecords in the list",2, auditEvents.size());
838
    }
839

    
840
    @Test
841
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
842
    public void testGetAuditEventsFromNow() {
843
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
844
        TaxonBase<?> taxon =  taxonDao.findByUuid(sphingidae);
845
        assert taxon != null : "taxon cannot be null";
846

    
847
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(taxon, null,null,AuditEventSort.FORWARDS,null);
848
        assertNotNull("getAuditEvents should return a list",auditEvents);
849
        assertFalse("the list should not be empty",auditEvents.isEmpty());
850
        assertEquals("There should be one audit event in the list",1,auditEvents.size());
851
    }
852

    
853
    @Test
854
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
855
    public void testCountAuditEvents() {
856
        TaxonBase<?> taxon = taxonDao.findByUuid(sphingidae);
857
        assert taxon != null : "taxon cannot be null";
858

    
859
        int numberOfAuditEvents = taxonDao.countAuditEvents(taxon, null);
860
        assertEquals("countAuditEvents should return 2",numberOfAuditEvents,2);
861
    }
862

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

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

    
873
    @Test
874
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
875
    public void getPreviousAuditEventAtBeginning() {
876
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
877
        TaxonBase taxon = taxonDao.findByUuid(sphingidae);
878
        assert taxon != null : "taxon cannot be null";
879

    
880
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getPreviousAuditEvent(taxon);
881
        assertNull("getPreviousAuditEvent should return null if we're at the first audit event anyway",auditEvent);
882
    }
883

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

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

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

    
902
        AuditEventRecord<TaxonBase> auditEvent = taxonDao.getNextAuditEvent(taxon);
903
        assertNull("getNextAuditEvent should return null as there no more audit events after the current one",auditEvent);
904
    }
905

    
906
    @Test
907
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
908
    public void testFind() {
909
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
910
        assert taxon != null : "taxon cannot be null";
911

    
912
       assertEquals("getRelationsToThisTaxon should contain 1 TaxonRelationship in this view",1,taxon.getRelationsToThisTaxon().size());
913
    }
914

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

    
922
        assertTrue("getRelationsToThisTaxon should contain 0 TaxonRelationship in this view",taxon.getRelationsToThisTaxon().isEmpty());
923
    }
924

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

    
931
        List<String> propertyPaths = new ArrayList<>();
932
         propertyPaths.add("fromTaxon");
933
         propertyPaths.add("fromTaxon.name");
934

    
935
         List<OrderHint> orderHints = new ArrayList<>();
936
         orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
937

    
938
        List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
939
        assertNotNull("getRelatedTaxa should return a list", taxonRelations);
940
        assertEquals("there should be one TaxonRelationship in the list in the current view",1,taxonRelations.size());
941
        assertTrue("TaxonRelationship.relatedFrom should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon()));
942
        assertTrue("TaxonRelationship.relatedFrom.name should be initialized",Hibernate.isInitialized(taxonRelations.get(0).getFromTaxon().getName()));
943
    }
944

    
945
    @Test
946
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
947
    public void testCountRelations() {
948
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
949
        assert taxon != null : "taxon cannot be null";
950
        assertEquals("countRelatedTaxa should return 1 in the current view",1, taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo));
951
    }
952

    
953
    @Test
954
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
955
    public void testGetRelationsInPreviousView() {
956
       AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
957
       Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
958
       assert taxon != null : "taxon cannot be null";
959

    
960
       List<String> propertyPaths = new ArrayList<String>();
961
       propertyPaths.add("relatedFrom");
962
       propertyPaths.add("relatedFrom.name");
963

    
964
       List<OrderHint> orderHints = new ArrayList<>();
965
       orderHints.add(new OrderHint("relatedFrom.titleCache", SortOrder.ASCENDING));
966

    
967
       List<TaxonRelationship> taxonRelations = taxonDao.getTaxonRelationships(taxon, TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), null, null,orderHints,propertyPaths, TaxonRelationship.Direction.relatedFrom);
968
       assertNotNull("getRelatedTaxa should return a list",taxonRelations);
969
       assertTrue("there should be no TaxonRelationships in the list in the prior view",taxonRelations.isEmpty());
970
    }
971

    
972
    @Test
973
    @DataSet("TaxonDaoHibernateImplTest.testFind.xml")
974
    public void testCountRelationsInPreviousView() {
975
        AuditEventContextHolder.getContext().setAuditEvent(previousAuditEvent);
976
        Taxon taxon = (Taxon)taxonDao.findByUuid(acherontiaLachesis);
977
        assert taxon != null : "taxon cannot be null";
978
        assertEquals("countRelatedTaxa should return 0 in the current view",0, taxonDao.countTaxonRelationships(taxon,TaxonRelationshipType.TAXONOMICALLY_INCLUDED_IN(), TaxonRelationship.Direction.relatedTo));
979
    }
980

    
981
    @Test
982
    @DataSet
983
    public void testGroupTaxa() {
984
        List<Grouping> groups = new ArrayList<>();
985
        groups.add(new GroupByCount("count",SortOrder.DESCENDING));
986
        groups.add(new Grouping("name.genusOrUninomial", "genus", "n", SortOrder.ASCENDING));
987
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
988
        System.out.println("count\tname.genuOrUninomial");
989
        for(Object[] result : results) {
990
            System.out.println(result[0] + "\t" + result[1]);
991
        }
992
    }
993

    
994
    @Test
995
    @DataSet
996
    public void testGroupTaxaByClass() {
997
        List<Grouping> groups = new ArrayList<>();
998
        groups.add(new GroupByCount("count",SortOrder.DESCENDING));
999
        groups.add(new Grouping("class", "class",null, SortOrder.ASCENDING));
1000
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1001
        System.out.println("count\tclass");
1002
        for(Object[] result : results) {
1003
            System.out.println(result[0] + "\t" + result[1]);
1004
        }
1005
    }
1006

    
1007
    @Test
1008
    @DataSet
1009
    public void testNativeSQLOrder() {
1010
        List<OrderHint> orderHints = new ArrayList<>();
1011
        orderHints.add(new NativeSqlOrderHint("case when {alias}.titleCache like 'C%' then 0 else 1 end",SortOrder.ASCENDING));
1012

    
1013
        List<TaxonBase> results = taxonDao.list(null, null, orderHints);
1014
        System.out.println("native SQL order");
1015
        for(TaxonBase<?> result : results) {
1016
            System.out.println(result.getTitleCache());
1017
        }
1018
    }
1019

    
1020
    @Test
1021
    @DataSet
1022
    public void testGroupByDateTaxa() {
1023
        List<Grouping> groups = new ArrayList<>();
1024
        groups.add(new GroupByCount("count",null));
1025
        groups.add(new GroupByDate("created", "dateGroup", SortOrder.ASCENDING, GroupByDate.Resolution.MONTH));
1026
        List<Object[]> results = taxonDao.group(null, null, null, groups,null);
1027
        System.out.println("count\tyear\tmonth");
1028
        for(Object[] result : results) {
1029
            System.out.println(result[0] + "\t" + result[1] + "\t" + result[2]);
1030
        }
1031
    }
1032

    
1033
    @Test
1034
    @DataSet ("TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
1035
    public final void testGetTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(){
1036
        Classification classification = classificationDao.findByUuid(classificationUuid);
1037
        List<UuidAndTitleCache<TaxonNode>> result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification,  null, null);
1038
        assertNotNull(result);
1039
        assertEquals(5, result.size());
1040

    
1041
        //test exclude
1042
        UUID excludeUUID = UUID.fromString("a9f42927-e507-4fda-9629-62073a908aae");
1043
        List<UUID> excludeUUids = new ArrayList<>();
1044
        excludeUUids.add(excludeUUID);
1045
        result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification,  null, null);
1046
        assertEquals(5, result.size());
1047

    
1048
        //test limit
1049
        int limit = 2;
1050
        result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification,  limit, null);
1051
        assertEquals(2, result.size());
1052

    
1053
        //test pattern
1054
        String pattern = "*Rothschi*";
1055
        result = taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, 2, pattern);
1056
        assertNotNull(result);
1057
        assertEquals(1, result.size());
1058
        assertEquals("0b5846e5-b8d2-4ca9-ac51-099286ea4adc", result.get(0).getUuid().toString());
1059

    
1060
    }
1061

    
1062

    
1063
    @Test
1064
    @DataSet("TaxonDaoHibernateImplTest.testFindDeleted.xml")
1065
    //NOTE: There is a problem with loading AuditEvents if this test runs
1066
    //stand alone or as first (one of the first) in the test suite. For some reason
1067
    //the AuditEvent records from the @DataSet are not inserted into the database then,
1068
    //while those inserted by the terms dataset are inserted as well as a completely new one.
1069
    //This problem for some reason does not happen if not running at first place
1070
    public void testGetAuditEventsByTypeWithRestrictions() {
1071
        commitAndStartNewTransaction(new String[]{"AUDITEVENT", "TAXONBASE_AUD"});
1072

    
1073
        List<String> propertyPaths = new ArrayList<String>();
1074
        propertyPaths.add("name");
1075
        propertyPaths.add("createdBy");
1076
        propertyPaths.add("updatedBy");
1077

    
1078
        List<AuditCriterion> criteria = new ArrayList<>();
1079
        criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
1080

    
1081
        int count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1082

    
1083
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, criteria,null, null, AuditEventSort.FORWARDS, propertyPaths);
1084
        assertNotNull("getAuditEvents should return a list",auditEvents);
1085
        assertFalse("the list should not be empty",auditEvents.isEmpty());
1086
        assertEquals("There should be one AuditEventRecord in the list",1, auditEvents.size());
1087
    }
1088

    
1089

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

    
1105
        List<String> propertyPaths = new ArrayList<>();
1106
        propertyPaths.add("name");
1107
        propertyPaths.add("createdBy");
1108
        propertyPaths.add("updatedBy");
1109
        int count = taxonDao.countAuditEvents(TaxonBase.class, null, null, null);
1110
        List<AuditEventRecord<TaxonBase>> auditEvents = taxonDao.getAuditEvents(TaxonBase.class, previousAuditEvent, mostRecentAuditEvent, null,null, null, AuditEventSort.FORWARDS, propertyPaths);
1111
        assertNotNull("getAuditEvents should return a list", auditEvents);
1112
        assertFalse("the list should not be empty", auditEvents.isEmpty());
1113
        assertEquals("There should be thirty eight AuditEventRecords in the list", 2, auditEvents.size());
1114
    }
1115

    
1116

    
1117
    @Test
1118
    @DataSet("TaxonDaoHibernateImplTest.testGetTaxaByNameAndArea.xml")
1119
    public void testGetCommonName(){
1120
       List<Taxon> commonNameResults = taxonDao.getTaxaByCommonName("common%", null,
1121
                MatchMode.BEGINNING, null, null, null, null);
1122

    
1123
        assertNotNull("getTaxaByCommonName should return a list", commonNameResults);
1124
        assertFalse("the list should not be empty", commonNameResults.isEmpty());
1125
        assertEquals("There should be two taxa with common name", 2,commonNameResults.size());
1126

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

    
1129
        assertNotNull("getTaxaByCommonName should return a list", commonNameResults);
1130
        assertFalse("the list should not be empty", commonNameResults.isEmpty());
1131
        assertEquals("There should be two Taxon with common name", 2,commonNameResults.size());
1132

    
1133
    }
1134

    
1135
    @Test
1136
    @DataSet
1137
    public void testGetTitleCache(){
1138
        UUID uuid = UUID.fromString("7b8b5cb3-37ba-4dba-91ac-4c6ffd6ac331");
1139
        String titleCache = taxonDao.getTitleCache(uuid, false);
1140
        Assert.assertEquals("Acherontia styx Westwood, 1847 sec. cate-sphingidae.org", titleCache);
1141
        titleCache = taxonDao.getTitleCache(uuid, true);
1142
        Assert.assertEquals("Acherontia styxx Westwood, 1847 sec. cate-sphingidae.org", titleCache);
1143
   }
1144

    
1145

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

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

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

    
1187
}
(3-3/4)