Project

General

Profile

Download (94.8 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.api.service;
11

    
12
import static org.junit.Assert.assertEquals;
13
import static org.junit.Assert.assertNotNull;
14
import static org.junit.Assert.assertNull;
15
import static org.junit.Assert.assertTrue;
16

    
17
import java.io.FileNotFoundException;
18
import java.util.ArrayList;
19
import java.util.Iterator;
20
import java.util.List;
21
import java.util.Random;
22
import java.util.Set;
23
import java.util.UUID;
24

    
25
import org.apache.log4j.Logger;
26
import org.junit.Assert;
27
import org.junit.Test;
28
import org.unitils.dbunit.annotation.DataSet;
29
import org.unitils.spring.annotation.SpringBeanByType;
30

    
31
import eu.etaxonomy.cdm.api.service.config.IncludedTaxonConfiguration;
32
import eu.etaxonomy.cdm.api.service.config.NameDeletionConfigurator;
33
import eu.etaxonomy.cdm.api.service.config.NodeDeletionConfigurator.ChildHandling;
34
import eu.etaxonomy.cdm.api.service.config.SynonymDeletionConfigurator;
35
import eu.etaxonomy.cdm.api.service.config.TaxonDeletionConfigurator;
36
import eu.etaxonomy.cdm.api.service.dto.IncludedTaxaDTO;
37
import eu.etaxonomy.cdm.api.service.exception.HomotypicalGroupChangeException;
38
import eu.etaxonomy.cdm.model.agent.Person;
39
import eu.etaxonomy.cdm.model.common.Annotation;
40
import eu.etaxonomy.cdm.model.common.CdmBase;
41
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
42
import eu.etaxonomy.cdm.model.common.Language;
43
import eu.etaxonomy.cdm.model.common.LanguageString;
44
import eu.etaxonomy.cdm.model.common.Marker;
45
import eu.etaxonomy.cdm.model.common.MarkerType;
46
import eu.etaxonomy.cdm.model.common.OriginalSourceType;
47
import eu.etaxonomy.cdm.model.description.CommonTaxonName;
48
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
49
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
50
import eu.etaxonomy.cdm.model.description.TaxonDescription;
51
import eu.etaxonomy.cdm.model.description.TextData;
52
import eu.etaxonomy.cdm.model.name.HomotypicalGroup;
53
import eu.etaxonomy.cdm.model.name.IBotanicalName;
54
import eu.etaxonomy.cdm.model.name.INonViralName;
55
import eu.etaxonomy.cdm.model.name.NameRelationship;
56
import eu.etaxonomy.cdm.model.name.NameRelationshipType;
57
import eu.etaxonomy.cdm.model.name.Rank;
58
import eu.etaxonomy.cdm.model.name.TaxonName;
59
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
60
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
61
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
62
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
63
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
64
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
65
import eu.etaxonomy.cdm.model.reference.Reference;
66
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
67
import eu.etaxonomy.cdm.model.taxon.Classification;
68
import eu.etaxonomy.cdm.model.taxon.Synonym;
69
import eu.etaxonomy.cdm.model.taxon.SynonymType;
70
import eu.etaxonomy.cdm.model.taxon.Taxon;
71
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
72
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
73
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
74
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
75
import eu.etaxonomy.cdm.strategy.cache.common.IIdentifiableEntityCacheStrategy;
76
import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
77
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
78

    
79
/**
80
 * @author a.mueller
81
 */
82

    
83

    
84
public class TaxonServiceImplTest extends CdmTransactionalIntegrationTest {
85
    private static final Logger logger = Logger.getLogger(TaxonServiceImplTest.class);
86

    
87
    @SpringBeanByType
88
    private ITaxonService service;
89

    
90
    @SpringBeanByType
91
    private INameService nameService;
92

    
93
    @SpringBeanByType
94
    private IReferenceService referenceService;
95

    
96
    @SpringBeanByType
97
    private IClassificationService classificationService;
98

    
99
    @SpringBeanByType
100
    private ITaxonNodeService nodeService;
101

    
102
    @SpringBeanByType
103
    private IDescriptionService descriptionService;
104

    
105
    @SpringBeanByType
106
    private IMarkerService markerService;
107

    
108
    @SpringBeanByType
109
    private IEventBaseService eventService;
110

    
111
    @SpringBeanByType
112
    private IOccurrenceService occurenceService;
113

    
114
    private Synonym synonym;
115
    private Synonym synonym2;
116

    
117
    private Taxon taxWithSyn;
118
    private Taxon tax2WithSyn;
119
    private Taxon taxWithoutSyn;
120
    private UUID uuidSyn;
121
    private UUID uuidTaxWithoutSyn;
122
    private UUID uuidSyn2;
123
    private UUID uuidTaxWithSyn;
124

    
125
    private static String[] genera = {"Carex", "Abies", "Belladonna", "Dracula", "Maria", "Calendula", "Polygala", "Vincia"};
126
    private static String[] epitheta = {"vulgaris", "magdalena", "officinalis", "alba", "negra", "communa", "alpina", "rotundifolia", "greutheriana", "helventica", "allemania", "franca"};
127
    private static String[] ranks = {"subsp", "var", "f"};
128

    
129
    public static UUID GENUS_NAME_UUID = UUID.fromString("8d761fc4-b509-42f4-9568-244161934336");
130
    public static UUID GENUS_UUID = UUID.fromString("bf4298a8-1735-4353-a210-244442e1bd62");
131
    public static UUID BASIONYM_UUID = UUID.fromString("7911c51d-ccb7-4708-8992-639eae58a0e3");
132
    public static UUID SPECIES1_UUID = UUID.fromString("f0eb77d9-76e0-47f4-813f-9b5605b78685");
133
    public static UUID SPECIES1_NAME_UUID = UUID.fromString("efd78713-126f-42e1-9070-a1ff83f12abf");
134
    public static UUID SYNONYM_NAME_UUID = UUID.fromString("b9cbaa74-dbe0-4930-8050-b7754ce85dc0");
135
    public static UUID SPECIES2_NAME_UUID = UUID.fromString("0267ab67-483e-4da5-b654-11013b242c22");
136
    public static UUID SPECIES2_UUID = UUID.fromString("e20eb549-ced6-4e79-9d74-44f0792a4929");
137
    public static UUID SYNONYM2_NAME_UUID = UUID.fromString("7c17c811-4201-454b-8108-7be7c91c0938");
138
    public static UUID SPECIES5_NAME_UUID = UUID.fromString("0c6ecaac-804d-49e5-a33f-1b7ee77439e3");
139

    
140
/****************** TESTS *****************************/
141

    
142

    
143
    /**
144
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#getTaxonByUuid(java.util.UUID)}.
145
     */
146
    @Test
147
    public final void testGetTaxonByUuid() {
148
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
149
        UUID uuid = service.save(expectedTaxon).getUuid();
150
        TaxonBase<?> actualTaxon = service.find(uuid);
151
        assertEquals(expectedTaxon, actualTaxon);
152
    }
153

    
154
    /**
155
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#saveTaxon(eu.etaxonomy.cdm.model.taxon.TaxonBase)}.
156
     */
157
    @Test
158
    public final void testSaveTaxon() {
159
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
160
        UUID uuid = service.save(expectedTaxon).getUuid();
161
        TaxonBase<?> actualTaxon = service.find(uuid);
162
        assertEquals(expectedTaxon, actualTaxon);
163
    }
164

    
165
    @Test
166
    public final void testSaveOrUpdateTaxon() {
167
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
168
        UUID uuid = service.save(expectedTaxon).getUuid();
169
        TaxonBase<?> actualTaxon = service.find(uuid);
170
        assertEquals(expectedTaxon, actualTaxon);
171

    
172
        actualTaxon.setName(TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES()));
173
        try{
174
            service.saveOrUpdate(actualTaxon);
175
        }catch(Exception e){
176
            Assert.fail();
177
        }
178
    }
179
    /**
180
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#removeTaxon(eu.etaxonomy.cdm.model.taxon.TaxonBase)}.
181
     */
182
    @Test
183
    public final void testRemoveTaxon() {
184
        Taxon taxon = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.UNKNOWN_RANK()), null);
185
        UUID uuid = service.save(taxon).getUuid();
186
       // try {
187
			service.deleteTaxon(taxon.getUuid(), null, null);
188
		/*} catch (DataChangeNoRollbackException e) {
189
			// TODO Auto-generated catch block
190
			e.printStackTrace();
191
		}*/
192
        TaxonBase<?> actualTaxon = service.find(uuid);
193
        assertNull(actualTaxon);
194
    }
195

    
196

    
197
    @Test
198
    public final void testMakeTaxonSynonym() {
199
        try {
200
			createTestDataSet();
201
		} catch (FileNotFoundException e) {
202
			// TODO Auto-generated catch block
203
			e.printStackTrace();
204
		}
205

    
206
        service.swapSynonymAndAcceptedTaxon(synonym, taxWithSyn);
207

    
208
        // find forces flush
209
        Taxon tax = (Taxon)service.find(uuidTaxWithSyn);
210
        tax.removeSynonym(synonym);
211
        tax.addHomotypicSynonym(synonym);
212
        service.saveOrUpdate(tax);
213
        TaxonBase<?> syn = service.find(uuidSyn);
214

    
215
        assertTrue(tax.getName().getTitleCache().equals("Test2"));
216

    
217
        HomotypicalGroup groupTest = tax.getHomotypicGroup();
218
        HomotypicalGroup groupTest2 = syn.getHomotypicGroup();
219
        assertEquals(groupTest, groupTest2);
220

    
221
    }
222

    
223
    @Test
224
    public final void testChangeSynonymToAcceptedTaxon(){
225
    	try {
226
			createTestDataSet();
227
		} catch (FileNotFoundException e1) {
228
			// TODO Auto-generated catch block
229
			e1.printStackTrace();
230
		}
231

    
232

    
233
        Taxon taxon = null;
234
        UpdateResult result = new UpdateResult();
235
        try {
236
            result = service.changeSynonymToAcceptedTaxon(synonym, taxWithSyn, true);
237
        } catch (HomotypicalGroupChangeException e) {
238
            Assert.fail("Invocation of change method should not throw an exception");
239
        }
240
        taxWithSyn = null;
241
        //test flush (resave deleted object)
242
        TaxonBase<?> syn = service.find(uuidSyn);
243
        taxWithSyn = (Taxon)service.find(uuidTaxWithSyn);
244
        Taxon taxNew = (Taxon)service.find(result.getCdmEntity().getUuid());
245
        assertNull(syn);
246
        assertNotNull(taxWithSyn);
247
        assertNotNull(taxNew);
248

    
249
        Assert.assertEquals("New taxon should have 1 synonym relationship (the old homotypic synonym)", 1, ((Taxon)result.getCdmEntity()).getSynonyms().size());
250
    }
251

    
252

    
253

    
254
    @Test
255
    public final void testChangeSynonymToAcceptedTaxonSynonymForTwoTaxa(){
256
        try {
257
			createTestDataSet();
258
		} catch (FileNotFoundException e1) {
259
			// TODO Auto-generated catch block
260
			e1.printStackTrace();
261
		}
262

    
263

    
264
        Taxon taxon = null;
265
        UpdateResult result = new UpdateResult();
266
        try {
267
            result = service.changeSynonymToAcceptedTaxon(synonym, taxWithSyn, true);
268
            service.save(taxon);
269
        } catch (HomotypicalGroupChangeException e) {
270
            Assert.fail("Invocation of change method should not throw an exception");
271
        }
272
        taxWithSyn = null;
273
        tax2WithSyn = null;
274

    
275
        //test flush (resave deleted object)
276
        TaxonBase<?> syn = service.find(uuidSyn);
277
        taxWithSyn = (Taxon)service.find(uuidTaxWithSyn);
278
        Taxon taxNew = (Taxon)service.find(((Taxon)result.getCdmEntity()).getUuid());
279
        assertNull(syn);
280
        assertNotNull(taxWithSyn);
281
        assertNotNull(taxNew);
282

    
283
       // Assert.assertEquals("New taxon should have 1 synonym relationship (the old homotypic synonym)", 1, taxon.getSynonymRelations().size());
284
    }
285

    
286
    /**
287
     * Old implementation taken from {@link TaxonServiceImplBusinessTest} for old version of method.
288
     */
289
    @Test
290
    public final void testMoveSynonymToAnotherTaxon_OLD() {
291
        SynonymType heteroTypicSynonymType = SynonymType.HETEROTYPIC_SYNONYM_OF();
292
        Reference reference = ReferenceFactory.newGeneric();
293
        String referenceDetail = "test";
294

    
295
        INonViralName t1n = TaxonNameFactory.NewNonViralInstance(null);
296
        Taxon t1 = Taxon.NewInstance(t1n, reference);
297
        INonViralName t2n = TaxonNameFactory.NewNonViralInstance(null);
298
        Taxon t2 = Taxon.NewInstance(t2n, reference);
299
        INonViralName s1n = TaxonNameFactory.NewNonViralInstance(null);
300
        Synonym s1 = Synonym.NewInstance(s1n, reference);
301
        t1.addSynonym(s1, heteroTypicSynonymType);
302
        service.saveOrUpdate(t1);
303

    
304
        Synonym synonym = t1.getSynonyms().iterator().next();
305

    
306
        boolean keepReference = false;
307
        boolean moveHomotypicGroup = false;
308
        try {
309
            service.moveSynonymToAnotherTaxon(synonym, t2, moveHomotypicGroup, heteroTypicSynonymType, reference, referenceDetail, keepReference);
310
        } catch (HomotypicalGroupChangeException e) {
311
            Assert.fail("Method call should not throw exception");
312
        }
313

    
314
        Assert.assertTrue("t1 should have no synonyms", t1.getSynonyms().isEmpty());
315

    
316
        Set<Synonym> synonyms = t2.getSynonyms();
317
        Assert.assertTrue("t2 should have exactly one synonym", synonyms.size() == 1);
318

    
319
        synonym = synonyms.iterator().next();
320

    
321
        Assert.assertEquals(t2, synonym.getAcceptedTaxon());
322
        Assert.assertEquals(heteroTypicSynonymType, synonym.getType());
323
        Assert.assertEquals(reference, synonym.getSec());
324
        Assert.assertEquals(referenceDetail, synonym.getSecMicroReference());
325
    }
326

    
327
    @Test
328
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testMoveSynonymToAnotherTaxon.xml")
329
    public final void testMoveSynonymToAnotherTaxon() throws Exception {
330
        final String[] tableNames = new String[]{};
331

    
332
//        printDataSet(System.err, new String[]{"AgentBase", "TaxonBase"});
333
//        printDataSet(System.err, new String[]{"TaxonNode"});
334

    
335
        UUID uuidNewTaxon = UUID.fromString("2d9a642d-5a82-442d-8fec-95efa978e8f8");
336
        UUID uuidOldTaxon = UUID.fromString("c47fdb72-f32c-452e-8305-4b44f01179d0");
337
        UUID uuidSyn1 = UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
338
        UUID uuidSyn3 = UUID.fromString("3fba2b22-22ae-4291-af67-faab748a5232");
339
        UUID uuidSyn4 = UUID.fromString("f9b589c7-50cf-4df2-a52e-1b85eb7e4805");
340
        UUID uuidSyn5 = UUID.fromString("fcc0bcf8-8bac-43bd-9508-1e97821587dd");
341
        UUID uuidSyn6 = UUID.fromString("0ccd4e7c-6fbd-4b7c-bd47-29e45b92f34b");
342
        UUID uuidRef1 = UUID.fromString("336f9b38-698c-45d7-be7b-993ed3355bdc");
343
        UUID uuidRef2 = UUID.fromString("c8f49d1a-69e1-48a3-98bb-45d61f3da3e7");
344

    
345

    
346
        boolean moveHomotypicGroup = true;
347
        SynonymType newSynonymType = null;
348
        boolean keepReference = true;
349
        Reference newReference = null;
350
        String newReferenceDetail = null;
351

    
352
        Taxon newTaxon = (Taxon)service.load(uuidNewTaxon);
353
        Synonym homotypicSynonym = (Synonym)service.load(uuidSyn1);
354
        Assert.assertNotNull("Synonym should exist", homotypicSynonym);
355
        Assert.assertNotNull("Synonym should have 1 relation", homotypicSynonym.getAcceptedTaxon());
356
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, homotypicSynonym.getAcceptedTaxon().getUuid());
357
        Taxon oldTaxon = homotypicSynonym.getAcceptedTaxon();
358

    
359
        try {
360
            service.moveSynonymToAnotherTaxon(homotypicSynonym, newTaxon, moveHomotypicGroup, newSynonymType, newReference, newReferenceDetail, keepReference);
361
            Assert.fail("Homotypic synonym move to other taxon should throw an exception");
362
        } catch (HomotypicalGroupChangeException e) {
363
            if (e.getMessage().contains("Synonym is in homotypic group with accepted taxon and other synonym(s). First remove synonym from homotypic group of accepted taxon before moving to other taxon")){
364
                //OK
365
                commitAndStartNewTransaction(tableNames);
366
            }else{
367
                Assert.fail("Unexpected exception occurred: " + e.getMessage());
368
            }
369
        }
370
        //Asserts
371
        homotypicSynonym = (Synonym)service.load(uuidSyn1);
372
        Assert.assertNotNull("Synonym should still exist", homotypicSynonym);
373
        Assert.assertNotNull("Synonym should still have 1 relation", homotypicSynonym.getAcceptedTaxon());
374
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", oldTaxon, homotypicSynonym.getAcceptedTaxon());
375

    
376
        //test heterotypic synonym with other synonym in homotypic group
377
        newTaxon = (Taxon)service.load(uuidNewTaxon);
378
        Synonym heterotypicSynonym = (Synonym)service.load(uuidSyn3);
379
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym);
380
        Assert.assertNotNull("Synonym should have 1 relation", heterotypicSynonym.getAcceptedTaxon());
381
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, heterotypicSynonym.getAcceptedTaxon().getUuid());
382
        oldTaxon = heterotypicSynonym.getAcceptedTaxon();
383
        moveHomotypicGroup = false;
384

    
385
        try {
386
            service.moveSynonymToAnotherTaxon(heterotypicSynonym, newTaxon, moveHomotypicGroup, newSynonymType, newReference, newReferenceDetail, keepReference);
387
            Assert.fail("Heterotypic synonym move to other taxon should throw an exception");
388
        } catch (HomotypicalGroupChangeException e) {
389
            if (e.getMessage().contains("Synonym is in homotypic group with other synonym(s). Either move complete homotypic group or remove synonym from homotypic group prior to moving to other taxon")){
390
                //OK
391
                commitAndStartNewTransaction(tableNames);
392
            }else{
393
                Assert.fail("Unexpected exception occurred: " + e.getMessage());
394
            }
395
        }
396
        //Asserts
397
        heterotypicSynonym = (Synonym)service.load(uuidSyn3);
398
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
399
        Assert.assertNotNull("Synonym should have accepted taxon", heterotypicSynonym.getAcceptedTaxon());
400
        Assert.assertEquals("Accepted taxon of single relation should still be the old taxon", oldTaxon, heterotypicSynonym.getAcceptedTaxon());
401

    
402

    
403
        //test heterotypic synonym with no other synonym in homotypic group
404
        //+ keep reference
405

    
406
//        printDataSet(System.err, new String[]{"TaxonBase"});
407

    
408
        newTaxon = (Taxon)service.load(uuidNewTaxon);
409
        heterotypicSynonym = (Synonym)service.load(uuidSyn5);
410
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym);
411
        Assert.assertNotNull("Synonym should have accepted taxon", heterotypicSynonym.getAcceptedTaxon());
412
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, heterotypicSynonym.getAcceptedTaxon().getUuid());
413
        oldTaxon = heterotypicSynonym.getAcceptedTaxon();
414
        moveHomotypicGroup = false;
415

    
416

    
417
        try {
418
            service.moveSynonymToAnotherTaxon(heterotypicSynonym, newTaxon, moveHomotypicGroup, newSynonymType, newReference, newReferenceDetail, keepReference);
419
        } catch (HomotypicalGroupChangeException e) {
420
            Assert.fail("Move of single heterotypic synonym should not throw exception: " + e.getMessage());
421
        }
422
        //Asserts
423
        //FIXME throws exception
424
        commitAndStartNewTransaction(tableNames);
425

    
426
//        printDataSet(System.err, new String[]{"AgentBase", "TaxonBase"});
427
//
428
//      printDataSet(System.err, new String[]{"TaxonBase"});
429

    
430
        heterotypicSynonym = (Synonym)service.load(uuidSyn5);
431

    
432
//      printDataSet(System.err, new String[]{"TaxonBase"});
433
//      System.exit(0);
434

    
435
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
436
        Assert.assertNotNull("Synonym should have accepted taxon", heterotypicSynonym.getAcceptedTaxon());
437
        Assert.assertEquals("Accepted taxon of single relation should be new taxon", newTaxon, heterotypicSynonym.getAcceptedTaxon());
438
        Assert.assertEquals("Old detail should be kept", "rel5", heterotypicSynonym.getSecMicroReference());
439

    
440

    
441
        //test heterotypic synonym with other synonym in homotypic group and moveHomotypicGroup="true"
442
        //+ new detail
443
        newTaxon = (Taxon)service.load(uuidNewTaxon);
444
        heterotypicSynonym = (Synonym)service.load(uuidSyn3);
445
        Reference ref1 = referenceService.load(uuidRef1);
446
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym);
447
        Assert.assertNotNull("Synonym should have 1 relation", heterotypicSynonym.getAcceptedTaxon());
448
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, heterotypicSynonym.getAcceptedTaxon().getUuid());
449
        oldTaxon = heterotypicSynonym.getAcceptedTaxon();
450
        Assert.assertEquals("Detail should be ref1", ref1, heterotypicSynonym.getSec());
451
        Assert.assertEquals("Detail should be 'rel3'", "rel3", heterotypicSynonym.getSecMicroReference());
452
        TaxonName oldSynName3 = heterotypicSynonym.getName();
453

    
454
        Synonym heterotypicSynonym4 = (Synonym)service.load(uuidSyn4);
455
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym4);
456
        Assert.assertNotNull("Synonym should have accepted taxon", heterotypicSynonym4.getAcceptedTaxon());
457
        Assert.assertEquals("Accepted taxon of other synonym in group should be the old taxon", uuidOldTaxon, heterotypicSynonym4.getAcceptedTaxon().getUuid());
458
        Assert.assertSame("Homotypic group of both synonyms should be same", oldSynName3.getHomotypicalGroup() , heterotypicSynonym4.getName().getHomotypicalGroup() );
459

    
460
        moveHomotypicGroup = true;
461
        keepReference = false;
462

    
463
        try {
464
            service.moveSynonymToAnotherTaxon(heterotypicSynonym4, newTaxon, moveHomotypicGroup, newSynonymType, newReference, newReferenceDetail, keepReference);
465
        } catch (HomotypicalGroupChangeException e) {
466
            Assert.fail("Move with 'moveHomotypicGroup = true' should not throw exception: " + e.getMessage());
467
        }
468
        //Asserts
469
        commitAndStartNewTransaction(tableNames);
470
        heterotypicSynonym = (Synonym)service.load(uuidSyn3);
471
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
472
        Assert.assertNotNull("Synonym should still have accepted taxon", heterotypicSynonym.getAcceptedTaxon());
473
        Assert.assertEquals("Accepted taxon of relation should be new taxon now", newTaxon, heterotypicSynonym.getAcceptedTaxon());
474
        TaxonName synName3 = heterotypicSynonym.getName();
475

    
476
        heterotypicSynonym = (Synonym)service.load(uuidSyn4);
477
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
478
        Assert.assertNotNull("Synonym should still have accepted taxon", heterotypicSynonym.getAcceptedTaxon());
479
        Assert.assertEquals("Accepted taxon of relation should be new taxon now", newTaxon, heterotypicSynonym.getAcceptedTaxon());
480
        Assert.assertNull("Old citation should be removed", heterotypicSynonym.getSec());
481
        Assert.assertNull("Old detail should be removed", heterotypicSynonym.getSecMicroReference());
482
        TaxonName synName4 = heterotypicSynonym.getName();
483
        Assert.assertEquals("Homotypic group of both synonyms should be equal", synName3.getHomotypicalGroup() , synName4.getHomotypicalGroup() );
484
        Assert.assertSame("Homotypic group of both synonyms should be same", synName3.getHomotypicalGroup() , synName4.getHomotypicalGroup() );
485
        Assert.assertEquals("Homotypic group of both synonyms should be equal to old homotypic group", oldSynName3.getHomotypicalGroup() , synName3.getHomotypicalGroup() );
486

    
487

    
488
        //test single heterotypic synonym to homotypic synonym of new taxon
489
        //+ new reference
490
        newTaxon = (Taxon)service.load(uuidNewTaxon);
491
        Reference ref2 = referenceService.load(uuidRef2);
492
        heterotypicSynonym = (Synonym)service.load(uuidSyn6);
493
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym);
494
        Assert.assertNotNull("Synonym should have accepted taxon", heterotypicSynonym.getAcceptedTaxon());
495
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, heterotypicSynonym.getAcceptedTaxon().getUuid());
496
        oldTaxon = heterotypicSynonym.getAcceptedTaxon();
497
        moveHomotypicGroup = false;
498
        keepReference = false;
499
        newReference = ref2;
500
        newReferenceDetail = "newRefDetail";
501
        newSynonymType = SynonymType.HOMOTYPIC_SYNONYM_OF();
502

    
503
        try {
504
            service.moveSynonymToAnotherTaxon(heterotypicSynonym, newTaxon, moveHomotypicGroup, newSynonymType, newReference, newReferenceDetail, keepReference);
505
        } catch (HomotypicalGroupChangeException e) {
506
            Assert.fail("Move of single heterotypic synonym should not throw exception: " + e.getMessage());
507
        }
508
        //Asserts
509
        commitAndStartNewTransaction(tableNames);
510
        heterotypicSynonym = (Synonym)service.load(uuidSyn6);
511
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
512
        Assert.assertNotNull("Synonym should still have accepted taxon", heterotypicSynonym.getAcceptedTaxon());
513
        Assert.assertEquals("Relationship type should be 'homotypic synonym'", newSynonymType, heterotypicSynonym.getType());
514
        Assert.assertEquals("Accepted taxon of single relation should be new taxon", newTaxon, heterotypicSynonym.getAcceptedTaxon());
515
        Assert.assertEquals("New citation should be ref2", ref2 ,heterotypicSynonym.getSec());
516
        Assert.assertEquals("New detail should be kept", "newRefDetail", heterotypicSynonym.getSecMicroReference());
517

    
518
        Assert.assertEquals("New taxon and new synonym should have equal homotypical group", heterotypicSynonym.getHomotypicGroup(), heterotypicSynonym.getAcceptedTaxon().getHomotypicGroup());
519
        Assert.assertSame("New taxon and new synonym should have same homotypical group", heterotypicSynonym.getHomotypicGroup(), heterotypicSynonym.getAcceptedTaxon().getHomotypicGroup());
520
    }
521

    
522

    
523

    
524
    @Test
525
    public final void testGetHeterotypicSynonymyGroups(){
526
        Rank rank = Rank.SPECIES();
527
        Reference ref1 = ReferenceFactory.newGeneric();
528
        //HomotypicalGroup group = HomotypicalGroup.NewInstance();
529
        Taxon taxon1 = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test3", null, null, null, null, null, null, null), null);
530
        Synonym synonym0 = Synonym.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test2", null, null, null, null, null, null, null), null);
531
        Synonym synonym1 = Synonym.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test2", null, null, null, null, null, null, null), null);
532
        Synonym synonym2 = Synonym.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test4", null, null, null, null, null, null, null), null);
533
        synonym0.getName().setHomotypicalGroup(taxon1.getHomotypicGroup());
534
        synonym2.getName().setHomotypicalGroup(synonym1.getHomotypicGroup());
535
        //tax2.addHeterotypicSynonymName(synonym.getName());
536
        taxon1.addSynonym(synonym1, SynonymType.HETEROTYPIC_SYNONYM_OF());
537
        taxon1.addSynonym(synonym2, SynonymType.HETEROTYPIC_SYNONYM_OF());
538

    
539
        service.save(synonym1);
540
        service.save(synonym2);
541
        service.save(taxon1);
542

    
543
        List<List<Synonym>> heteroSyns = service.getHeterotypicSynonymyGroups(taxon1, null);
544
        Assert.assertEquals("There should be 1 heterotypic group", 1, heteroSyns.size());
545
        List<Synonym> synList = heteroSyns.get(0);
546
        Assert.assertEquals("There should be 2 heterotypic syns in group 1", 2, synList.size());
547

    
548
        //test sec
549
        synonym2.setSec(ref1);
550
        heteroSyns = service.getHeterotypicSynonymyGroups(taxon1, null);
551
        Assert.assertEquals("There should be 1 heterotypic group", 1, heteroSyns.size());
552
        synList = heteroSyns.get(0);
553
        Assert.assertEquals("getHeterotypicSynonymyGroups should be independent of sec reference", 2, synList.size());
554

    
555
    }
556

    
557

    
558
    @Test
559
    public final void testGetHomotypicSynonymsByHomotypicGroup(){
560
        Rank rank = Rank.SPECIES();
561
        Reference ref1 = ReferenceFactory.newGeneric();
562
        //HomotypicalGroup group = HomotypicalGroup.NewInstance();
563
        Taxon taxon1 = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test3", null, null, null, null, null, null, null), null);
564
        Synonym synonym0 = Synonym.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test2", null, null, null, null, null, null, null), null);
565
        Synonym synonym1 = Synonym.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test2", null, null, null, null, null, null, null), null);
566
        Synonym synonym2 = Synonym.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test4", null, null, null, null, null, null, null), null);
567
        synonym0.getName().setHomotypicalGroup(taxon1.getHomotypicGroup());
568
        synonym2.getName().setHomotypicalGroup(synonym1.getHomotypicGroup());
569
        //tax2.addHeterotypicSynonymName(synonym.getName());
570
        taxon1.addSynonym(synonym0, SynonymType.HOMOTYPIC_SYNONYM_OF());
571
        taxon1.addSynonym(synonym1, SynonymType.HETEROTYPIC_SYNONYM_OF());
572
        taxon1.addSynonym(synonym2, SynonymType.HETEROTYPIC_SYNONYM_OF());
573

    
574
        service.save(synonym1);
575
        service.save(synonym2);
576
        service.save(taxon1);
577

    
578
        List<Synonym> homoSyns = service.getHomotypicSynonymsByHomotypicGroup(taxon1, null);
579
        Assert.assertEquals("There should be 1 heterotypic group", 1, homoSyns.size());
580
        Assert.assertSame("The homotypic synonym should be synonym0", synonym0, homoSyns.get(0));
581

    
582
        //test sec
583
        synonym0.setSec(ref1);
584
        homoSyns = service.getHomotypicSynonymsByHomotypicGroup(taxon1, null);
585
        Assert.assertEquals("getHeterotypicSynonymyGroups should be independent of sec reference", 1, homoSyns.size());
586

    
587
    }
588

    
589
    @Test
590
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
591
    //test delete synonym, but the name will not be deleted
592
    public final void testDeleteSynonymSynonymTaxonDontDeleteName(){
593
        final String[]tableNames = {
594
//                "TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
595
//                "HomotypicalGroup","HomotypicalGroup_AUD"
596
        };
597

    
598
        int nSynonyms = service.count(Synonym.class);
599
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
600
        int nNames = nameService.count(TaxonName.class);
601
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
602
        int nRelations = service.countSynonyms(true);
603
        Assert.assertEquals("There should be two relationship left in the database", 2, nRelations);
604

    
605
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
606

    
607

    
608
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
609
        SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
610
        config.setDeleteNameIfPossible(false);
611
        config.setNewHomotypicGroupIfNeeded(true);
612
        service.deleteSynonym(synonym1, config);
613

    
614
        this.commitAndStartNewTransaction(tableNames);
615

    
616
        nSynonyms = service.count(Synonym.class);
617
        Assert.assertEquals("There should be 1 synonym left in the database", 1, nSynonyms);
618
        nNames = nameService.count(TaxonName.class);
619
        Assert.assertEquals("There should be 4 names left in the database", 4, nNames);
620
        nRelations = service.countSynonyms(true);
621
        Assert.assertEquals("There should be no relationship left in the database", 1, nRelations);
622
    }
623

    
624
    @Test
625
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
626
    //test delete synonym and his name
627
    public final void testDeleteSynonymSynonymTaxonDeleteName(){
628
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
629
                "HomotypicalGroup","HomotypicalGroup_AUD"};
630

    
631
        int nSynonyms = service.count(Synonym.class);
632
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
633
        int nNames = nameService.count(TaxonName.class);
634
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
635
        int nRelations = service.countSynonyms(true);
636
        Assert.assertEquals("There should be 2 relationship left in the database", 2, nRelations);
637

    
638
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
639

    
640

    
641
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
642
        service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
643

    
644
        this.commitAndStartNewTransaction(tableNames);
645

    
646
        nSynonyms = service.count(Synonym.class);
647
        Assert.assertEquals("There should be 1 synonym left in the database", 1, nSynonyms);
648
        nNames = nameService.count(TaxonName.class);
649
        Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
650
        nRelations = service.countSynonyms(true);
651
        Assert.assertEquals("There should be 1 relationship left in the database", 1, nRelations);
652

    
653
    }
654

    
655
    @Test
656
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
657
    //test remove synonym from taxon -> synonym and name still in the db and the synonymrelationship to the other taxon
658
    //test delete synonym -> all relationships are deleted, the name is deleted and the synonym itself
659
    public final void testDeleteSynonymSynonymTaxonBooleanRelToOneTaxon(){
660
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
661
                "HomotypicalGroup","HomotypicalGroup_AUD"};
662

    
663
        int nSynonyms = service.count(Synonym.class);
664
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
665
        int nNames = nameService.count(TaxonName.class);
666
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
667

    
668
        UUID uuidTaxon1=UUID.fromString("c47fdb72-f32c-452e-8305-4b44f01179d0");
669
        UUID uuidTaxon2=UUID.fromString("2d9a642d-5a82-442d-8fec-95efa978e8f8");
670
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
671

    
672

    
673
        Taxon taxon2 = (Taxon)service.load(uuidTaxon1);
674

    
675
        List<String> initStrat = new ArrayList<String>();
676
        initStrat.add("markers");
677
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1, initStrat);
678
        int nRelations = service.countSynonyms(true);
679
        Assert.assertEquals("There should be 2 relationship left in the database", 2, nRelations);
680

    
681
        taxon2.removeSynonym(synonym1, false);
682
        service.saveOrUpdate(taxon2);
683

    
684
        commitAndStartNewTransaction(null);
685

    
686
        nSynonyms = service.count(Synonym.class);
687
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
688
        nNames = nameService.count(TaxonName.class);
689
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
690
        nRelations = service.countSynonyms(true);
691
        Assert.assertEquals("There should be 1 relationship left in the database", 1, nRelations);
692
        Marker marker1 = Marker.NewInstance(MarkerType.IMPORTED(), true);
693
        Marker marker2 = Marker.NewInstance(MarkerType.COMPUTED(), true);
694
        synonym1.addMarker(marker1);
695
        synonym1.addMarker(marker2);
696
        service.update(synonym1);
697
        synonym1 =(Synonym) service.load(uuidSynonym1);
698

    
699

    
700
        Set<Marker> markers = synonym1.getMarkers();
701
        Marker marker = markers.iterator().next();
702
        UUID markerUUID = marker.getUuid();
703
       // taxon2 = (Taxon)service.load(uuidTaxon2);
704
        synonym1 = (Synonym)service.load(uuidSynonym1);
705
        //the marker should not prevent the deletion
706
        DeleteResult result = service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
707
        if (!result.isOk()){
708
        	Assert.fail();
709
        }
710

    
711

    
712
        commitAndStartNewTransaction(tableNames);
713
        nSynonyms = service.count(Synonym.class);
714
        Assert.assertEquals("There should be 1 synonym left in the database", 1, nSynonyms);
715
        nNames = nameService.count(TaxonName.class);
716
        Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
717
        nRelations = service.countSynonyms(true);
718
        Assert.assertEquals("There should be no relationship left in the database", 1, nRelations);
719
        marker = markerService.load(markerUUID);
720
        assertNull(marker);
721

    
722
    }
723

    
724
    @Test
725
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
726
    //this test is more or less obsolete since we have no synonym relationships anymore
727
    //test delete synonym, only for a special taxon, but because of other relationships it will not be deleted at all
728
    public final void testDeleteSynonymSynonymTaxonBooleanDeleteOneTaxon(){
729
        final String[]tableNames = {
730
//                "TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
731
//                "HomotypicalGroup","HomotypicalGroup_AUD"
732
        };
733
        int nSynonyms = service.count(Synonym.class);
734
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
735
        int nNames = nameService.count(TaxonName.class);
736
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
737

    
738
        UUID uuidTaxon2=UUID.fromString("2d9a642d-5a82-442d-8fec-95efa978e8f8");
739
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
740

    
741
        Taxon taxon2 = (Taxon)service.load(uuidTaxon2);
742
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
743
        taxon2.addSynonym(synonym1, SynonymType.HETEROTYPIC_SYNONYM_OF());
744
        service.saveOrUpdate(synonym1);
745
        int nRelations = service.countSynonyms(true);
746
        //this was "3" when we still had synonym relationships
747
        Assert.assertEquals("There should be 2 relationship left in the database", 2, nRelations);
748
        service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
749

    
750
        this.commitAndStartNewTransaction(tableNames);
751

    
752
        nSynonyms = service.count(Synonym.class);
753
        //this was "2" when we still had synonym relationships
754
        Assert.assertEquals("There should still be 1 synonym left in the database", 1, nSynonyms);
755
        nNames = nameService.count(TaxonName.class);
756
        //was 3
757
        Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
758
        nRelations = service.countSynonyms(true);
759
        Assert.assertEquals("There should be 1 related synonym left in the database", 1, nRelations);
760
    }
761

    
762
    @Test
763
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
764

    
765
    public final void testDeleteSynonymWithAnnotations(){
766
        final String[]tableNames = {
767
//                "TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
768
//                "HomotypicalGroup","HomotypicalGroup_AUD"
769
        };
770

    
771

    
772
        UUID uuidTaxon2=UUID.fromString("2d9a642d-5a82-442d-8fec-95efa978e8f8");
773
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
774

    
775
        Taxon taxon2 = (Taxon)service.load(uuidTaxon2);
776
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
777
        taxon2.addSynonym(synonym1, SynonymType.HETEROTYPIC_SYNONYM_OF());
778

    
779
        Annotation annotation = Annotation.NewDefaultLanguageInstance("test");
780
        synonym1.addAnnotation(annotation);
781
        service.saveOrUpdate(synonym1);
782

    
783
        DeleteResult result = service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
784
        if (result.isError()){
785
            Assert.fail();
786
        }
787
        this.commitAndStartNewTransaction(tableNames);
788

    
789

    
790
    }
791

    
792

    
793
    @Test
794
    @DataSet("TaxonServiceImplTest.testDeleteSynonym.xml")
795

    
796
    public final void testDeleteSynonymSynonymTaxonBooleanWithRelatedName(){
797
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
798
                "HomotypicalGroup","HomotypicalGroup_AUD"};
799

    
800
        int nSynonyms = service.count(Synonym.class);
801
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
802
        int nNames = nameService.count(TaxonName.class);
803
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
804

    
805
        UUID uuidTaxon1=UUID.fromString("c47fdb72-f32c-452e-8305-4b44f01179d0");
806
        UUID uuidTaxon2=UUID.fromString("2d9a642d-5a82-442d-8fec-95efa978e8f8");
807
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
808
        UUID uuidSynonym2=UUID.fromString("f8d86dc9-5f18-4877-be46-fbb9412465e4");
809
        UUID uuidSynonymName2=UUID.fromString("613f3c93-013e-4ffc-aadc-1c98d71c335e");
810

    
811
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
812
        TaxonName name2 = nameService.load(uuidSynonymName2);
813
        UUID name3Uuid = synonym1.getName().getUuid();
814
        TaxonName name3 = nameService.load(name3Uuid);
815
        name3.addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
816

    
817
        service.saveOrUpdate(synonym1);
818

    
819
        int nRelations = nameService.getAllRelationships(1000, 0).size();
820
        logger.info("number of name relations: " + nRelations);
821
        Assert.assertEquals("There should be 1 name relationship left in the database", 1, nRelations);
822
        SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
823

    
824
        service.deleteSynonym(synonym1, config);
825

    
826
        this.commitAndStartNewTransaction(tableNames);
827
        //synonym is deleted, but the name can not be deleted because of a name relationship
828
        nSynonyms = service.count(Synonym.class);
829
        Assert.assertEquals("There should still be 1 synonyms left in the database", 1, nSynonyms);
830
        nNames = nameService.count(TaxonName.class);
831
        Assert.assertEquals("There should be 4 names left in the database (name is related to synonymName2)", 4, nNames);
832
        nRelations = service.countSynonyms(true);
833
        //may change with better implementation of countAllRelationships (see #2653)
834
        nRelations = nameService.getAllRelationships(1000, 0).size();
835
        logger.info("number of name relations: " + nRelations);
836
        Assert.assertEquals("There should be 1 name relationship left in the database", 1, nRelations);
837

    
838

    
839
        //clean up database
840
        name2 = nameService.load(uuidSynonymName2);
841
        NameRelationship rel = CdmBase.deproxy(name2.getNameRelations().iterator().next(), NameRelationship.class);
842
        name2.removeNameRelationship(rel);
843
        nameService.save(name2);
844
        this.setComplete();
845
        this.endTransaction();
846

    
847
    }
848

    
849
    @Test
850
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
851
    public final void testDeleteSynonymSynonymTaxonBooleanWithRelatedNameDeleteAllNameRelations(){
852
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
853
                "HomotypicalGroup","HomotypicalGroup_AUD"};
854

    
855
        int nSynonyms = service.count(Synonym.class);
856
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
857
        int nNames = nameService.count(TaxonName.class);
858
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
859

    
860
        UUID uuidTaxon1=UUID.fromString("c47fdb72-f32c-452e-8305-4b44f01179d0");
861
        UUID uuidTaxon2=UUID.fromString("2d9a642d-5a82-442d-8fec-95efa978e8f8");
862
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
863
        UUID uuidSynonym2=UUID.fromString("f8d86dc9-5f18-4877-be46-fbb9412465e4");
864
        UUID uuidSynonymName2=UUID.fromString("613f3c93-013e-4ffc-aadc-1c98d71c335e");
865

    
866
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
867
        TaxonName name2 = nameService.load(uuidSynonymName2);
868
        UUID name3Uuid = synonym1.getName().getUuid();
869
        TaxonName name3 = nameService.load(name3Uuid);
870
        name3.addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
871

    
872
        service.saveOrUpdate(synonym1);
873

    
874
        int nRelations = nameService.getAllRelationships(1000, 0).size();
875
        logger.info("number of name relations: " + nRelations);
876
        Assert.assertEquals("There should be 1 name relationship left in the database", 1, nRelations);
877
        SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
878
        NameDeletionConfigurator nameDeletionConfig = new NameDeletionConfigurator();
879
        nameDeletionConfig.setRemoveAllNameRelationships(true);
880
        config.setNameDeletionConfig(nameDeletionConfig);
881

    
882
        service.deleteSynonym(synonym1, config);
883

    
884
        this.commitAndStartNewTransaction(tableNames);
885

    
886
        nSynonyms = service.count(Synonym.class);
887
        Assert.assertEquals("There should still be 1 synonyms left in the database", 1, nSynonyms);
888
        nNames = nameService.count(TaxonName.class);
889
        Assert.assertEquals("There should be 3 names left in the database ", 3, nNames);
890
        nRelations = service.countSynonyms(true);
891
        //may change with better implementation of countAllRelationships (see #2653)
892
        nRelations = nameService.getAllRelationships(1000, 0).size();
893
        logger.info("number of name relations: " + nRelations);
894
        Assert.assertEquals("There should be no name relationship left in the database", 0, nRelations);
895
    }
896

    
897
    @Test
898
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
899
    public final void testDeleteSynonymSynonymTaxonBooleanWithRelatedNameIgnoreIsBasionym(){
900
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
901
                "HomotypicalGroup","HomotypicalGroup_AUD"};
902

    
903
        int nSynonyms = service.count(Synonym.class);
904
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
905
        int nNames = nameService.count(TaxonName.class);
906
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
907

    
908
        UUID uuidTaxon1=UUID.fromString("c47fdb72-f32c-452e-8305-4b44f01179d0");
909
        UUID uuidTaxon2=UUID.fromString("2d9a642d-5a82-442d-8fec-95efa978e8f8");
910
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
911
        UUID uuidSynonym2=UUID.fromString("f8d86dc9-5f18-4877-be46-fbb9412465e4");
912
        UUID uuidSynonymName2=UUID.fromString("613f3c93-013e-4ffc-aadc-1c98d71c335e");
913

    
914
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
915
        TaxonName synName2 = nameService.load(uuidSynonymName2);
916
        UUID name3Uuid = synonym1.getName().getUuid();
917
        TaxonName synName1 = nameService.load(name3Uuid);
918
        synName1.addRelationshipFromName(synName2, NameRelationshipType.BASIONYM(), null);
919

    
920
        service.saveOrUpdate(synonym1);
921

    
922
        int nRelations = nameService.getAllRelationships(1000, 0).size();
923
        logger.info("number of name relations: " + nRelations);
924
        Assert.assertEquals("There should be 1 name relationship left in the database", 1, nRelations);
925
        SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
926
        NameDeletionConfigurator nameDeletionConfig = new NameDeletionConfigurator();
927
        nameDeletionConfig.setIgnoreIsBasionymFor(true);
928
        config.setNameDeletionConfig(nameDeletionConfig);
929

    
930
        DeleteResult result =service.deleteSynonym(synonym1, config);
931
        if (!result.isOk()){
932
        	Assert.fail();
933
        }
934

    
935

    
936
        logger.debug(result);
937
        this.commitAndStartNewTransaction(tableNames);
938

    
939
        nSynonyms = service.count(Synonym.class);
940
        Assert.assertEquals("There should still be 1 synonyms left in the database", 1, nSynonyms);
941
        nNames = nameService.count(TaxonName.class);
942
        Assert.assertEquals("There should be 3 names left in the database ", 3, nNames);
943
        nRelations = service.countSynonyms(true);
944
        //may change with better implementation of countAllRelationships (see #2653)
945
        nRelations = nameService.getAllRelationships(1000, 0).size();
946
        logger.info("number of name relations: " + nRelations);
947
        Assert.assertEquals("There should be no name relationship left in the database", 0, nRelations);
948
    }
949

    
950

    
951
    @Test
952
    @DataSet("TaxonServiceImplTest.testDeleteSynonym.xml")
953
    public final void testDeleteSynonymSynonymTaxonBooleanWithRollback(){
954
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
955
                "HomotypicalGroup","HomotypicalGroup_AUD"};
956

    
957
        int nSynonyms = service.count(Synonym.class);
958
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
959
        int nNames = nameService.count(TaxonName.class);
960
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
961
        int nRelations = service.countSynonyms(true);
962

    
963

    
964
        //may change with better implementation of countAllRelationships (see #2653)
965

    
966
        logger.debug("");
967
        Assert.assertEquals("There should be 2 relationships in the database (the 2 synonym relationship) but no name relationship", 2, nRelations);
968

    
969
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
970
        UUID uuidSynonymName2=UUID.fromString("613f3c93-013e-4ffc-aadc-1c98d71c335e");
971

    
972
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
973
        TaxonName name2 = nameService.load(uuidSynonymName2);
974
        synonym1.getName().addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
975

    
976
        service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
977

    
978
        this.rollback();
979
//		printDataSet(System.out, tableNames);
980
        this.startNewTransaction();
981

    
982
        nSynonyms = service.count(Synonym.class);
983
        Assert.assertEquals("There should still be 2 synonyms left in the database", 2, nSynonyms);
984
        nNames = nameService.count(TaxonName.class);
985
        Assert.assertEquals("There should be 4 names left in the database", 4, nNames);
986
        nRelations = service.countSynonyms(true);
987
        //may change with better implementation of countAllRelationships (see #2653)
988
        Assert.assertEquals("There should be 2 relationship in the database (the 2 synonym relationship) but no name relationship", 2, nRelations);
989

    
990
    }
991

    
992
    @Test
993
    @DataSet("TaxonServiceImplTest.testDeleteSynonym.xml")
994
    public final void testDeleteSynonymSynonymTaxonBooleanWithoutTransaction(){
995
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonName","TaxonName_AUD",
996
                "HomotypicalGroup","HomotypicalGroup_AUD"};
997

    
998
        int nSynonyms = service.count(Synonym.class);
999
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
1000
        int nNames = nameService.count(TaxonName.class);
1001
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
1002
        int nRelations = service.countSynonyms(true);
1003
        //may change with better implementation of countAllRelationships (see #2653)
1004
        Assert.assertEquals("There should be 2 relationship in the database (the 2 synonym relationships) but no name relationship", 2, nRelations);
1005

    
1006
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
1007
        UUID uuidSynonymName2=UUID.fromString("613f3c93-013e-4ffc-aadc-1c98d71c335e");
1008

    
1009
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
1010
        TaxonName name2 = nameService.load(uuidSynonymName2);
1011
        synonym1.getName().addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
1012

    
1013
        service.saveOrUpdate(synonym1);
1014
        nRelations = service.countSynonyms(true);
1015
        Assert.assertEquals("There should be two relationships in the database", 2, nRelations);
1016
        this.setComplete();
1017
        this.endTransaction();
1018

    
1019
//        printDataSet(System.out, tableNames);
1020

    
1021
        //out of wrapping transaction
1022
        service.deleteSynonym(synonym1,  new SynonymDeletionConfigurator());
1023

    
1024
        this.startNewTransaction();
1025

    
1026
        nSynonyms = service.count(Synonym.class);
1027
        Assert.assertEquals("There should still be 1 synonyms left in the database. The rollback on name delete should not lead to rollback in synonym delete.", 1, nSynonyms);
1028
        nNames = nameService.count(TaxonName.class);
1029
        Assert.assertEquals("There should be 4 names left in the database", 4, nNames);
1030
        nRelations = service.countSynonyms(true);
1031
        Assert.assertEquals("There should be no taxon or synonym relationship in the database", 1, nRelations);
1032
        nRelations = nameService.getAllRelationships(1000,0).size();
1033
        Assert.assertEquals("There should be one name relationship in the database", 1, nRelations);
1034

    
1035
    }
1036

    
1037
    @Test
1038
    @DataSet("TaxonServiceImplTest.testInferredSynonyms.xml")
1039
    public void testCreateInferredSynonymy(){
1040

    
1041
        UUID classificationUuid = UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9");
1042
        Classification tree = classificationService.find(classificationUuid);
1043
        UUID taxonUuid = UUID.fromString("bc09aca6-06fd-4905-b1e7-cbf7cc65d783");
1044
        TaxonBase<?> taxonBase =  service.find(taxonUuid);
1045
        List <Synonym> synonyms = service.list(Synonym.class, null, null, null, null);
1046
        assertEquals("Number of synonyms should be 2",2,synonyms.size());
1047
        Taxon taxon = (Taxon)taxonBase;
1048

    
1049
        //synonyms = taxonDao.getAllSynonyms(null, null);
1050
        //assertEquals("Number of synonyms should be 2",2,synonyms.size());
1051
        List<Synonym> inferredSynonyms = service.createInferredSynonyms(taxon, tree, SynonymType.INFERRED_EPITHET_OF(), true);
1052
        assertNotNull("there should be a new synonym ", inferredSynonyms);
1053
        assertEquals ("the name of inferred epithet should be SynGenus lachesis", "SynGenus lachesis syn. sec. Sp. Pl.", inferredSynonyms.get(0).getTitleCache());
1054

    
1055
        inferredSynonyms = service.createInferredSynonyms(taxon, tree, SynonymType.INFERRED_GENUS_OF(), true);
1056
        assertNotNull("there should be a new synonym ", inferredSynonyms);
1057
        assertEquals ("the name of inferred epithet should be SynGenus lachesis", "Acherontia ciprosus syn. sec. Sp. Pl.", inferredSynonyms.get(0).getTitleCache());
1058

    
1059
        inferredSynonyms = service.createInferredSynonyms(taxon, tree, SynonymType.POTENTIAL_COMBINATION_OF(), true);
1060
        assertNotNull("there should be a new synonym ", inferredSynonyms);
1061
        assertEquals ("the name of inferred epithet should be SynGenus lachesis", "SynGenus ciprosus syn. sec. Sp. Pl.", inferredSynonyms.get(0).getTitleCache());
1062
        //assertTrue("set of synonyms should contain an inferred Synonym ", synonyms.contains(arg0))
1063
    }
1064

    
1065
    @Test
1066
    @DataSet("../../database/BlankDataSet.xml")
1067
    public final void testTaxonDeletionConfig(){
1068
        final String[]tableNames = {}
1069
//                "Classification", "Classification_AUD",
1070
//                "TaxonBase","TaxonBase_AUD",
1071
//                "TaxonNode","TaxonNode_AUD",
1072
//                "TaxonName","TaxonName_AUD",
1073
//                "TaxonRelationship", "TaxonRelationship_AUD",
1074
//                "TaxonDescription", "TaxonDescription_AUD",
1075
//                "HomotypicalGroup","HomotypicalGroup_AUD",
1076
//                "PolytomousKey","PolytomousKey_AUD",
1077
//                "PolytomousKeyNode","PolytomousKeyNode_AUD",
1078
//                "Media","Media_AUD",
1079
//                "DescriptiveDataSet","DescriptiveDataSet_AUD",
1080
//                "DescriptionElementBase","DescriptionElementBase_AUD",
1081
//        		"DeterminationEvent","DeterminationEvent_AUD",
1082
//        		"SpecimenOrObservationBase","SpecimenOrObservationBase_AUD"}
1083
        ;
1084

    
1085
        UUID uuidParent=UUID.fromString("b5271d4f-e203-4577-941f-00d76fa9f4ca");
1086
        UUID uuidChild1=UUID.fromString("326167f9-0b97-4e7d-b1bf-4ca47b82e21e");
1087
        UUID uuidSameAs=UUID.fromString("c2bb0f01-f2dd-43fb-ba12-2a85727ccb8d");
1088
        commitAndStartNewTransaction(tableNames);
1089
        Taxon testTaxon =getTestTaxon();
1090
       // service.save(testTaxon);
1091
        commitAndStartNewTransaction(tableNames);
1092
        int nTaxa = service.count(Taxon.class);
1093

    
1094
        Assert.assertEquals("There should be 4 taxa in the database", 4, nTaxa);
1095
        Taxon parent = (Taxon)service.find(GENUS_UUID);
1096
        Assert.assertNotNull("Parent taxon should exist", parent);
1097
        Taxon child1 = (Taxon)service.find(SPECIES1_UUID);
1098
        Assert.assertNotNull("Child taxon should exist", child1);
1099
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1100
        config.setDeleteTaxonNodes(false);
1101
        config.setDeleteMisappliedNamesAndInvalidDesignations(false);
1102
        //try {
1103
            //commitAndStartNewTransaction(tableNames);
1104

    
1105
        DeleteResult result = service.deleteTaxon(child1.getUuid(), config, null);
1106
        if (result.isOk()){
1107
            Assert.fail("Delete should throw an error as long as name is used in classification.");
1108
        }
1109

    
1110
        nTaxa = service.count(Taxon.class);
1111
        Assert.assertEquals("There should be 4 taxa in the database", 4, nTaxa);
1112
        child1 = (Taxon)service.find(SPECIES1_UUID);
1113
        Assert.assertNotNull("Child taxon should exist", child1);
1114
        Assert.assertEquals("Child should belong to 1 node", 1, child1.getTaxonNodes().size());
1115

    
1116
        TaxonNode node = child1.getTaxonNodes().iterator().next();
1117
        child1.addSource(IdentifiableSource.NewInstance(OriginalSourceType.Import));
1118

    
1119
        SpecimenOrObservationBase<?> identifiedUnit = DerivedUnit.NewInstance(SpecimenOrObservationType.DerivedUnit);
1120
        DeterminationEvent.NewInstance(child1, identifiedUnit);
1121
        //UUID eventUUID = eventService.save(determinationEvent);
1122
        UUID identifiedUnitUUID = occurenceService.save(identifiedUnit).getUuid();
1123

    
1124

    
1125
        TaxonNode parentNode = node.getParent();
1126
        parentNode =CdmBase.deproxy(parentNode, TaxonNode.class);
1127
        parentNode.deleteChildNode(node);
1128
        nodeService.save(parentNode);
1129
        //commitAndStartNewTransaction(tableNames);
1130

    
1131
       // try {
1132

    
1133
       result = service.deleteTaxon(child1
1134
    		   .getUuid(), config, null);
1135
       if (result.isOk()){
1136
           	Assert.fail("Delete should throw an exception because of the determination event");
1137
       }
1138

    
1139

    
1140

    
1141
        //determinationEvent = (DeterminationEvent)eventService.load(eventUUID);
1142
        commitAndStartNewTransaction(tableNames);
1143
        identifiedUnit = occurenceService.load(identifiedUnitUUID);
1144

    
1145
        occurenceService.delete(identifiedUnit);
1146

    
1147
        commitAndStartNewTransaction(tableNames);
1148
        child1 = (Taxon)service.find(SPECIES1_UUID);
1149

    
1150
        assertEquals(0, child1.getTaxonNodes().size());
1151
       // try {
1152

    
1153
         result = service.deleteTaxon(child1.getUuid(), config, null);
1154

    
1155
         if (!result.isOk()){
1156
            Assert.fail("Delete should not throw an exception anymore");
1157
         }
1158

    
1159
        nTaxa = service.count(Taxon.class);
1160
        Assert.assertEquals("There should be 3 taxa in the database", 3, nTaxa);
1161

    
1162
        config.setDeleteTaxonNodes(true);
1163
        Taxon child2 =(Taxon) service.find(SPECIES2_UUID);
1164

    
1165
       // try {
1166
        result = service.deleteTaxon(child2.getUuid(), config, child2.getTaxonNodes().iterator().next().getClassification().getUuid());
1167
        if (!result.isOk()){
1168
            Assert.fail("Delete should not throw an exception");
1169
        }
1170

    
1171

    
1172
        //service.find(uuid);
1173

    
1174
        nTaxa = service.count(Taxon.class);
1175
        Assert.assertEquals("There should be 2 taxa in the database",2, nTaxa);
1176
//		nNames = nameService.count(TaxonName.class);
1177
//		Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
1178
//		int nRelations = service.countAllRelationships();
1179
//		Assert.assertEquals("There should be no relationship left in the database", 0, nRelations);
1180
    }
1181

    
1182

    
1183
    @Test
1184
    @DataSet(value="../../database/BlankDataSet.xml")
1185
    public final void testDeleteTaxon(){
1186

    
1187
        //create a small classification
1188

    
1189
        Taxon testTaxon = getTestTaxon();
1190

    
1191
        service.save(testTaxon).getUuid();
1192

    
1193
        Taxon speciesTaxon = (Taxon)service.find(SPECIES1_UUID);
1194
        Iterator<TaxonDescription> descriptionIterator = speciesTaxon.getDescriptions().iterator();
1195
        UUID descrUUID = null;
1196
        UUID descrElementUUID = null;
1197
        if (descriptionIterator.hasNext()){
1198
            TaxonDescription descr = descriptionIterator.next();
1199
            descrUUID = descr.getUuid();
1200
            descrElementUUID = descr.getElements().iterator().next().getUuid();
1201
        }
1202
        IBotanicalName taxonName = nameService.find(SPECIES1_NAME_UUID);
1203
        assertNotNull(taxonName);
1204

    
1205
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1206
        config.setDeleteNameIfPossible(false);
1207

    
1208

    
1209

    
1210
       // try {
1211

    
1212
        DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1213
        if (!result.isOk()){
1214
        	Assert.fail();
1215
        }
1216
        commitAndStartNewTransaction(null);
1217

    
1218
        taxonName = nameService.find(SPECIES1_NAME_UUID);
1219
        Taxon taxon = (Taxon)service.find(SPECIES1_UUID);
1220

    
1221
        //descriptionService.find(descrUUID);
1222
        assertNull(descriptionService.find(descrUUID));
1223
        assertNull(descriptionService.getDescriptionElementByUuid(descrElementUUID));
1224
        //assertNull(synName);
1225
        assertNotNull(taxonName);
1226
        assertNull(taxon);
1227
        config.setDeleteNameIfPossible(true);
1228
        Taxon newTaxon = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES()), null);
1229
        service.save(newTaxon);
1230
        result = service.deleteTaxon(newTaxon.getUuid()
1231
        		, config, null);
1232
        if (!result.isOk()){
1233
        	Assert.fail();
1234
        }
1235

    
1236

    
1237
    }
1238

    
1239
    @Test
1240
    @DataSet(value="../../database/BlankDataSet.xml")
1241
    public final void testDeleteTaxonWithAnnotations(){
1242

    
1243
        //create a small classification
1244

    
1245
        Taxon testTaxon = getTestTaxon();
1246

    
1247
        service.save(testTaxon).getUuid();
1248

    
1249
        Taxon speciesTaxon = (Taxon)service.find(SPECIES1_UUID);
1250
        Iterator<TaxonDescription> descriptionIterator = speciesTaxon.getDescriptions().iterator();
1251
        UUID descrUUID = null;
1252
        UUID descrElementUUID = null;
1253
        if (descriptionIterator.hasNext()){
1254
            TaxonDescription descr = descriptionIterator.next();
1255
            descrUUID = descr.getUuid();
1256
            descrElementUUID = descr.getElements().iterator().next().getUuid();
1257
        }
1258
        IBotanicalName taxonName = nameService.find(SPECIES1_NAME_UUID);
1259
        assertNotNull(taxonName);
1260

    
1261
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1262
        config.setDeleteNameIfPossible(false);
1263
        Annotation annotation = Annotation.NewDefaultLanguageInstance("test");
1264
        speciesTaxon.addAnnotation(annotation);
1265

    
1266

    
1267
       // try {
1268

    
1269
        DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1270
        if (!result.isOk()){
1271
            Assert.fail();
1272
        }
1273
        commitAndStartNewTransaction(null);
1274

    
1275
        taxonName = nameService.find(SPECIES1_NAME_UUID);
1276
        Taxon taxon = (Taxon)service.find(SPECIES1_UUID);
1277

    
1278
        //descriptionService.find(descrUUID);
1279
        assertNull(descriptionService.find(descrUUID));
1280
        assertNull(descriptionService.getDescriptionElementByUuid(descrElementUUID));
1281
        //assertNull(synName);
1282
        assertNotNull(taxonName);
1283
        assertNull(taxon);
1284
        config.setDeleteNameIfPossible(true);
1285
        Taxon newTaxon = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES()), null);
1286
        service.save(newTaxon);
1287
        result = service.deleteTaxon(newTaxon.getUuid()
1288
                , config, null);
1289
        if (!result.isOk()){
1290
            Assert.fail();
1291
        }
1292

    
1293

    
1294
    }
1295

    
1296
    @Test
1297
    @DataSet(value="../../database/BlankDataSet.xml")
1298
    public final void testDeleteTaxonUsedInTaxonRelation(){
1299

    
1300
        //create a small classification
1301
        Taxon testTaxon = getTestTaxon();
1302

    
1303
        service.save(testTaxon).getUuid();
1304

    
1305
        Taxon speciesTaxon = (Taxon)service.find(SPECIES1_UUID);
1306
        Taxon speciesTaxon2 = (Taxon)service.find(SPECIES2_UUID);
1307
        speciesTaxon.addTaxonRelation(speciesTaxon2, TaxonRelationshipType.MISAPPLIED_NAME_FOR(), null, null);
1308

    
1309
        IBotanicalName taxonName = nameService.find(SPECIES1_NAME_UUID);
1310
        assertNotNull(taxonName);
1311

    
1312
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1313
        config.setDeleteNameIfPossible(false);
1314
        config.setDeleteTaxonRelationships(false);
1315

    
1316

    
1317
       // try {
1318

    
1319
        DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1320
        if (result.isOk()){
1321
            Assert.fail();
1322
        }
1323
        commitAndStartNewTransaction(null);
1324

    
1325
        taxonName = nameService.find(SPECIES1_NAME_UUID);
1326
        Taxon taxon = (Taxon)service.find(SPECIES1_UUID);
1327

    
1328

    
1329
        assertNotNull(taxonName);
1330
        assertNotNull(taxon);
1331

    
1332

    
1333
        config.setDeleteNameIfPossible(false);
1334
        config.setDeleteTaxonRelationships(true);
1335

    
1336

    
1337
       // try {
1338

    
1339
       result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1340
        if (!result.isOk()){
1341
            Assert.fail();
1342
        }
1343
        commitAndStartNewTransaction(null);
1344

    
1345

    
1346
        config.setDeleteNameIfPossible(true);
1347
        Taxon newTaxon = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES()), null);
1348
        service.save(newTaxon);
1349
        result = service.deleteTaxon(newTaxon.getUuid()
1350
                , config, null);
1351
        if (!result.isOk()){
1352
            Assert.fail();
1353
        }
1354

    
1355

    
1356
    }
1357

    
1358
    @Test
1359
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="../../database/BlankDataSet.xml")
1360
    public final void testDeleteTaxonDeleteSynonymRelations(){
1361

    
1362
    	 final String[]tableNames = {
1363
                 "Classification", "Classification_AUD",
1364
                 "TaxonBase","TaxonBase_AUD",
1365
                 "TaxonNode","TaxonNode_AUD",
1366
                 "TaxonName","TaxonName_AUD"};
1367
    	 commitAndStartNewTransaction(tableNames);
1368
        //create a small classification
1369
        Taxon testTaxon = getTestTaxon();
1370

    
1371
        service.save(testTaxon).getUuid();
1372

    
1373
        Taxon speciesTaxon = (Taxon)service.find(SPECIES2_UUID);
1374

    
1375
        Synonym synonym = speciesTaxon.getSynonyms().iterator().next();
1376
        UUID synonymUuid = synonym.getUuid();
1377
        service.countSynonyms(true);
1378

    
1379
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1380
        config.setDeleteSynonymsIfPossible(false);
1381

    
1382

    
1383
        DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1384
        if (!result.isOk()){
1385
        	Assert.fail();
1386
        }
1387
        commitAndStartNewTransaction(null);
1388

    
1389
        Taxon taxon = (Taxon)service.find(SPECIES2_UUID);
1390
        assertNull("The deleted taxon should no longer exist", taxon);
1391

    
1392
        Synonym syn = (Synonym)service.find(synonymUuid);
1393
        assertNotNull("The synonym should still exist since DeleteSynonymsIfPossible was false", service.find(synonymUuid));
1394
        assertNull("The synonym should not be attached to an accepted taxon anymore", syn.getAcceptedTaxon());
1395
    }
1396

    
1397

    
1398
    @Test
1399
    @DataSet(value="../../database/BlankDataSet.xml")
1400
    public final void testDeleteTaxonNameUsedInOtherContext(){
1401

    
1402
        //create a small classification
1403
        Taxon testTaxon = getTestTaxon();
1404

    
1405
        service.save(testTaxon).getUuid();
1406

    
1407
        Taxon speciesTaxon = (Taxon)service.find(SPECIES1_UUID);
1408

    
1409
        IBotanicalName taxonName = nameService.find(SPECIES1_NAME_UUID);
1410
        assertNotNull(taxonName);
1411
        TaxonName fromName = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
1412
        taxonName.addRelationshipFromName(fromName, NameRelationshipType.VALIDATED_BY_NAME(), null);
1413
        nameService.save(fromName);
1414

    
1415
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1416
        config.setDeleteNameIfPossible(true);
1417
        DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1418
        if (!result.isOk()){
1419
        	Assert.fail();
1420
        }
1421
        commitAndStartNewTransaction(null);
1422

    
1423
        taxonName = nameService.find(SPECIES1_NAME_UUID);
1424
        Taxon taxon = (Taxon)service.find(SPECIES1_UUID);
1425
        //because of the namerelationship the name cannot be deleted
1426
        assertNotNull(taxonName);
1427
        assertNull(taxon);
1428

    
1429
    }
1430

    
1431
    @Test
1432
    @DataSet(value="../../database/BlankDataSet.xml")
1433
    public final void testDeleteTaxonNameUsedInTwoClassificationsDeleteAllNodes(){
1434
        commitAndStartNewTransaction(null);
1435
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1436
        //create a small classification
1437
        Taxon testTaxon = getTestTaxon();
1438

    
1439
        UUID uuid = service.save(testTaxon).getUuid();
1440
        //BotanicalName name = nameService.find(uuid);
1441
        Set<TaxonNode> nodes = testTaxon.getTaxonNodes();
1442
        TaxonNode node = nodes.iterator().next();
1443
        List<TaxonNode> childNodes = node.getChildNodes();
1444
        TaxonNode childNode = childNodes.iterator().next();
1445
        UUID childUUID = childNode.getTaxon().getUuid();
1446
        Classification secondClassification = getTestClassification("secondClassification");
1447

    
1448
        secondClassification.addChildTaxon(testTaxon, null, null);
1449
        //delete the taxon in all classifications
1450
        config.setDeleteInAllClassifications(true);
1451
       DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, null);
1452
       if (!result.isOk()){
1453
        	Assert.fail();
1454
        }
1455
        commitAndStartNewTransaction(null);
1456
        Taxon tax = (Taxon)service.find(uuid);
1457
        assertNull(tax);
1458
        Taxon childTaxon = (Taxon)service.find(childUUID);
1459
        assertNull(tax);
1460
        commitAndStartNewTransaction(null);
1461

    
1462

    
1463

    
1464

    
1465

    
1466
    }
1467

    
1468
    @Test
1469
    @DataSet(value="../../database/BlankDataSet.xml")
1470
    public final void testDeleteTaxonNameUsedInTwoClassificationsDoNotDeleteAllNodes(){
1471
        // delete the taxon only in second classification, this should delete only the nodes, not the taxa
1472
        Taxon testTaxon = getTestTaxon();
1473
        UUID uuid = service.save(testTaxon).getUuid();
1474
        Classification secondClassification = getTestClassification("secondClassification");
1475
        Set<TaxonNode> nodes = testTaxon.getTaxonNodes();
1476
        TaxonNode node = nodes.iterator().next();
1477
        List<TaxonNode> childNodes = node.getChildNodes();
1478
        TaxonNode childNode = childNodes.iterator().next();
1479
        UUID childUUID = childNode.getTaxon().getUuid();
1480
        childNode = secondClassification.addChildTaxon(testTaxon, null, null);
1481
        UUID childNodeUUID = childNode.getUuid();
1482

    
1483
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1484
        config.setDeleteInAllClassifications(false);
1485
       //     try {
1486
       DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, secondClassification.getUuid());
1487
/*                Assert.fail("The taxon should not be deletable because it is used in a second classification and the configuration is set to deleteInAllClassifications = false");
1488
            } catch (DataChangeNoRollbackException e) {
1489
                logger.debug(e.getMessage());
1490
            }
1491
  */
1492

    
1493
       if (result.isOk()){
1494
           	Assert.fail("The taxon should not be deletable because it is used in a second classification and the configuration is set to deleteInAllClassifications = false");
1495
        }
1496

    
1497
        //commitAndStartNewTransaction(null);
1498
        Taxon tax = (Taxon)service.find(uuid);
1499
        assertNotNull(tax);
1500
        Taxon childTaxon = (Taxon)service.find(childUUID);
1501
        assertNotNull(tax);
1502
        node = nodeService.find(childNodeUUID);
1503
        assertNull(node);
1504
    }
1505

    
1506
    @Test
1507
    @DataSet(value="../../database/BlankDataSet.xml")
1508
    public final void testTaxonNodeDeletionConfiguratorMoveToParent(){
1509
        //test childHandling MOVE_TO_PARENT:
1510
        Taxon testTaxon = getTestTaxon();
1511
        UUID uuid = service.save(testTaxon).getUuid();
1512

    
1513
        Taxon topMost = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.FAMILY()), null);
1514

    
1515
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1516
        TaxonNode node =nodes.next();
1517
        Classification classification = node.getClassification();
1518
        classification.addParentChild(topMost, testTaxon, null, null);
1519
        UUID topMostUUID = service.save(topMost).getUuid();
1520

    
1521
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1522
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.MOVE_TO_PARENT);
1523

    
1524

    
1525
        DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, classification.getUuid());
1526
        if(!result.isOk()){
1527
         	Assert.fail();
1528
       	}
1529

    
1530
        commitAndStartNewTransaction(null);
1531
        Taxon tax = (Taxon)service.find(uuid);
1532
        assertNull(tax);
1533
        tax = (Taxon)service.find(topMostUUID);
1534
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1535
        assertNotNull(topMostNodes);
1536
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1537
        nodes = topMostNodes.iterator();
1538
        TaxonNode topMostNode = nodes.next();
1539
        int size = topMostNode.getChildNodes().size();
1540

    
1541
        assertEquals(2, size);
1542
    }
1543

    
1544
    @Test
1545
    @DataSet(value="../../database/BlankDataSet.xml")
1546
    public final void testTaxonNodeDeletionConfiguratorDeleteChildren(){
1547
        //test childHandling DELETE:
1548
        Taxon testTaxon = getTestTaxon();
1549
        UUID uuid = service.save(testTaxon).getUuid();
1550

    
1551
        Taxon topMost = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.FAMILY()), null);
1552

    
1553
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1554
        TaxonNode node =nodes.next();
1555
        UUID taxonNodeUUID = node.getUuid();
1556
        Classification classification = node.getClassification();
1557
        classification.addParentChild(topMost, testTaxon, null, null);
1558
        UUID topMostUUID = service.save(topMost).getUuid();
1559

    
1560
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1561
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.DELETE);
1562

    
1563
       // try {
1564
        DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, testTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1565
        if(!result.isOk()){
1566
         	Assert.fail();
1567
       	}
1568
        commitAndStartNewTransaction(null);
1569
        Taxon tax = (Taxon)service.find(uuid);
1570
        assertNull(tax);
1571
        tax = (Taxon)service.find(topMostUUID);
1572
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1573
        assertNotNull(topMostNodes);
1574
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1575
        nodes = topMostNodes.iterator();
1576
        TaxonNode topMostNode = nodes.next();
1577
        int size = topMostNode.getChildNodes().size();
1578
        node = nodeService.find(taxonNodeUUID);
1579
        assertNull(node);
1580
        assertEquals(0, size);
1581
    }
1582

    
1583

    
1584
    @Test
1585
    @DataSet(value="../../database/BlankDataSet.xml")
1586
    public final void testTaxonDeletionConfiguratorDeleteMarker(){
1587
        //test childHandling DELETE:
1588
        Taxon testTaxon = getTestTaxon();
1589
        UUID uuid = service.save(testTaxon).getUuid();
1590

    
1591
        Taxon topMost = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.FAMILY()), null);
1592

    
1593
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1594
        TaxonNode node =nodes.next();
1595
        Classification classification = node.getClassification();
1596
        classification.addParentChild(topMost, testTaxon, null, null);
1597
        UUID topMostUUID = service.save(topMost).getUuid();
1598
        Marker marker = Marker.NewInstance(testTaxon, true, MarkerType.IS_DOUBTFUL());
1599
        testTaxon.addMarker(marker);
1600
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1601
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.DELETE);
1602

    
1603
        DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, node.getClassification().getUuid());
1604

    
1605
        if(!result.isOk()){
1606
         	Assert.fail();
1607
       	}
1608
        commitAndStartNewTransaction(null);
1609
        Taxon tax = (Taxon)service.find(uuid);
1610
        assertNull(tax);
1611
        tax = (Taxon)service.find(topMostUUID);
1612
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1613
        assertNotNull(topMostNodes);
1614
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1615
        nodes = topMostNodes.iterator();
1616
        TaxonNode topMostNode = nodes.next();
1617
        int size = topMostNode.getChildNodes().size();
1618

    
1619
        assertEquals(0, size);
1620
    }
1621

    
1622

    
1623
    @Test
1624
    @DataSet(value="../../database/BlankDataSet.xml")
1625
    public final void testTaxonDeletionConfiguratorTaxonWithMisappliedName(){
1626

    
1627
        Taxon testTaxon = getTestTaxon();
1628
        UUID uuid = service.save(testTaxon).getUuid();
1629

    
1630
        Taxon misappliedName = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.GENUS()), null);
1631

    
1632
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1633
        TaxonNode node =nodes.next();
1634
        testTaxon.addMisappliedName(misappliedName, null, null);
1635
        UUID misappliedNameUUID = service.save(misappliedName).getUuid();
1636

    
1637
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1638
        config.setDeleteMisappliedNamesAndInvalidDesignations(true);
1639

    
1640
        DeleteResult result  = service.deleteTaxon(testTaxon.getUuid(), config, node.getClassification().getUuid());
1641
        if(!result.isOk()){
1642
         	Assert.fail();
1643
       	}
1644
        commitAndStartNewTransaction(null);
1645
        Taxon tax = (Taxon)service.find(uuid);
1646
        assertNull(tax);
1647
        tax = (Taxon)service.find(misappliedNameUUID);
1648
        //TODO: is that correct or should it be deleted because there is no relation to anything
1649
        assertNull(tax);
1650

    
1651
    }
1652
    @Test
1653
    @DataSet(value="../../database/BlankDataSet.xml")
1654
    public final void testTaxonDeletionConfiguratorTaxonWithMisappliedNameDoNotDelete(){
1655

    
1656
        Taxon testTaxon = getTestTaxon();
1657
        UUID uuid = service.save(testTaxon).getUuid();
1658

    
1659
        Taxon misappliedName = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.GENUS()), null);
1660

    
1661
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1662
        TaxonNode node =nodes.next();
1663
        testTaxon.addMisappliedName(misappliedName, null, null);
1664
        UUID misappliedNameUUID = service.save(misappliedName).getUuid();
1665

    
1666
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1667
        config.setDeleteMisappliedNamesAndInvalidDesignations(false);
1668

    
1669
        DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, node.getClassification().getUuid());
1670
        if(!result.isOk()){
1671
         	Assert.fail();
1672
       	}
1673
        commitAndStartNewTransaction(null);
1674
        Taxon tax = (Taxon)service.find(uuid);
1675
        assertNull(tax);
1676
        tax = (Taxon)service.find(misappliedNameUUID);
1677
        //TODO: is that correct or should it be deleted because there is no relation to anything
1678
        assertNotNull(tax);
1679

    
1680
    }
1681

    
1682
    @Test
1683
    @DataSet(value="../../database/BlankDataSet.xml")
1684
    public final void testTaxonDeletionConfiguratorTaxonMisappliedName(){
1685

    
1686
        Taxon testTaxon = getTestTaxon();
1687
        UUID uuid = service.save(testTaxon).getUuid();
1688

    
1689
        Taxon misappliedNameTaxon = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(Rank.GENUS()), null);
1690

    
1691
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1692
        TaxonNode node =nodes.next();
1693
        testTaxon.addMisappliedName(misappliedNameTaxon, null, null);
1694
        UUID misappliedNameUUID = service.save(misappliedNameTaxon).getUuid();
1695
        misappliedNameTaxon = (Taxon)service.find(misappliedNameUUID);
1696
        UUID misNameUUID = misappliedNameTaxon.getName().getUuid();
1697

    
1698
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1699

    
1700

    
1701
       // try {
1702
            service.deleteTaxon(misappliedNameTaxon.getUuid(), config,null);
1703
       // } catch (DataChangeNoRollbackException e) {
1704
         //   e.printStackTrace();
1705

    
1706
        //}
1707

    
1708
        commitAndStartNewTransaction(null);
1709
        Taxon tax = (Taxon)service.find(uuid);
1710
        assertNotNull(tax);
1711
        tax = (Taxon)service.find(misappliedNameUUID);
1712
        IBotanicalName name = nameService.find(misNameUUID);
1713

    
1714
        assertNull(tax);
1715
        assertNull(name);
1716

    
1717
    }
1718

    
1719
    @Test
1720
    @DataSet(value="../../database/BlankDataSet.xml")
1721
    public final void testLlistIncludedTaxa(){
1722
    	Reference citation = null;
1723
    	String microcitation = null;
1724

    
1725
    	//Data
1726
    	Classification cl1 = Classification.NewInstance("testClassification1");
1727
    	Classification cl2 = Classification.NewInstance("testClassification2");
1728
    	Classification cl3 = Classification.NewInstance("testClassification3");
1729

    
1730
    	classificationService.save(cl1);
1731
        classificationService.save(cl2);
1732
        classificationService.save(cl3);
1733

    
1734
    	Taxon c1Genus = Taxon.NewInstance(null, null);c1Genus.setUuid(UUID.fromString("daa24f6f-7e38-4668-b385-10c789212e4e"));
1735
    	Taxon c1Species = Taxon.NewInstance(null, null);c1Species.setUuid(UUID.fromString("1c1d0566-67d0-4806-bf23-ecf55f4b9118"));
1736
    	Taxon c1SubSpecies1 = Taxon.NewInstance(null, null);c1SubSpecies1.setUuid(UUID.fromString("96ae2fad-76df-429f-b179-42e00838fea4"));
1737
    	Taxon c1SubSpecies2 = Taxon.NewInstance(null, null);c1SubSpecies2.setUuid(UUID.fromString("5d3f6147-ca72-40e0-be8a-6c835a09a579"));
1738
    	TaxonNode c1childNodeSpecies1 = cl1.addParentChild(c1Genus, c1Species, null, null);
1739
    	nodeService.saveOrUpdate(c1childNodeSpecies1);
1740
    	TaxonNode c1childNodeSubSpecies1 =cl1.addParentChild(c1Species, c1SubSpecies1, null, null);
1741
    	nodeService.saveOrUpdate(c1childNodeSubSpecies1);
1742
    	TaxonNode c1childNodeSubSpecies2 =cl1.addParentChild(c1Species, c1SubSpecies2, null, null);
1743
    	nodeService.saveOrUpdate(c1childNodeSubSpecies2);
1744

    
1745
    	Taxon c2Genus = Taxon.NewInstance(null, null);c2Genus.setUuid(UUID.fromString("ed0ec006-3ac8-4a12-ae13-fdf2a13dedbe"));
1746
    	Taxon c2Species = Taxon.NewInstance(null, null);c2Species.setUuid(UUID.fromString("1027eb18-1c26-450e-a299-981b775ebc3c"));
1747
    	Taxon c2SubSpecies1 = Taxon.NewInstance(null, null);c2SubSpecies1.setUuid(UUID.fromString("61f039c8-01f3-4f5d-8e16-1602139774e7"));
1748
    	Taxon c2SubSpecies2 = Taxon.NewInstance(null, null);c2SubSpecies2.setUuid(UUID.fromString("2ed6b6f8-05f9-459a-a075-2bca57e3013e"));
1749
    	TaxonNode c2childNodeSpecies1 = cl2.addParentChild(c2Genus, c2Species, null, null);
1750
    	nodeService.saveOrUpdate(c2childNodeSpecies1);
1751
    	TaxonNode c2childNodeSubSpecies1 = cl2.addParentChild(c2Species, c2SubSpecies1, null, null);
1752
    	nodeService.saveOrUpdate(c2childNodeSubSpecies1);
1753
    	TaxonNode c2childNodeSubSpecies2 = cl2.addParentChild(c2Species, c2SubSpecies2, null, null);
1754
    	nodeService.saveOrUpdate(c2childNodeSubSpecies2);
1755

    
1756
    	Taxon c3Genus = Taxon.NewInstance(null, null);c3Genus.setUuid(UUID.fromString("407dfc8d-7a4f-4370-ada4-76c1a8279d1f"));
1757
    	Taxon c3Species = Taxon.NewInstance(null, null);c3Species.setUuid(UUID.fromString("b6d34fc7-4aa7-41e5-b633-86f474edbbd5"));
1758
    	Taxon c3SubSpecies1 = Taxon.NewInstance(null, null);c3SubSpecies1.setUuid(UUID.fromString("01c07585-a422-40cd-9339-a74c56901d9f"));
1759
    	Taxon c3SubSpecies2 = Taxon.NewInstance(null, null);c3SubSpecies2.setUuid(UUID.fromString("390c8e23-e05f-4f89-b417-50cf080f4c91"));
1760
    	TaxonNode c3childNodeSpecies1 = cl3.addParentChild(c3Genus, c3Species, null, null);
1761
    	nodeService.saveOrUpdate(c3childNodeSpecies1);
1762
    	TaxonNode c3childNodeSubSpecies1 = cl3.addParentChild(c3Species, c3SubSpecies1, null, null);
1763
    	nodeService.saveOrUpdate(c3childNodeSubSpecies1);
1764
    	TaxonNode c3childNodeSubSpecies2 = cl3.addParentChild(c3Species, c3SubSpecies2, null, null);
1765
    	nodeService.saveOrUpdate(c3childNodeSubSpecies2);
1766

    
1767

    
1768

    
1769
      	Taxon c4Genus = Taxon.NewInstance(null, null);c4Genus.setUuid(UUID.fromString("bfd6bbdd-0116-4ab2-a781-9316224aad78"));
1770
    	Taxon c4Species = Taxon.NewInstance(null, null);c4Species.setUuid(UUID.fromString("9347a3d9-5ece-4d64-9035-e8aaf5d3ee02"));
1771
    	Taxon c4SubSpecies = Taxon.NewInstance(null, null);c4SubSpecies.setUuid(UUID.fromString("777aabbe-4c3a-449c-ab99-a91f2fec9f07"));
1772

    
1773
    	TaxonRelationship rel = c1Species.addTaxonRelation(c2Species, TaxonRelationshipType.CONGRUENT_TO(), citation, microcitation);
1774
    	rel.setDoubtful(true);
1775
    	c1Species.addTaxonRelation(c4Species, TaxonRelationshipType.INCLUDES(), citation, microcitation);
1776
    	c2Species.addTaxonRelation(c1SubSpecies2, TaxonRelationshipType.INCLUDES(), citation, microcitation);
1777

    
1778
    	service.saveOrUpdate(c1Species);
1779
       	service.saveOrUpdate(c2Species);
1780
       	service.save(c4Species);
1781

    
1782
    	//Tests
1783
       	//default starting at species 1
1784
       	IncludedTaxaDTO dto = service.listIncludedTaxa(c1Species.getUuid(), new IncludedTaxonConfiguration(null, true, false));
1785
    	Assert.assertNotNull("IncludedTaxaDTO", dto);
1786
    	Assert.assertEquals("Result should contain 7 taxa: c1Species", 7, dto.getIncludedTaxa().size());
1787
    	Assert.assertNotNull("date should not be null", dto.getDate());
1788
//    	Assert.assertTrue(dto.contains(taxonUuid));
1789
        //same without doubtful
1790
    	dto = service.listIncludedTaxa(c1Species.getUuid(), new IncludedTaxonConfiguration(null, false, false));
1791
    	Assert.assertEquals(4, dto.getIncludedTaxa().size());
1792

    
1793
    	//other example starting at Genus2
1794
    	dto = service.listIncludedTaxa(c2Genus.getUuid(), new IncludedTaxonConfiguration(null, true, false));
1795
    	Assert.assertEquals(8, dto.getIncludedTaxa().size());
1796
    	//same without doubtful
1797
    	dto = service.listIncludedTaxa(c2Genus.getUuid(), new IncludedTaxonConfiguration(null, false, false));
1798
    	Assert.assertEquals(5, dto.getIncludedTaxa().size());
1799

    
1800
    	//only congruent
1801
    	dto = service.listIncludedTaxa(c1Species.getUuid(), new IncludedTaxonConfiguration(null, true, true));
1802
    	Assert.assertEquals(2, dto.getIncludedTaxa().size());
1803
    	//same without doubtful
1804
    	dto = service.listIncludedTaxa(c1Species.getUuid(), new IncludedTaxonConfiguration(null, false, true));
1805
    	Assert.assertEquals(1, dto.getIncludedTaxa().size());
1806
    }
1807

    
1808
    @Test
1809
    public void testDeleteDescriptions(){
1810
    	try {
1811
			createTestDataSet();
1812
		} catch (FileNotFoundException e) {
1813
			// TODO Auto-generated catch block
1814
			e.printStackTrace();
1815
		}
1816
    	TaxonDescription description = TaxonDescription.NewInstance(taxWithoutSyn);
1817
    	SpecimenOrObservationBase<IIdentifiableEntityCacheStrategy<FieldUnit>> specimen = FieldUnit.NewInstance();
1818
    	UUID uuid = occurenceService.saveOrUpdate(specimen);
1819
    	DescriptionElementBase element = IndividualsAssociation.NewInstance(specimen);
1820
    	description.addElement(element);
1821
    	service.saveOrUpdate(taxWithoutSyn);
1822

    
1823

    
1824
    	Taxon tax = (Taxon)service.find(uuidTaxWithoutSyn);
1825
    	Set<TaxonDescription> descr =  tax.getDescriptions();
1826
    	assertEquals(1, descr.size());
1827
    	description = descr.iterator().next();
1828
    	UUID uuidDescr = description.getUuid();
1829
    	UUID uuidDescEl = description.getElements().iterator().next().getUuid();
1830

    
1831
    	descriptionService.deleteDescription(description);
1832
    	service.saveOrUpdate(tax);
1833

    
1834
    	description = (TaxonDescription) descriptionService.find(uuidDescr);
1835
    	specimen = occurenceService.find(uuid);
1836
    	assertNull(description);
1837
    	DeleteResult result = occurenceService.delete(specimen);
1838
    	assertTrue(result.isOk());
1839

    
1840
    }
1841

    
1842
    @Test
1843
    public void testRemoveDescriptionsFromTaxa(){
1844
        try {
1845
            createTestDataSet();
1846
        } catch (FileNotFoundException e) {
1847
            // TODO Auto-generated catch block
1848
            e.printStackTrace();
1849
        }
1850
        TaxonDescription description = TaxonDescription.NewInstance(taxWithoutSyn);
1851
        SpecimenOrObservationBase<IIdentifiableEntityCacheStrategy<FieldUnit>> specimen = FieldUnit.NewInstance();
1852
        UUID uuid = occurenceService.saveOrUpdate(specimen);
1853
        DescriptionElementBase element = IndividualsAssociation.NewInstance(specimen);
1854
        description.addElement(element);
1855
        service.saveOrUpdate(taxWithoutSyn);
1856

    
1857

    
1858
        Taxon tax = (Taxon)service.find(uuidTaxWithoutSyn);
1859
        Set<TaxonDescription> descr =  tax.getDescriptions();
1860
        assertEquals(1, descr.size());
1861
        description = descr.iterator().next();
1862
        UUID uuidDescr = description.getUuid();
1863

    
1864

    
1865
        tax.removeDescription(description, true);
1866
        service.saveOrUpdate(tax);
1867

    
1868
        description = (TaxonDescription) descriptionService.find(uuidDescr);
1869
        specimen = occurenceService.find(uuid);
1870
        assertNotNull(description);
1871
        DeleteResult result = occurenceService.delete(specimen);
1872
        assertTrue(result.isOk());
1873

    
1874
    }
1875

    
1876

    
1877
    @Override
1878
    public void createTestDataSet() throws FileNotFoundException {
1879
    	Rank rank = Rank.SPECIES();
1880

    
1881
        taxWithoutSyn = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test1", null, null, null, null, null, null, null), null);
1882
        taxWithSyn = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test3", null, null, null, null, null, null, null), null);
1883
        tax2WithSyn = Taxon.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test5", null, null, null, null, null, null, null), null);
1884
        synonym = Synonym.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test2", null, null, null, null, null, null, null), null);
1885
        synonym2 = Synonym.NewInstance(TaxonNameFactory.NewBotanicalInstance(rank, "Test4", null, null, null, null, null, null, null), null);
1886
        synonym2.getName().setHomotypicalGroup(synonym.getHomotypicGroup());
1887

    
1888
        taxWithSyn.addSynonym(synonym, SynonymType.HETEROTYPIC_SYNONYM_OF());
1889
        taxWithSyn.addSynonym(synonym2, SynonymType.HETEROTYPIC_SYNONYM_OF());
1890

    
1891
        uuidTaxWithoutSyn = service.save(taxWithoutSyn).getUuid();
1892
        uuidSyn = service.save(synonym).getUuid();
1893
        uuidSyn2 = service.save(synonym2).getUuid();
1894
        uuidTaxWithSyn =service.save(taxWithSyn).getUuid();
1895

    
1896
    }
1897

    
1898

    
1899

    
1900
        //public static UUID DESCRIPTION1_UUID = UUID.fromString("f3e061f6-c5df-465c-a253-1e18ab4c7e50");
1901
        //public static UUID DESCRIPTION2_UUID = UUID.fromString("1b009a40-ebff-4f7e-9f7f-75a850ba995d");
1902

    
1903

    
1904

    
1905
        private final Random rnd = new Random();
1906

    
1907
        public Taxon getTestTaxon(){
1908
            int descrIndex = 6000;
1909
            Person deCandolle = Person.NewInstance();
1910
            deCandolle.setTitleCache("DC.", true);
1911

    
1912
            Reference sec = ReferenceFactory.newDatabase();
1913
            sec.setTitleCache("Flora lunaea", true);
1914
            Reference citationRef = ReferenceFactory.newBook();
1915
            citationRef.setTitleCache("Sp. lunarum", true);
1916

    
1917
            //genus taxon with Name, combinationAuthor,
1918
            IBotanicalName botName = TaxonNameFactory.NewBotanicalInstance(Rank.GENUS());
1919
            botName.setTitleCache("Hieracium L.", true);
1920
            botName.setGenusOrUninomial("Hieracium");
1921
            botName.setCombinationAuthorship(Person.NewInstance());
1922
            botName.getCombinationAuthorship().setNomenclaturalTitle("L.");
1923
            botName.setUuid(GENUS_NAME_UUID);
1924
            Taxon genusTaxon = Taxon.NewInstance(botName, sec);
1925
            genusTaxon.setUuid(GENUS_UUID);
1926
            service.save(genusTaxon);
1927
            //a name that is the basionym of genusTaxon's name
1928
            TaxonName basionym = TaxonNameFactory.NewBotanicalInstance(Rank.GENUS());
1929
            basionym.setTitleCache("Hieracilla DC.", true);
1930
            basionym.setGenusOrUninomial("Hieracilla");
1931
            basionym.setCombinationAuthorship(deCandolle);
1932
            basionym.setUuid(BASIONYM_UUID);
1933
            botName.addBasionym(basionym, null, null,"216");
1934
            nameService.saveOrUpdate(basionym);
1935
            //species taxon that is the child of genus taxon
1936
            IBotanicalName botSpecies = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
1937
            botSpecies.setTitleCache("Hieracium asturianum Pau", true);
1938
            botSpecies.setGenusOrUninomial("Hieracium");
1939
            botSpecies.setSpecificEpithet("asturianum");
1940
            botSpecies.setCombinationAuthorship(Person.NewInstance());
1941
            botSpecies.getCombinationAuthorship().setNomenclaturalTitle("Pau");
1942
            botSpecies.setUuid(SPECIES1_NAME_UUID);
1943
            Taxon childTaxon = Taxon.NewInstance(botSpecies, sec);
1944
            childTaxon.setUuid(SPECIES1_UUID);
1945
            TaxonDescription taxDesc = getTestDescription(descrIndex++);
1946
            //taxDesc.setUuid(DESCRIPTION1_UUID);
1947
            childTaxon.addDescription(taxDesc);
1948
            service.saveOrUpdate(childTaxon);
1949
            Classification classification = getTestClassification("TestClassification");
1950
            classification.addParentChild(genusTaxon, childTaxon, citationRef, "456");
1951
//            childTaxon.setTaxonomicParent(genusTaxon, citationRef, "456");
1952
            classificationService.save(classification);
1953
            //homotypic synonym of childTaxon1
1954
            IBotanicalName botSpecies4= TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
1955
            botSpecies4.setTitleCache("Hieracium gueri DC.", true);
1956
            botSpecies4.setGenusOrUninomial("Hieracium");
1957
            botSpecies4.setSpecificEpithet("gueri");
1958
            botSpecies4.setCombinationAuthorship(deCandolle);
1959
            botSpecies4.setUuid(SYNONYM_NAME_UUID);
1960
            Synonym homoSynonym = Synonym.NewInstance(botSpecies4, sec);
1961
            childTaxon.addSynonym(homoSynonym, SynonymType.HOMOTYPIC_SYNONYM_OF());
1962
            service.saveOrUpdate(childTaxon);
1963

    
1964
            //2nd child species taxon that is the child of genus taxon
1965
            IBotanicalName botSpecies2= TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
1966
            botSpecies2.setTitleCache("Hieracium wolffii Zahn", true);
1967
            botSpecies2.setGenusOrUninomial("Hieracium");
1968
            botSpecies2.setSpecificEpithet("wolffii");
1969
            botSpecies2.setCombinationAuthorship(Person.NewInstance());
1970
            botSpecies2.getCombinationAuthorship().setNomenclaturalTitle("Zahn");
1971
            botSpecies2.setUuid(SPECIES2_NAME_UUID);
1972
            Taxon childTaxon2 = Taxon.NewInstance(botSpecies2, sec);
1973
            childTaxon2.setUuid(SPECIES2_UUID);
1974
            classification.addParentChild(genusTaxon, childTaxon2, citationRef, "499");
1975
            //childTaxon2.setTaxonomicParent(genusTaxon, citationRef, "499");
1976
            service.saveOrUpdate(childTaxon2);
1977
            //heterotypic synonym of childTaxon2
1978
            IBotanicalName botSpecies3= TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
1979
            botSpecies3.setTitleCache("Hieracium lupium DC.", true);
1980
            botSpecies3.setGenusOrUninomial("Hieracium");
1981
            botSpecies3.setSpecificEpithet("lupium");
1982
            botSpecies3.setCombinationAuthorship(deCandolle);
1983
            botSpecies3.setUuid(SYNONYM2_NAME_UUID);
1984
            Synonym heteroSynonym = Synonym.NewInstance(botSpecies3, sec);
1985
            childTaxon2.addSynonym(heteroSynonym, SynonymType.HETEROTYPIC_SYNONYM_OF());
1986
            service.saveOrUpdate(childTaxon2);
1987
            //missaplied Name for childTaxon2
1988
            IBotanicalName missName= TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
1989
            missName.setTitleCache("Hieracium lupium DC.", true);
1990
            missName.setGenusOrUninomial("Hieracium");
1991
            missName.setSpecificEpithet("lupium");
1992
            missName.setCombinationAuthorship(deCandolle);
1993
            missName.setUuid(SPECIES5_NAME_UUID);
1994
            Taxon misappliedNameTaxon = Taxon.NewInstance(missName, sec);
1995
            childTaxon2.addMisappliedName(misappliedNameTaxon, citationRef, "125");
1996
            taxDesc = getTestDescription(descrIndex++);
1997
           // taxDesc.setUuid(DESCRIPTION2_UUID);
1998
            genusTaxon.addDescription(taxDesc);
1999
            service.saveOrUpdate(genusTaxon);
2000
            service.save(misappliedNameTaxon);
2001

    
2002
            return genusTaxon;
2003
        }
2004

    
2005
        public TaxonDescription getTestDescription(int index){
2006
            TaxonDescription taxonDescription = TaxonDescription.NewInstance();
2007
            Language language = Language.DEFAULT();
2008
            //taxonDescription.setId(index);
2009

    
2010
            //textData
2011
            TextData textData = TextData.NewInstance();
2012
            String descriptionText = "this is a desciption for a taxon";
2013
            LanguageString languageString = LanguageString.NewInstance(descriptionText, language);
2014
            textData.putText(languageString);
2015
            taxonDescription.addElement(textData);
2016

    
2017
            //commonName
2018

    
2019
            String commonNameString = "Schönveilchen";
2020
            CommonTaxonName commonName = CommonTaxonName.NewInstance(commonNameString, language);
2021
            taxonDescription.addElement(commonName);
2022

    
2023
            return taxonDescription;
2024
        }
2025

    
2026
        public Classification getTestClassification(String name){
2027
            return Classification.NewInstance(name);
2028
        }
2029
}
(27-27/35)