Project

General

Profile

Download (86.9 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.Set;
22
import java.util.UUID;
23

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

    
30
import eu.etaxonomy.cdm.api.service.config.IncludedTaxonConfiguration;
31
import eu.etaxonomy.cdm.api.service.config.NameDeletionConfigurator;
32
import eu.etaxonomy.cdm.api.service.config.NodeDeletionConfigurator.ChildHandling;
33
import eu.etaxonomy.cdm.api.service.config.SynonymDeletionConfigurator;
34
import eu.etaxonomy.cdm.api.service.config.TaxonDeletionConfigurator;
35
import eu.etaxonomy.cdm.api.service.dto.IncludedTaxaDTO;
36
import eu.etaxonomy.cdm.api.service.exception.HomotypicalGroupChangeException;
37
import eu.etaxonomy.cdm.datagenerator.TaxonGenerator;
38
import eu.etaxonomy.cdm.model.common.CdmBase;
39
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
40
import eu.etaxonomy.cdm.model.common.Marker;
41
import eu.etaxonomy.cdm.model.common.MarkerType;
42
import eu.etaxonomy.cdm.model.common.OriginalSourceType;
43
import eu.etaxonomy.cdm.model.common.RelationshipBase;
44
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
45
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
46
import eu.etaxonomy.cdm.model.description.TaxonDescription;
47
import eu.etaxonomy.cdm.model.name.BotanicalName;
48
import eu.etaxonomy.cdm.model.name.HomotypicalGroup;
49
import eu.etaxonomy.cdm.model.name.NameRelationship;
50
import eu.etaxonomy.cdm.model.name.NameRelationshipType;
51
import eu.etaxonomy.cdm.model.name.NonViralName;
52
import eu.etaxonomy.cdm.model.name.Rank;
53
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
54
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
55
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
56
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
57
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
58
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
59
import eu.etaxonomy.cdm.model.reference.Reference;
60
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
61
import eu.etaxonomy.cdm.model.taxon.Classification;
62
import eu.etaxonomy.cdm.model.taxon.Synonym;
63
import eu.etaxonomy.cdm.model.taxon.SynonymRelationship;
64
import eu.etaxonomy.cdm.model.taxon.SynonymRelationshipType;
65
import eu.etaxonomy.cdm.model.taxon.Taxon;
66
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
67
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
68
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
69
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
70
import eu.etaxonomy.cdm.strategy.cache.common.IIdentifiableEntityCacheStrategy;
71
import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
72
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
73

    
74
/**
75
 * @author a.mueller
76
 */
77

    
78

    
79
public class TaxonServiceImplTest extends CdmTransactionalIntegrationTest {
80
    private static final Logger logger = Logger.getLogger(TaxonServiceImplTest.class);
81

    
82
    @SpringBeanByType
83
    private ITaxonService service;
84

    
85
    @SpringBeanByType
86
    private INameService nameService;
87

    
88
    @SpringBeanByType
89
    private IReferenceService referenceService;
90

    
91
    @SpringBeanByType
92
    private IClassificationService classificationService;
93

    
94
    @SpringBeanByType
95
    private ITaxonNodeService nodeService;
96

    
97
    @SpringBeanByType
98
    private IDescriptionService descriptionService;
99

    
100
    @SpringBeanByType
101
    private IMarkerService markerService;
102

    
103
    @SpringBeanByType
104
    private IEventBaseService eventService;
105

    
106
    @SpringBeanByType
107
    private IOccurrenceService occurenceService;
108

    
109
    private Synonym synonym;
110
    private Synonym synonym2;
111

    
112
    private Taxon taxWithSyn;
113
    private Taxon tax2WithSyn;
114
    private Taxon taxWithoutSyn;
115
    private UUID uuidSyn;
116
    private UUID uuidTaxWithoutSyn;
117
    private UUID uuidSyn2;
118
    private UUID uuidTaxWithSyn;
119

    
120
/****************** TESTS *****************************/
121

    
122

    
123
    /**
124
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#getTaxonByUuid(java.util.UUID)}.
125
     */
126
    @Test
127
    public final void testGetTaxonByUuid() {
128
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
129
        UUID uuid = service.save(expectedTaxon).getUuid();
130
        TaxonBase<?> actualTaxon = service.find(uuid);
131
        assertEquals(expectedTaxon, actualTaxon);
132
    }
133

    
134
    /**
135
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#saveTaxon(eu.etaxonomy.cdm.model.taxon.TaxonBase)}.
136
     */
137
    @Test
138
    public final void testSaveTaxon() {
139
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
140
        UUID uuid = service.save(expectedTaxon).getUuid();
141
        TaxonBase<?> actualTaxon = service.find(uuid);
142
        assertEquals(expectedTaxon, actualTaxon);
143
    }
144

    
145
    @Test
146
    public final void testSaveOrUpdateTaxon() {
147
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
148
        UUID uuid = service.save(expectedTaxon).getUuid();
149
        TaxonBase<?> actualTaxon = service.find(uuid);
150
        assertEquals(expectedTaxon, actualTaxon);
151

    
152
        actualTaxon.setName(BotanicalName.NewInstance(Rank.SPECIES()));
153
        try{
154
            service.saveOrUpdate(actualTaxon);
155
        }catch(Exception e){
156
            Assert.fail();
157
        }
158
    }
159
    /**
160
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#removeTaxon(eu.etaxonomy.cdm.model.taxon.TaxonBase)}.
161
     */
162
    @Test
163
    public final void testRemoveTaxon() {
164
        Taxon taxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.UNKNOWN_RANK()), null);
165
        UUID uuid = service.save(taxon).getUuid();
166
       // try {
167
			service.deleteTaxon(taxon.getUuid(), null, null);
168
		/*} catch (DataChangeNoRollbackException e) {
169
			// TODO Auto-generated catch block
170
			e.printStackTrace();
171
		}*/
172
        TaxonBase<?> actualTaxon = service.find(uuid);
173
        assertNull(actualTaxon);
174
    }
175

    
176

    
177
    @Test
178
    public final void testMakeTaxonSynonym() {
179
        try {
180
			createTestDataSet();
181
		} catch (FileNotFoundException e) {
182
			// TODO Auto-generated catch block
183
			e.printStackTrace();
184
		}
185

    
186
        service.swapSynonymAndAcceptedTaxon(synonym, taxWithSyn);
187

    
188
        // find forces flush
189
        Taxon tax = (Taxon)service.find(uuidTaxWithSyn);
190
        tax.removeSynonym(synonym);
191
        tax.addHomotypicSynonym(synonym, null, null);
192
        service.saveOrUpdate(tax);
193
        TaxonBase<?> syn = service.find(uuidSyn);
194

    
195
        assertTrue(tax.getName().getTitleCache().equals("Test2"));
196

    
197
        HomotypicalGroup groupTest = tax.getHomotypicGroup();
198
        HomotypicalGroup groupTest2 = syn.getHomotypicGroup();
199
        assertEquals(groupTest, groupTest2);
200

    
201
    }
202

    
203
    @Test
204
    public final void testChangeSynonymToAcceptedTaxon(){
205
    	try {
206
			createTestDataSet();
207
		} catch (FileNotFoundException e1) {
208
			// TODO Auto-generated catch block
209
			e1.printStackTrace();
210
		}
211

    
212

    
213
        Taxon taxon = null;
214
        try {
215
            taxon = service.changeSynonymToAcceptedTaxon(synonym, taxWithSyn, true, true, null, null);
216
        } catch (HomotypicalGroupChangeException e) {
217
            Assert.fail("Invocation of change method should not throw an exception");
218
        }
219
        taxWithSyn = null;
220
        //test flush (resave deleted object)
221
        TaxonBase<?> syn = service.find(uuidSyn);
222
        taxWithSyn = (Taxon)service.find(uuidTaxWithSyn);
223
        Taxon taxNew = (Taxon)service.find(taxon.getUuid());
224
        assertNull(syn);
225
        assertNotNull(taxWithSyn);
226
        assertNotNull(taxNew);
227

    
228
        Assert.assertEquals("New taxon should have 1 synonym relationship (the old homotypic synonym)", 1, taxon.getSynonymRelations().size());
229
    }
230

    
231

    
232

    
233
    @Test
234
    public final void testChangeSynonymToAcceptedTaxonSynonymForTwoTaxa(){
235
        try {
236
			createTestDataSet();
237
		} catch (FileNotFoundException e1) {
238
			// TODO Auto-generated catch block
239
			e1.printStackTrace();
240
		}
241

    
242

    
243
        Taxon taxon = null;
244
        try {
245
            taxon = service.changeSynonymToAcceptedTaxon(synonym, taxWithSyn, true, true, null, null);
246
            service.save(taxon);
247
        } catch (HomotypicalGroupChangeException e) {
248
            Assert.fail("Invocation of change method should not throw an exception");
249
        }
250
        taxWithSyn = null;
251
        tax2WithSyn = null;
252

    
253
        //test flush (resave deleted object)
254
        TaxonBase<?> syn = service.find(uuidSyn);
255
        taxWithSyn = (Taxon)service.find(uuidTaxWithSyn);
256
        Taxon taxNew = (Taxon)service.find(taxon.getUuid());
257
        assertNull(syn);
258
        assertNotNull(taxWithSyn);
259
        assertNotNull(taxNew);
260

    
261
       // Assert.assertEquals("New taxon should have 1 synonym relationship (the old homotypic synonym)", 1, taxon.getSynonymRelations().size());
262
    }
263

    
264
    /**
265
     * Old implementation taken from {@link TaxonServiceImplBusinessTest} for old version of method.
266
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#moveSynonymToAnotherTaxon(eu.etaxonomy.cdm.model.taxon.SynonymRelationship, eu.etaxonomy.cdm.model.taxon.Taxon, eu.etaxonomy.cdm.model.taxon.SynonymRelationshipType, eu.etaxonomy.cdm.model.reference.Reference, java.lang.String)}.
267
     */
268
    @Test
269
    public final void testMoveSynonymToAnotherTaxon_OLD() {
270
        SynonymRelationshipType heteroTypicSynonymRelationshipType = SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF();
271
        Reference reference = ReferenceFactory.newGeneric();
272
        String referenceDetail = "test";
273

    
274
        NonViralName<?> t1n = NonViralName.NewInstance(null);
275
        Taxon t1 = Taxon.NewInstance(t1n, reference);
276
        NonViralName<?> t2n = NonViralName.NewInstance(null);
277
        Taxon t2 = Taxon.NewInstance(t2n, reference);
278
        NonViralName<?> s1n = NonViralName.NewInstance(null);
279
        Synonym s1 = Synonym.NewInstance(s1n, reference);
280
        t1.addSynonym(s1, heteroTypicSynonymRelationshipType);
281
        service.saveOrUpdate(t1);
282

    
283
        SynonymRelationship synonymRelation = t1.getSynonymRelations().iterator().next();
284

    
285
        boolean keepReference = false;
286
        boolean moveHomotypicGroup = false;
287
        try {
288
            service.moveSynonymToAnotherTaxon(synonymRelation, t2, moveHomotypicGroup, heteroTypicSynonymRelationshipType, reference, referenceDetail, keepReference);
289
        } catch (HomotypicalGroupChangeException e) {
290
            Assert.fail("Method call should not throw exception");
291
        }
292

    
293
        Assert.assertTrue("t1 should have no synonym relationships", t1.getSynonymRelations().isEmpty());
294

    
295
        Set<SynonymRelationship> synonymRelations = t2.getSynonymRelations();
296
        Assert.assertTrue("t2 should have exactly one synonym relationship", synonymRelations.size() == 1);
297

    
298
        synonymRelation = synonymRelations.iterator().next();
299

    
300
        Assert.assertEquals(t2, synonymRelation.getAcceptedTaxon());
301
        Assert.assertEquals(heteroTypicSynonymRelationshipType, synonymRelation.getType());
302
        Assert.assertEquals(reference, synonymRelation.getCitation());
303
        Assert.assertEquals(referenceDetail, synonymRelation.getCitationMicroReference());
304
    }
305

    
306
    @Test
307
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testMoveSynonymToAnotherTaxon.xml")
308
    public final void testMoveSynonymToAnotherTaxon() throws Exception {
309
        final String[] tableNames = new String[]{"SynonymRelationship"};
310

    
311
//        printDataSet(System.err, new String[]{"AgentBase", "TaxonBase"});
312
//        printDataSet(System.err, new String[]{"TaxonNode"});
313

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

    
324

    
325
        boolean moveHomotypicGroup = true;
326
        SynonymRelationshipType newSynonymRelationshipType = null;
327
        boolean keepReference = true;
328
        Reference newReference = null;
329
        String newReferenceDetail = null;
330

    
331
        Taxon newTaxon = (Taxon)service.load(uuidNewTaxon);
332
        Synonym homotypicSynonym = (Synonym)service.load(uuidSyn1);
333
        Assert.assertNotNull("Synonym should exist", homotypicSynonym);
334
        Assert.assertEquals("Synonym should have 1 relation", 1, homotypicSynonym.getSynonymRelations().size());
335
        SynonymRelationship rel = homotypicSynonym.getSynonymRelations().iterator().next();
336
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, rel.getAcceptedTaxon().getUuid());
337
        Taxon oldTaxon = rel.getAcceptedTaxon();
338

    
339
        try {
340
            service.moveSynonymToAnotherTaxon(rel, newTaxon, moveHomotypicGroup, newSynonymRelationshipType, newReference, newReferenceDetail, keepReference);
341
            Assert.fail("Homotypic synonym move to other taxon should throw an exception");
342
        } catch (HomotypicalGroupChangeException e) {
343
            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")){
344
                //OK
345
                commitAndStartNewTransaction(tableNames);
346
            }else{
347
                Assert.fail("Unexpected exception occurred: " + e.getMessage());
348
            }
349
        }
350
        //Asserts
351
        homotypicSynonym = (Synonym)service.load(uuidSyn1);
352
        Assert.assertNotNull("Synonym should still exist", homotypicSynonym);
353
        Assert.assertEquals("Synonym should still have 1 relation", 1, homotypicSynonym.getSynonymRelations().size());
354
        rel = homotypicSynonym.getSynonymRelations().iterator().next();
355
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", oldTaxon, rel.getAcceptedTaxon());
356

    
357
        //test heterotypic synonym with other synonym in homotypic group
358
        newTaxon = (Taxon)service.load(uuidNewTaxon);
359
        Synonym heterotypicSynonym = (Synonym)service.load(uuidSyn3);
360
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym);
361
        Assert.assertEquals("Synonym should have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
362
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
363
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, rel.getAcceptedTaxon().getUuid());
364
        oldTaxon = rel.getAcceptedTaxon();
365
        moveHomotypicGroup = false;
366

    
367
        try {
368
            service.moveSynonymToAnotherTaxon(rel, newTaxon, moveHomotypicGroup, newSynonymRelationshipType, newReference, newReferenceDetail, keepReference);
369
            Assert.fail("Heterotypic synonym move to other taxon should throw an exception");
370
        } catch (HomotypicalGroupChangeException e) {
371
            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")){
372
                //OK
373
                commitAndStartNewTransaction(tableNames);
374
            }else{
375
                Assert.fail("Unexpected exception occurred: " + e.getMessage());
376
            }
377
        }
378
        //Asserts
379
        heterotypicSynonym = (Synonym)service.load(uuidSyn3);
380
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
381
        Assert.assertEquals("Synonym should still have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
382
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
383
        Assert.assertEquals("Accepted taxon of single relation should still be the old taxon", oldTaxon, rel.getAcceptedTaxon());
384

    
385

    
386
        //test heterotypic synonym with no other synonym in homotypic group
387
        //+ keep reference
388

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

    
391
        newTaxon = (Taxon)service.load(uuidNewTaxon);
392
        heterotypicSynonym = (Synonym)service.load(uuidSyn5);
393
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym);
394
        Assert.assertEquals("Synonym should have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
395
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
396
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, rel.getAcceptedTaxon().getUuid());
397
        oldTaxon = rel.getAcceptedTaxon();
398
        moveHomotypicGroup = false;
399

    
400

    
401
        try {
402
            service.moveSynonymToAnotherTaxon(rel, newTaxon, moveHomotypicGroup, newSynonymRelationshipType, newReference, newReferenceDetail, keepReference);
403
        } catch (HomotypicalGroupChangeException e) {
404
            Assert.fail("Move of single heterotypic synonym should not throw exception: " + e.getMessage());
405
        }
406
        //Asserts
407
        //FIXME throws exception
408
        commitAndStartNewTransaction(tableNames);
409

    
410
//        printDataSet(System.err, new String[]{"AgentBase", "TaxonBase"});
411
//
412
//      printDataSet(System.err, new String[]{"TaxonBase"});
413

    
414
        heterotypicSynonym = (Synonym)service.load(uuidSyn5);
415

    
416
//      printDataSet(System.err, new String[]{"TaxonBase"});
417
//      System.exit(0);
418

    
419
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
420
        Assert.assertEquals("Synonym should still have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
421
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
422
        Assert.assertEquals("Accepted taxon of single relation should be new taxon", newTaxon, rel.getAcceptedTaxon());
423
        Assert.assertEquals("Old detail should be kept", "rel5", rel.getCitationMicroReference());
424

    
425

    
426
        //test heterotypic synonym with other synonym in homotypic group and moveHomotypicGroup="true"
427
        //+ new detail
428
        newTaxon = (Taxon)service.load(uuidNewTaxon);
429
        heterotypicSynonym = (Synonym)service.load(uuidSyn3);
430
        Reference ref1 = referenceService.load(uuidRef1);
431
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym);
432
        Assert.assertEquals("Synonym should have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
433
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
434
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, rel.getAcceptedTaxon().getUuid());
435
        oldTaxon = rel.getAcceptedTaxon();
436
        Assert.assertEquals("Detail should be ref1", ref1, rel.getCitation());
437
        Assert.assertEquals("Detail should be 'rel3'", "rel3", rel.getCitationMicroReference());
438
        TaxonNameBase<?,?> oldSynName3 = heterotypicSynonym.getName();
439

    
440
        Synonym heterotypicSynonym4 = (Synonym)service.load(uuidSyn4);
441
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym4);
442
        Assert.assertEquals("Synonym should have 1 relation", 1, heterotypicSynonym4.getSynonymRelations().size());
443
        SynonymRelationship rel4 = heterotypicSynonym4.getSynonymRelations().iterator().next();
444
        Assert.assertEquals("Accepted taxon of other synonym in group should be the old taxon", uuidOldTaxon, rel4.getAcceptedTaxon().getUuid());
445
        Assert.assertSame("Homotypic group of both synonyms should be same", oldSynName3.getHomotypicalGroup() , heterotypicSynonym4.getName().getHomotypicalGroup() );
446

    
447
        moveHomotypicGroup = true;
448
        keepReference = false;
449

    
450
        try {
451
            service.moveSynonymToAnotherTaxon(rel, newTaxon, moveHomotypicGroup, newSynonymRelationshipType, newReference, newReferenceDetail, keepReference);
452
        } catch (HomotypicalGroupChangeException e) {
453
            Assert.fail("Move with 'moveHomotypicGroup = true' should not throw exception: " + e.getMessage());
454
        }
455
        //Asserts
456
        commitAndStartNewTransaction(tableNames);
457
        heterotypicSynonym = (Synonym)service.load(uuidSyn3);
458
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
459
        Assert.assertEquals("Synonym should still have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
460
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
461
        Assert.assertEquals("Accepted taxon of relation should be new taxon now", newTaxon, rel.getAcceptedTaxon());
462
        TaxonNameBase<?,?> synName3 = rel.getSynonym().getName();
463

    
464
        heterotypicSynonym = (Synonym)service.load(uuidSyn4);
465
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
466
        Assert.assertEquals("Synonym should still have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
467
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
468
        Assert.assertEquals("Accepted taxon of relation should be new taxon now", newTaxon, rel.getAcceptedTaxon());
469
        Assert.assertNull("Old citation should be removed", rel.getCitation());
470
        Assert.assertNull("Old detail should be removed", rel.getCitationMicroReference());
471
        TaxonNameBase<?,?> synName4 = rel.getSynonym().getName();
472
        Assert.assertEquals("Homotypic group of both synonyms should be equal", synName3.getHomotypicalGroup() , synName4.getHomotypicalGroup() );
473
        Assert.assertSame("Homotypic group of both synonyms should be same", synName3.getHomotypicalGroup() , synName4.getHomotypicalGroup() );
474
        Assert.assertEquals("Homotypic group of both synonyms should be equal to old homotypic group", oldSynName3.getHomotypicalGroup() , synName3.getHomotypicalGroup() );
475

    
476

    
477
        //test single heterotypic synonym to homotypic synonym of new taxon
478
        //+ new reference
479
        newTaxon = (Taxon)service.load(uuidNewTaxon);
480
        Reference ref2 = referenceService.load(uuidRef2);
481
        heterotypicSynonym = (Synonym)service.load(uuidSyn6);
482
        Assert.assertNotNull("Synonym should exist", heterotypicSynonym);
483
        Assert.assertEquals("Synonym should have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
484
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
485
        Assert.assertEquals("Accepted taxon of single relation should be the old taxon", uuidOldTaxon, rel.getAcceptedTaxon().getUuid());
486
        oldTaxon = rel.getAcceptedTaxon();
487
        moveHomotypicGroup = false;
488
        keepReference = false;
489
        newReference = ref2;
490
        newReferenceDetail = "newRefDetail";
491
        newSynonymRelationshipType = SynonymRelationshipType.HOMOTYPIC_SYNONYM_OF();
492

    
493
        try {
494
            service.moveSynonymToAnotherTaxon(rel, newTaxon, moveHomotypicGroup, newSynonymRelationshipType, newReference, newReferenceDetail, keepReference);
495
        } catch (HomotypicalGroupChangeException e) {
496
            Assert.fail("Move of single heterotypic synonym should not throw exception: " + e.getMessage());
497
        }
498
        //Asserts
499
        commitAndStartNewTransaction(tableNames);
500
        heterotypicSynonym = (Synonym)service.load(uuidSyn6);
501
        Assert.assertNotNull("Synonym should still exist", heterotypicSynonym);
502
        Assert.assertEquals("Synonym should still have 1 relation", 1, heterotypicSynonym.getSynonymRelations().size());
503
        rel = heterotypicSynonym.getSynonymRelations().iterator().next();
504
        Assert.assertEquals("Relationship type should be 'homotypic synonym'", newSynonymRelationshipType, rel.getType());
505
        Assert.assertEquals("Accepted taxon of single relation should be new taxon", newTaxon, rel.getAcceptedTaxon());
506
        Assert.assertEquals("New citation should be ref2", ref2 ,rel.getCitation());
507
        Assert.assertEquals("New detail should be kept", "newRefDetail", rel.getCitationMicroReference());
508

    
509
        Assert.assertEquals("New taxon and new synonym should have equal homotypical group", rel.getSynonym().getHomotypicGroup(), rel.getAcceptedTaxon().getHomotypicGroup());
510
        Assert.assertSame("New taxon and new synonym should have same homotypical group", rel.getSynonym().getHomotypicGroup(), rel.getAcceptedTaxon().getHomotypicGroup());
511
    }
512

    
513

    
514

    
515
    @Test
516
    public final void testGetHeterotypicSynonymyGroups(){
517
        Rank rank = Rank.SPECIES();
518
        Reference ref1 = ReferenceFactory.newGeneric();
519
        //HomotypicalGroup group = HomotypicalGroup.NewInstance();
520
        Taxon taxon1 = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test3", null, null, null, null, null, null, null), null);
521
        Synonym synonym0 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test2", null, null, null, null, null, null, null), null);
522
        Synonym synonym1 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test2", null, null, null, null, null, null, null), null);
523
        Synonym synonym2 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test4", null, null, null, null, null, null, null), null);
524
        synonym0.getName().setHomotypicalGroup(taxon1.getHomotypicGroup());
525
        synonym2.getName().setHomotypicalGroup(synonym1.getHomotypicGroup());
526
        //tax2.addHeterotypicSynonymName(synonym.getName());
527
        taxon1.addSynonym(synonym1, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
528
        taxon1.addSynonym(synonym2, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
529

    
530
        service.save(synonym1);
531
        service.save(synonym2);
532
        service.save(taxon1);
533

    
534
        List<List<Synonym>> heteroSyns = service.getHeterotypicSynonymyGroups(taxon1, null);
535
        Assert.assertEquals("There should be 1 heterotypic group", 1, heteroSyns.size());
536
        List<Synonym> synList = heteroSyns.get(0);
537
        Assert.assertEquals("There should be 2 heterotypic syns in group 1", 2, synList.size());
538

    
539
        //test sec
540
        synonym2.setSec(ref1);
541
        heteroSyns = service.getHeterotypicSynonymyGroups(taxon1, null);
542
        Assert.assertEquals("There should be 1 heterotypic group", 1, heteroSyns.size());
543
        synList = heteroSyns.get(0);
544
        Assert.assertEquals("getHeterotypicSynonymyGroups should be independent of sec reference", 2, synList.size());
545

    
546
    }
547

    
548

    
549
    @Test
550
    public final void testGetHomotypicSynonymsByHomotypicGroup(){
551
        Rank rank = Rank.SPECIES();
552
        Reference ref1 = ReferenceFactory.newGeneric();
553
        //HomotypicalGroup group = HomotypicalGroup.NewInstance();
554
        Taxon taxon1 = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test3", null, null, null, null, null, null, null), null);
555
        Synonym synonym0 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test2", null, null, null, null, null, null, null), null);
556
        Synonym synonym1 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test2", null, null, null, null, null, null, null), null);
557
        Synonym synonym2 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test4", null, null, null, null, null, null, null), null);
558
        synonym0.getName().setHomotypicalGroup(taxon1.getHomotypicGroup());
559
        synonym2.getName().setHomotypicalGroup(synonym1.getHomotypicGroup());
560
        //tax2.addHeterotypicSynonymName(synonym.getName());
561
        taxon1.addSynonym(synonym0, SynonymRelationshipType.HOMOTYPIC_SYNONYM_OF());
562
        taxon1.addSynonym(synonym1, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
563
        taxon1.addSynonym(synonym2, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
564

    
565
        service.save(synonym1);
566
        service.save(synonym2);
567
        service.save(taxon1);
568

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

    
573
        //test sec
574
        synonym0.setSec(ref1);
575
        homoSyns = service.getHomotypicSynonymsByHomotypicGroup(taxon1, null);
576
        Assert.assertEquals("getHeterotypicSynonymyGroups should be independent of sec reference", 1, homoSyns.size());
577

    
578
    }
579

    
580
    @Test
581
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
582
    //test delete synonym, but the name will not be deleted
583
    public final void testDeleteSynonymSynonymTaxonDontDeleteName(){
584
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
585
                "SynonymRelationship","SynonymRelationship_AUD",
586
                "HomotypicalGroup","HomotypicalGroup_AUD"};
587

    
588
        int nSynonyms = service.count(Synonym.class);
589
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
590
        int nNames = nameService.count(TaxonNameBase.class);
591
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
592
        int nRelations = service.countAllRelationships();
593
        Assert.assertEquals("There should be two relationship left in the database", 2, nRelations);
594

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

    
597

    
598
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
599
        SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
600
        config.setDeleteNameIfPossible(false);
601
        config.setNewHomotypicGroupIfNeeded(true);
602
        service.deleteSynonym(synonym1, config);
603

    
604
        this.commitAndStartNewTransaction(tableNames);
605

    
606
        nSynonyms = service.count(Synonym.class);
607
        Assert.assertEquals("There should be 1 synonym left in the database", 1, nSynonyms);
608
        nNames = nameService.count(TaxonNameBase.class);
609
        Assert.assertEquals("There should be 4 names left in the database", 4, nNames);
610
        nRelations = service.countAllRelationships();
611
        Assert.assertEquals("There should be no relationship left in the database", 1, nRelations);
612
    }
613

    
614
    @Test
615
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
616
    //test delete synonym and his name
617
    public final void testDeleteSynonymSynonymTaxonDeleteName(){
618
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
619
                "SynonymRelationship","SynonymRelationship_AUD",
620
                "HomotypicalGroup","HomotypicalGroup_AUD"};
621

    
622
        int nSynonyms = service.count(Synonym.class);
623
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
624
        int nNames = nameService.count(TaxonNameBase.class);
625
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
626
        int nRelations = service.countAllRelationships();
627
        Assert.assertEquals("There should be 2 relationship left in the database", 2, nRelations);
628

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

    
631

    
632
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
633
        service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
634

    
635
        this.commitAndStartNewTransaction(tableNames);
636

    
637
        nSynonyms = service.count(Synonym.class);
638
        Assert.assertEquals("There should be 1 synonym left in the database", 1, nSynonyms);
639
        nNames = nameService.count(TaxonNameBase.class);
640
        Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
641
        nRelations = service.countAllRelationships();
642
        Assert.assertEquals("There should be 1 relationship left in the database", 1, nRelations);
643

    
644
    }
645

    
646
    @Test
647
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
648
    //test remove synonym from taxon -> synonym and name still in the db and the synonymrelationship to the other taxon
649
    //test delete synonym -> all relationships are deleted, the name is deleted and the synonym itself
650
    public final void testDeleteSynonymSynonymTaxonBooleanRelToOneTaxon(){
651
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
652
                "SynonymRelationship","SynonymRelationship_AUD",
653
                "HomotypicalGroup","HomotypicalGroup_AUD"};
654

    
655
        int nSynonyms = service.count(Synonym.class);
656
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
657
        int nNames = nameService.count(TaxonNameBase.class);
658
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
659

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

    
664

    
665
        Taxon taxon2 = (Taxon)service.load(uuidTaxon1);
666

    
667
        List<String> initStrat = new ArrayList<String>();
668
        initStrat.add("markers");
669
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1, initStrat);
670
        int nRelations = service.countAllRelationships();
671
        Assert.assertEquals("There should be 2 relationship left in the database", 2, nRelations);
672

    
673
        taxon2.removeSynonym(synonym1, false);
674
        service.saveOrUpdate(taxon2);
675

    
676
        commitAndStartNewTransaction(null);
677

    
678
        nSynonyms = service.count(Synonym.class);
679
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
680
        nNames = nameService.count(TaxonNameBase.class);
681
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
682
        nRelations = service.countAllRelationships();
683
        Assert.assertEquals("There should be 1 relationship left in the database", 1, nRelations);
684
        Marker marker1 = Marker.NewInstance(MarkerType.IMPORTED(), true);
685
        Marker marker2 = Marker.NewInstance(MarkerType.COMPUTED(), true);
686
        synonym1.addMarker(marker1);
687
        synonym1.addMarker(marker2);
688
        service.update(synonym1);
689
        synonym1 =(Synonym) service.load(uuidSynonym1);
690

    
691

    
692
        Set<Marker> markers = synonym1.getMarkers();
693
        Marker marker = markers.iterator().next();
694
        UUID markerUUID = marker.getUuid();
695
       // taxon2 = (Taxon)service.load(uuidTaxon2);
696
        synonym1 = (Synonym)service.load(uuidSynonym1);
697
        //the marker should not prevent the deletion
698
        DeleteResult result = service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
699
        if (!result.isOk()){
700
        	Assert.fail();
701
        }
702

    
703

    
704

    
705

    
706
        commitAndStartNewTransaction(tableNames);
707
        nSynonyms = service.count(Synonym.class);
708
        Assert.assertEquals("There should be 1 synonym left in the database", 1, nSynonyms);
709
        nNames = nameService.count(TaxonNameBase.class);
710
        Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
711
        nRelations = service.countAllRelationships();
712
        Assert.assertEquals("There should be no relationship left in the database", 1, nRelations);
713
        marker = markerService.load(markerUUID);
714
        assertNull(marker);
715

    
716
    }
717

    
718
    @Test
719
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
720
    //test delete synonym, only for a special taxon, but because of other relationships it will not be deleted at all
721
    public final void testDeleteSynonymSynonymTaxonBooleanDeleteOneTaxon(){
722
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
723
                "SynonymRelationship","SynonymRelationship_AUD",
724
                "HomotypicalGroup","HomotypicalGroup_AUD"};
725

    
726

    
727
        int nSynonyms = service.count(Synonym.class);
728
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
729
        int nNames = nameService.count(TaxonNameBase.class);
730
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
731

    
732
        UUID uuidTaxon1=UUID.fromString("c47fdb72-f32c-452e-8305-4b44f01179d0");
733
        UUID uuidTaxon2=UUID.fromString("2d9a642d-5a82-442d-8fec-95efa978e8f8");
734
        UUID uuidSynonym1=UUID.fromString("7da85381-ad9d-4886-9d4d-0eeef40e3d88");
735
        UUID uuidSynonym2=UUID.fromString("f8d86dc9-5f18-4877-be46-fbb9412465e4");
736

    
737
        Taxon taxon1 = (Taxon)service.load(uuidTaxon1);
738
        Taxon taxon2 = (Taxon)service.load(uuidTaxon2);
739
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
740
        taxon2.addSynonym(synonym1, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
741
        service.saveOrUpdate(synonym1);
742
        int nRelations = service.countAllRelationships();
743
        Assert.assertEquals("There should be 3 relationship left in the database", 3, nRelations);
744
        service.deleteSynonym(synonym1, taxon1, new SynonymDeletionConfigurator());
745

    
746
        this.commitAndStartNewTransaction(tableNames);
747

    
748
        nSynonyms = service.count(Synonym.class);
749
        Assert.assertEquals("There should still be 2 synonyms left in the database (synonym is related to taxon2)", 2, nSynonyms);
750
        nNames = nameService.count(TaxonNameBase.class);
751
        Assert.assertEquals("There should be 4 names left in the database (name not deleted as synonym was not deleted)", 4, nNames);
752
        nRelations = service.countAllRelationships();
753
        Assert.assertEquals("There should be 2 relationship left in the database", 2, nRelations);
754

    
755

    
756
    }
757

    
758
    @Test
759
    @DataSet("TaxonServiceImplTest.testDeleteSynonym.xml")
760

    
761
    public final void testDeleteSynonymSynonymTaxonBooleanWithRelatedName(){
762
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
763
                "SynonymRelationship","SynonymRelationship_AUD",
764
                "HomotypicalGroup","HomotypicalGroup_AUD"};
765

    
766
        int nSynonyms = service.count(Synonym.class);
767
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
768
        int nNames = nameService.count(TaxonNameBase.class);
769
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
770

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

    
777
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
778
        TaxonNameBase name2 = nameService.load(uuidSynonymName2);
779
        UUID name3Uuid = synonym1.getName().getUuid();
780
        TaxonNameBase name3 = nameService.load(name3Uuid);
781
        name3.addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
782

    
783
        service.saveOrUpdate(synonym1);
784

    
785
        int nRelations = nameService.getAllRelationships(1000, 0).size();
786
        logger.info("number of name relations: " + nRelations);
787
        Assert.assertEquals("There should be 1 name relationship left in the database", 1, nRelations);
788
        SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
789

    
790
        service.deleteSynonym(synonym1, config);
791

    
792
        this.commitAndStartNewTransaction(tableNames);
793
        //synonym is deleted, but the name can not be deleted because of a name relationship
794
        nSynonyms = service.count(Synonym.class);
795
        Assert.assertEquals("There should still be 1 synonyms left in the database", 1, nSynonyms);
796
        nNames = nameService.count(TaxonNameBase.class);
797
        Assert.assertEquals("There should be 4 names left in the database (name is related to synonymName2)", 4, nNames);
798
        nRelations = service.countAllRelationships();
799
        //may change with better implementation of countAllRelationships (see #2653)
800
        nRelations = nameService.getAllRelationships(1000, 0).size();
801
        logger.info("number of name relations: " + nRelations);
802
        Assert.assertEquals("There should be 1 name relationship left in the database", 1, nRelations);
803

    
804

    
805
        //clean up database
806
        name2 = nameService.load(uuidSynonymName2);
807
        NameRelationship rel = CdmBase.deproxy(name2.getNameRelations().iterator().next(), NameRelationship.class);
808
        name2.removeNameRelationship(rel);
809
        nameService.save(name2);
810
        this.setComplete();
811
        this.endTransaction();
812

    
813
    }
814
    @Test
815
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
816
    public final void testDeleteSynonymSynonymTaxonBooleanWithRelatedNameDeleteAllNameRelations(){
817
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
818
                "SynonymRelationship","SynonymRelationship_AUD",
819
                "HomotypicalGroup","HomotypicalGroup_AUD"};
820

    
821
        int nSynonyms = service.count(Synonym.class);
822
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
823
        int nNames = nameService.count(TaxonNameBase.class);
824
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
825

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

    
832
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
833
        TaxonNameBase name2 = nameService.load(uuidSynonymName2);
834
        UUID name3Uuid = synonym1.getName().getUuid();
835
        TaxonNameBase name3 = nameService.load(name3Uuid);
836
        name3.addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
837

    
838
        service.saveOrUpdate(synonym1);
839

    
840
        int nRelations = nameService.getAllRelationships(1000, 0).size();
841
        logger.info("number of name relations: " + nRelations);
842
        Assert.assertEquals("There should be 1 name relationship left in the database", 1, nRelations);
843
        SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
844
        NameDeletionConfigurator nameDeletionConfig = new NameDeletionConfigurator();
845
        nameDeletionConfig.setRemoveAllNameRelationships(true);
846
        config.setNameDeletionConfig(nameDeletionConfig);
847

    
848
        service.deleteSynonym(synonym1, config);
849

    
850
        this.commitAndStartNewTransaction(tableNames);
851

    
852
        nSynonyms = service.count(Synonym.class);
853
        Assert.assertEquals("There should still be 1 synonyms left in the database", 1, nSynonyms);
854
        nNames = nameService.count(TaxonNameBase.class);
855
        Assert.assertEquals("There should be 3 names left in the database ", 3, nNames);
856
        nRelations = service.countAllRelationships();
857
        //may change with better implementation of countAllRelationships (see #2653)
858
        nRelations = nameService.getAllRelationships(1000, 0).size();
859
        logger.info("number of name relations: " + nRelations);
860
        Assert.assertEquals("There should be no name relationship left in the database", 0, nRelations);
861
    }
862

    
863
    @Test
864
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="TaxonServiceImplTest.testDeleteSynonym.xml")
865
    public final void testDeleteSynonymSynonymTaxonBooleanWithRelatedNameIgnoreIsBasionym(){
866
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
867
                "SynonymRelationship","SynonymRelationship_AUD",
868
                "HomotypicalGroup","HomotypicalGroup_AUD"};
869

    
870
        int nSynonyms = service.count(Synonym.class);
871
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
872
        int nNames = nameService.count(TaxonNameBase.class);
873
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
874

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

    
881
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
882
        TaxonNameBase synName2 = nameService.load(uuidSynonymName2);
883
        UUID name3Uuid = synonym1.getName().getUuid();
884
        TaxonNameBase synName1 = nameService.load(name3Uuid);
885
        synName1.addRelationshipFromName(synName2, NameRelationshipType.BASIONYM(), null);
886

    
887
        service.saveOrUpdate(synonym1);
888

    
889
        int nRelations = nameService.getAllRelationships(1000, 0).size();
890
        logger.info("number of name relations: " + nRelations);
891
        Assert.assertEquals("There should be 1 name relationship left in the database", 1, nRelations);
892
        SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
893
        NameDeletionConfigurator nameDeletionConfig = new NameDeletionConfigurator();
894
        nameDeletionConfig.setIgnoreIsBasionymFor(true);
895
        config.setNameDeletionConfig(nameDeletionConfig);
896

    
897
        DeleteResult result =service.deleteSynonym(synonym1, config);
898
        if (!result.isOk()){
899
        	Assert.fail();
900
        }
901

    
902

    
903
        logger.debug(result);
904
        this.commitAndStartNewTransaction(tableNames);
905

    
906
        nSynonyms = service.count(Synonym.class);
907
        Assert.assertEquals("There should still be 1 synonyms left in the database", 1, nSynonyms);
908
        nNames = nameService.count(TaxonNameBase.class);
909
        Assert.assertEquals("There should be 3 names left in the database ", 3, nNames);
910
        nRelations = service.countAllRelationships();
911
        //may change with better implementation of countAllRelationships (see #2653)
912
        nRelations = nameService.getAllRelationships(1000, 0).size();
913
        logger.info("number of name relations: " + nRelations);
914
        Assert.assertEquals("There should be no name relationship left in the database", 0, nRelations);
915
    }
916

    
917

    
918
    @Test
919
    @DataSet("TaxonServiceImplTest.testDeleteSynonym.xml")
920
    public final void testDeleteSynonymSynonymTaxonBooleanWithRollback(){
921
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
922
                "SynonymRelationship","SynonymRelationship_AUD",
923
                "HomotypicalGroup","HomotypicalGroup_AUD"};
924

    
925
        int nSynonyms = service.count(Synonym.class);
926
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
927
        int nNames = nameService.count(TaxonNameBase.class);
928
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
929
        int nRelations = service.countAllRelationships();
930

    
931

    
932
        //may change with better implementation of countAllRelationships (see #2653)
933

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

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

    
940
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
941
        TaxonNameBase name2 = nameService.load(uuidSynonymName2);
942
        synonym1.getName().addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
943

    
944
        service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
945

    
946
        this.rollback();
947
//		printDataSet(System.out, tableNames);
948
        this.startNewTransaction();
949

    
950
        nSynonyms = service.count(Synonym.class);
951
        Assert.assertEquals("There should still be 2 synonyms left in the database", 2, nSynonyms);
952
        nNames = nameService.count(TaxonNameBase.class);
953
        Assert.assertEquals("There should be 4 names left in the database", 4, nNames);
954
        nRelations = service.countAllRelationships();
955
        //may change with better implementation of countAllRelationships (see #2653)
956
        Assert.assertEquals("There should be 2 relationship in the database (the 2 synonym relationship) but no name relationship", 2, nRelations);
957

    
958
    }
959

    
960
    @Test
961
    @DataSet("TaxonServiceImplTest.testDeleteSynonym.xml")
962
    public final void testDeleteSynonymSynonymTaxonBooleanWithoutTransaction(){
963
        final String[]tableNames = {"TaxonBase","TaxonBase_AUD", "TaxonNameBase","TaxonNameBase_AUD",
964
                "SynonymRelationship","SynonymRelationship_AUD",
965
                "HomotypicalGroup","HomotypicalGroup_AUD"};
966

    
967
        int nSynonyms = service.count(Synonym.class);
968
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
969
        int nNames = nameService.count(TaxonNameBase.class);
970
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
971
        int nRelations = service.countAllRelationships();
972
        //may change with better implementation of countAllRelationships (see #2653)
973
        Assert.assertEquals("There should be 2 relationship in the database (the 2 synonym relationships) but no name relationship", 2, nRelations);
974

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

    
978
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
979
        TaxonNameBase name2 = nameService.load(uuidSynonymName2);
980
        synonym1.getName().addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
981

    
982
        service.saveOrUpdate(synonym1);
983
        nRelations = service.countAllRelationships();
984
        Assert.assertEquals("There should be two relationships in the database", 2, nRelations);
985
        this.setComplete();
986
        this.endTransaction();
987

    
988
//        printDataSet(System.out, tableNames);
989

    
990
        //out of wrapping transaction
991
        service.deleteSynonym(synonym1,  new SynonymDeletionConfigurator());
992

    
993
        this.startNewTransaction();
994

    
995
        nSynonyms = service.count(Synonym.class);
996
        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);
997
        nNames = nameService.count(TaxonNameBase.class);
998
        Assert.assertEquals("There should be 4 names left in the database", 4, nNames);
999
        nRelations = service.countAllRelationships();
1000
        Assert.assertEquals("There should be no taxon or synonym relationship in the database", 1, nRelations);
1001
        nRelations = nameService.getAllRelationships(1000,0).size();
1002
        Assert.assertEquals("There should be one name relationship in the database", 1, nRelations);
1003

    
1004
    }
1005

    
1006
    @Test
1007
    @DataSet("TaxonServiceImplTest.testInferredSynonyms.xml")
1008
    public void testCreateInferredSynonymy(){
1009

    
1010
        UUID classificationUuid = UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9");
1011
        Classification tree = classificationService.find(classificationUuid);
1012
        UUID taxonUuid = UUID.fromString("bc09aca6-06fd-4905-b1e7-cbf7cc65d783");
1013
        TaxonBase<?> taxonBase =  service.find(taxonUuid);
1014
        List <Synonym> synonyms = service.list(Synonym.class, null, null, null, null);
1015
        assertEquals("Number of synonyms should be 2",2,synonyms.size());
1016
        Taxon taxon = (Taxon)taxonBase;
1017

    
1018
        //synonyms = taxonDao.getAllSynonyms(null, null);
1019
        //assertEquals("Number of synonyms should be 2",2,synonyms.size());
1020
        List<Synonym> inferredSynonyms = service.createInferredSynonyms(taxon, tree, SynonymRelationshipType.INFERRED_EPITHET_OF(), true);
1021
        assertNotNull("there should be a new synonym ", inferredSynonyms);
1022
        assertEquals ("the name of inferred epithet should be SynGenus lachesis", "SynGenus lachesis sec. Sp. Pl.", inferredSynonyms.get(0).getTitleCache());
1023

    
1024
        inferredSynonyms = service.createInferredSynonyms(taxon, tree, SynonymRelationshipType.INFERRED_GENUS_OF(), true);
1025
        assertNotNull("there should be a new synonym ", inferredSynonyms);
1026
        assertEquals ("the name of inferred epithet should be SynGenus lachesis", "Acherontia ciprosus sec. Sp. Pl.", inferredSynonyms.get(0).getTitleCache());
1027

    
1028
        inferredSynonyms = service.createInferredSynonyms(taxon, tree, SynonymRelationshipType.POTENTIAL_COMBINATION_OF(), true);
1029
        assertNotNull("there should be a new synonym ", inferredSynonyms);
1030
        assertEquals ("the name of inferred epithet should be SynGenus lachesis", "SynGenus ciprosus sec. Sp. Pl.", inferredSynonyms.get(0).getTitleCache());
1031
        //assertTrue("set of synonyms should contain an inferred Synonym ", synonyms.contains(arg0))
1032
    }
1033

    
1034
    @Test
1035
    @DataSet("BlankDataSet.xml")
1036
    public final void testTaxonDeletionConfig(){
1037
        final String[]tableNames = {
1038
                "Classification", "Classification_AUD",
1039
                "TaxonBase","TaxonBase_AUD",
1040
                "TaxonNode","TaxonNode_AUD",
1041
                "TaxonNameBase","TaxonNameBase_AUD",
1042
                "SynonymRelationship","SynonymRelationship_AUD",
1043
                "TaxonRelationship", "TaxonRelationship_AUD",
1044
                "TaxonDescription", "TaxonDescription_AUD",
1045
                "HomotypicalGroup","HomotypicalGroup_AUD",
1046
                "PolytomousKey","PolytomousKey_AUD",
1047
                "PolytomousKeyNode","PolytomousKeyNode_AUD",
1048
                "Media","Media_AUD",
1049
                "WorkingSet","WorkingSet_AUD",
1050
                "DescriptionElementBase","DescriptionElementBase_AUD",
1051
        		"DeterminationEvent","DeterminationEvent_AUD",
1052
        		"SpecimenOrObservationBase","SpecimenOrObservationBase_AUD"};
1053

    
1054
        UUID uuidParent=UUID.fromString("b5271d4f-e203-4577-941f-00d76fa9f4ca");
1055
        UUID uuidChild1=UUID.fromString("326167f9-0b97-4e7d-b1bf-4ca47b82e21e");
1056
        UUID uuidSameAs=UUID.fromString("c2bb0f01-f2dd-43fb-ba12-2a85727ccb8d");
1057
        commitAndStartNewTransaction(tableNames);
1058
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1059
        service.save(testTaxon);
1060
        commitAndStartNewTransaction(tableNames);
1061
        int nTaxa = service.count(Taxon.class);
1062

    
1063
        Assert.assertEquals("There should be 4 taxa in the database", 4, nTaxa);
1064
        Taxon parent = (Taxon)service.find(TaxonGenerator.GENUS_UUID);
1065
        Assert.assertNotNull("Parent taxon should exist", parent);
1066
        Taxon child1 = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1067
        Assert.assertNotNull("Child taxon should exist", child1);
1068
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1069
        config.setDeleteTaxonNodes(false);
1070
        config.setDeleteMisappliedNamesAndInvalidDesignations(false);
1071
        //try {
1072
            //commitAndStartNewTransaction(tableNames);
1073

    
1074
        DeleteResult result = service.deleteTaxon(child1.getUuid(), config, null);
1075
        if (result.isOk()){
1076
            Assert.fail("Delete should throw an error as long as name is used in classification.");
1077
        }
1078

    
1079
        nTaxa = service.count(Taxon.class);
1080
        Assert.assertEquals("There should be 4 taxa in the database", 4, nTaxa);
1081
        child1 = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1082
        Assert.assertNotNull("Child taxon should exist", child1);
1083
        Assert.assertEquals("Child should belong to 1 node", 1, child1.getTaxonNodes().size());
1084

    
1085
        TaxonNode node = child1.getTaxonNodes().iterator().next();
1086
        child1.addSource(IdentifiableSource.NewInstance(OriginalSourceType.Import));
1087

    
1088
        SpecimenOrObservationBase<IIdentifiableEntityCacheStrategy> identifiedUnit = DerivedUnit.NewInstance(SpecimenOrObservationType.DerivedUnit);
1089
        DeterminationEvent determinationEvent = DeterminationEvent.NewInstance(child1, identifiedUnit);
1090
        //UUID eventUUID = eventService.save(determinationEvent);
1091
        UUID identifiedUnitUUID = occurenceService.save(identifiedUnit).getUuid();
1092

    
1093

    
1094
        TaxonNode parentNode = node.getParent();
1095
        parentNode =CdmBase.deproxy(parentNode, TaxonNode.class);
1096
        parentNode.deleteChildNode(node);
1097
        nodeService.save(parentNode);
1098
        //commitAndStartNewTransaction(tableNames);
1099

    
1100
       // try {
1101

    
1102
       result = service.deleteTaxon(child1
1103
    		   .getUuid(), config, null);
1104
       if (result.isOk()){
1105
           	Assert.fail("Delete should throw an exception because of the determination event");
1106
       }
1107

    
1108

    
1109

    
1110
        //determinationEvent = (DeterminationEvent)eventService.load(eventUUID);
1111
        commitAndStartNewTransaction(tableNames);
1112
        identifiedUnit = occurenceService.load(identifiedUnitUUID);
1113

    
1114
        occurenceService.delete(identifiedUnit);
1115

    
1116
        commitAndStartNewTransaction(tableNames);
1117
        child1 = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1118

    
1119
        assertEquals(0, child1.getTaxonNodes().size());
1120
       // try {
1121

    
1122
         result = service.deleteTaxon(child1.getUuid(), config, null);
1123

    
1124
         if (!result.isOk()){
1125
            Assert.fail("Delete should not throw an exception anymore");
1126
         }
1127

    
1128
        nTaxa = service.count(Taxon.class);
1129
        Assert.assertEquals("There should be 3 taxa in the database", 3, nTaxa);
1130

    
1131
        config.setDeleteTaxonNodes(true);
1132
        Taxon child2 =(Taxon) service.find(TaxonGenerator.SPECIES2_UUID);
1133

    
1134
       // try {
1135
        result = service.deleteTaxon(child2.getUuid(), config, child2.getTaxonNodes().iterator().next().getClassification().getUuid());
1136
        if (!result.isOk()){
1137
            Assert.fail("Delete should not throw an exception");
1138
        }
1139

    
1140

    
1141
        //service.find(uuid);
1142

    
1143
        nTaxa = service.count(Taxon.class);
1144
        Assert.assertEquals("There should be 2 taxa in the database",2, nTaxa);
1145
//		nNames = nameService.count(TaxonNameBase.class);
1146
//		Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
1147
//		int nRelations = service.countAllRelationships();
1148
//		Assert.assertEquals("There should be no relationship left in the database", 0, nRelations);
1149
    }
1150

    
1151

    
1152
    @Test
1153
    @DataSet(value="BlankDataSet.xml")
1154
    public final void testDeleteTaxon(){
1155

    
1156
        //create a small classification
1157
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1158

    
1159
        UUID uuid = service.save(testTaxon).getUuid();
1160

    
1161
        Taxon speciesTaxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1162
        Iterator<TaxonDescription> descriptionIterator = speciesTaxon.getDescriptions().iterator();
1163
        UUID descrUUID = null;
1164
        UUID descrElementUUID = null;
1165
        if (descriptionIterator.hasNext()){
1166
            TaxonDescription descr = descriptionIterator.next();
1167
            descrUUID = descr.getUuid();
1168
            descrElementUUID = descr.getElements().iterator().next().getUuid();
1169
        }
1170
        BotanicalName taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1171
        assertNotNull(taxonName);
1172

    
1173
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1174
        config.setDeleteNameIfPossible(false);
1175

    
1176

    
1177

    
1178
       // try {
1179

    
1180
        DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1181
        if (!result.isOk()){
1182
        	Assert.fail();
1183
        }
1184
        commitAndStartNewTransaction(null);
1185

    
1186
        taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1187
        Taxon taxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1188

    
1189
        //descriptionService.find(descrUUID);
1190
        assertNull(descriptionService.find(descrUUID));
1191
        assertNull(descriptionService.getDescriptionElementByUuid(descrElementUUID));
1192
        //assertNull(synName);
1193
        assertNotNull(taxonName);
1194
        assertNull(taxon);
1195
        config.setDeleteNameIfPossible(true);
1196
        Taxon newTaxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.SPECIES()), null);
1197
        service.save(newTaxon);
1198
        result = service.deleteTaxon(newTaxon.getUuid()
1199
        		, config, null);
1200
        if (!result.isOk()){
1201
        	Assert.fail();
1202
        }
1203

    
1204

    
1205
    }
1206

    
1207
    @Test
1208
    @DataSet(value="BlankDataSet.xml")
1209
    public final void testDeleteTaxonUsedInTaxonRelation(){
1210

    
1211
        //create a small classification
1212
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1213

    
1214
        UUID uuid = service.save(testTaxon).getUuid();
1215

    
1216
        Taxon speciesTaxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1217
        Taxon speciesTaxon2 = (Taxon)service.find(TaxonGenerator.SPECIES2_UUID);
1218
        speciesTaxon.addTaxonRelation(speciesTaxon2, TaxonRelationshipType.MISAPPLIED_NAME_FOR(), null, null);
1219

    
1220
        BotanicalName taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1221
        assertNotNull(taxonName);
1222

    
1223
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1224
        config.setDeleteNameIfPossible(false);
1225
        config.setDeleteTaxonRelationships(false);
1226

    
1227

    
1228
       // try {
1229

    
1230
        DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1231
        if (result.isOk()){
1232
            Assert.fail();
1233
        }
1234
        commitAndStartNewTransaction(null);
1235

    
1236
        taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1237
        Taxon taxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1238

    
1239

    
1240
        assertNotNull(taxonName);
1241
        assertNotNull(taxon);
1242

    
1243

    
1244
        config.setDeleteNameIfPossible(false);
1245
        config.setDeleteTaxonRelationships(true);
1246

    
1247

    
1248
       // try {
1249

    
1250
       result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1251
        if (!result.isOk()){
1252
            Assert.fail();
1253
        }
1254
        commitAndStartNewTransaction(null);
1255

    
1256

    
1257
        config.setDeleteNameIfPossible(true);
1258
        Taxon newTaxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.SPECIES()), null);
1259
        service.save(newTaxon);
1260
        result = service.deleteTaxon(newTaxon.getUuid()
1261
                , config, null);
1262
        if (!result.isOk()){
1263
            Assert.fail();
1264
        }
1265

    
1266

    
1267
    }
1268

    
1269
    @Test
1270
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="BlankDataSet.xml")
1271
    public final void testDeleteTaxonDeleteSynonymRelations(){
1272

    
1273
    	 final String[]tableNames = {
1274
                 "Classification", "Classification_AUD",
1275
                 "TaxonBase","TaxonBase_AUD",
1276
                 "TaxonNode","TaxonNode_AUD",
1277
                 "TaxonNameBase","TaxonNameBase_AUD"};
1278
    	 commitAndStartNewTransaction(tableNames);
1279
        //create a small classification
1280
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1281

    
1282
        UUID uuid = service.save(testTaxon).getUuid();
1283

    
1284
        Taxon speciesTaxon = (Taxon)service.find(TaxonGenerator.SPECIES2_UUID);
1285

    
1286
        SynonymRelationship synRel = speciesTaxon.getSynonymRelations().iterator().next();
1287
        UUID synonymRelationUuid = synRel.getUuid();
1288
        UUID synonymUuid = synRel.getSynonym().getUuid();
1289
        int i = service.getAllRelationships(1000, 0).size();
1290

    
1291
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1292
        config.setDeleteSynonymsIfPossible(false);
1293

    
1294

    
1295
       DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1296
        if (!result.isOk()){
1297
        	Assert.fail();
1298
        }
1299
        commitAndStartNewTransaction(null);
1300

    
1301
        Taxon taxon = (Taxon)service.find(TaxonGenerator.SPECIES2_UUID);
1302
        assertNull("The deleted taxon should no longer exist", taxon);
1303

    
1304
        assertNotNull("The synonym should still exist since DeleteSynonymsIfPossible was false", service.find(synonymUuid));
1305

    
1306
        for(RelationshipBase rel : service.getAllRelationships(1000, 0)){
1307
            if(rel instanceof SynonymRelationship && rel.getUuid().equals(synonymRelationUuid)){
1308
                Assert.fail("The SynonymRelationship should no longer exist");
1309
            }
1310
        }
1311
    }
1312

    
1313

    
1314
    @Test
1315
    @DataSet(value="BlankDataSet.xml")
1316
    public final void testDeleteTaxonNameUsedInOtherContext(){
1317

    
1318
        //create a small classification
1319
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1320

    
1321
        UUID uuid = service.save(testTaxon).getUuid();
1322

    
1323
        Taxon speciesTaxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1324

    
1325
        BotanicalName taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1326
        assertNotNull(taxonName);
1327
        BotanicalName fromName = BotanicalName.NewInstance(Rank.SPECIES());
1328
        taxonName.addRelationshipFromName(fromName, NameRelationshipType.VALIDATED_BY_NAME(), null);
1329

    
1330
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1331
        config.setDeleteNameIfPossible(true);
1332
        DeleteResult result = service.deleteTaxon(speciesTaxon.getUuid(), config, speciesTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1333
        if (!result.isOk()){
1334
        	Assert.fail();
1335
        }
1336
        commitAndStartNewTransaction(null);
1337

    
1338
        taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1339
        Taxon taxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1340
        //because of the namerelationship the name cannot be deleted
1341
        assertNotNull(taxonName);
1342
        assertNull(taxon);
1343

    
1344
    }
1345

    
1346
    @Test
1347
    @DataSet(value="BlankDataSet.xml")
1348
    public final void testDeleteTaxonNameUsedInTwoClassificationsDeleteAllNodes(){
1349
        commitAndStartNewTransaction(null);
1350
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1351
        //create a small classification
1352
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1353

    
1354
        UUID uuid = service.save(testTaxon).getUuid();
1355
        //BotanicalName name = nameService.find(uuid);
1356
        Set<TaxonNode> nodes = testTaxon.getTaxonNodes();
1357
        TaxonNode node = nodes.iterator().next();
1358
        List<TaxonNode> childNodes = node.getChildNodes();
1359
        TaxonNode childNode = childNodes.iterator().next();
1360
        UUID childUUID = childNode.getTaxon().getUuid();
1361
        Classification secondClassification = TaxonGenerator.getTestClassification("secondClassification");
1362

    
1363
        secondClassification.addChildTaxon(testTaxon, null, null);
1364
        //delete the taxon in all classifications
1365
        config.setDeleteInAllClassifications(true);
1366
       DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, null);
1367
       if (!result.isOk()){
1368
        	Assert.fail();
1369
        }
1370
        commitAndStartNewTransaction(null);
1371
        Taxon tax = (Taxon)service.find(uuid);
1372
        assertNull(tax);
1373
        Taxon childTaxon = (Taxon)service.find(childUUID);
1374
        assertNull(tax);
1375
        commitAndStartNewTransaction(null);
1376

    
1377

    
1378

    
1379

    
1380

    
1381
    }
1382

    
1383
    @Test
1384
    @DataSet(value="BlankDataSet.xml")
1385
    public final void testDeleteTaxonNameUsedInTwoClassificationsDoNotDeleteAllNodes(){
1386
        // delete the taxon only in second classification, this should delete only the nodes, not the taxa
1387
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1388
        UUID uuid = service.save(testTaxon).getUuid();
1389
        Classification secondClassification = TaxonGenerator.getTestClassification("secondClassification");
1390
        Set<TaxonNode> nodes = testTaxon.getTaxonNodes();
1391
        TaxonNode node = nodes.iterator().next();
1392
        List<TaxonNode> childNodes = node.getChildNodes();
1393
        TaxonNode childNode = childNodes.iterator().next();
1394
        UUID childUUID = childNode.getTaxon().getUuid();
1395
        childNode = secondClassification.addChildTaxon(testTaxon, null, null);
1396
        UUID childNodeUUID = childNode.getUuid();
1397

    
1398
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1399
        config.setDeleteInAllClassifications(false);
1400
       //     try {
1401
       DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, secondClassification.getUuid());
1402
/*                Assert.fail("The taxon should not be deletable because it is used in a second classification and the configuration is set to deleteInAllClassifications = false");
1403
            } catch (DataChangeNoRollbackException e) {
1404
                logger.debug(e.getMessage());
1405
            }
1406
  */
1407

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

    
1412
        //commitAndStartNewTransaction(null);
1413
        Taxon tax = (Taxon)service.find(uuid);
1414
        assertNotNull(tax);
1415
        Taxon childTaxon = (Taxon)service.find(childUUID);
1416
        assertNotNull(tax);
1417
        node = nodeService.find(childNodeUUID);
1418
        assertNull(node);
1419
    }
1420

    
1421
    @Test
1422
    @DataSet(value="BlankDataSet.xml")
1423
    public final void testTaxonNodeDeletionConfiguratorMoveToParent(){
1424
        //test childHandling MOVE_TO_PARENT:
1425
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1426
        UUID uuid = service.save(testTaxon).getUuid();
1427

    
1428
        Taxon topMost = Taxon.NewInstance(BotanicalName.NewInstance(Rank.FAMILY()), null);
1429

    
1430
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1431
        TaxonNode node =nodes.next();
1432
        Classification classification = node.getClassification();
1433
        classification.addParentChild(topMost, testTaxon, null, null);
1434
        UUID topMostUUID = service.save(topMost).getUuid();
1435

    
1436
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1437
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.MOVE_TO_PARENT);
1438

    
1439

    
1440
        DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, classification.getUuid());
1441
        if(!result.isOk()){
1442
         	Assert.fail();
1443
       	}
1444

    
1445
        commitAndStartNewTransaction(null);
1446
        Taxon tax = (Taxon)service.find(uuid);
1447
        assertNull(tax);
1448
        tax = (Taxon)service.find(topMostUUID);
1449
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1450
        assertNotNull(topMostNodes);
1451
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1452
        nodes = topMostNodes.iterator();
1453
        TaxonNode topMostNode = nodes.next();
1454
        int size = topMostNode.getChildNodes().size();
1455

    
1456
        assertEquals(2, size);
1457
    }
1458

    
1459
    @Test
1460
    @DataSet(value="BlankDataSet.xml")
1461
    public final void testTaxonNodeDeletionConfiguratorDeleteChildren(){
1462
        //test childHandling DELETE:
1463
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1464
        UUID uuid = service.save(testTaxon).getUuid();
1465

    
1466
        Taxon topMost = Taxon.NewInstance(BotanicalName.NewInstance(Rank.FAMILY()), null);
1467

    
1468
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1469
        TaxonNode node =nodes.next();
1470
        UUID taxonNodeUUID = node.getUuid();
1471
        Classification classification = node.getClassification();
1472
        classification.addParentChild(topMost, testTaxon, null, null);
1473
        UUID topMostUUID = service.save(topMost).getUuid();
1474

    
1475
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1476
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.DELETE);
1477

    
1478
       // try {
1479
        DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, testTaxon.getTaxonNodes().iterator().next().getClassification().getUuid());
1480
        if(!result.isOk()){
1481
         	Assert.fail();
1482
       	}
1483
        commitAndStartNewTransaction(null);
1484
        Taxon tax = (Taxon)service.find(uuid);
1485
        assertNull(tax);
1486
        tax = (Taxon)service.find(topMostUUID);
1487
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1488
        assertNotNull(topMostNodes);
1489
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1490
        nodes = topMostNodes.iterator();
1491
        TaxonNode topMostNode = nodes.next();
1492
        int size = topMostNode.getChildNodes().size();
1493
        node = nodeService.find(taxonNodeUUID);
1494
        assertNull(node);
1495
        assertEquals(0, size);
1496
    }
1497

    
1498

    
1499
    @Test
1500
    @DataSet(value="BlankDataSet.xml")
1501
    public final void testTaxonDeletionConfiguratorDeleteMarker(){
1502
        //test childHandling DELETE:
1503
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1504
        UUID uuid = service.save(testTaxon).getUuid();
1505

    
1506
        Taxon topMost = Taxon.NewInstance(BotanicalName.NewInstance(Rank.FAMILY()), null);
1507

    
1508
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1509
        TaxonNode node =nodes.next();
1510
        Classification classification = node.getClassification();
1511
        classification.addParentChild(topMost, testTaxon, null, null);
1512
        UUID topMostUUID = service.save(topMost).getUuid();
1513
        Marker marker = Marker.NewInstance(testTaxon, true, MarkerType.IS_DOUBTFUL());
1514
        testTaxon.addMarker(marker);
1515
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1516
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.DELETE);
1517

    
1518
        DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, node.getClassification().getUuid());
1519

    
1520
        if(!result.isOk()){
1521
         	Assert.fail();
1522
       	}
1523
        commitAndStartNewTransaction(null);
1524
        Taxon tax = (Taxon)service.find(uuid);
1525
        assertNull(tax);
1526
        tax = (Taxon)service.find(topMostUUID);
1527
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1528
        assertNotNull(topMostNodes);
1529
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1530
        nodes = topMostNodes.iterator();
1531
        TaxonNode topMostNode = nodes.next();
1532
        int size = topMostNode.getChildNodes().size();
1533

    
1534
        assertEquals(0, size);
1535
    }
1536

    
1537

    
1538
    @Test
1539
    @DataSet(value="BlankDataSet.xml")
1540
    public final void testTaxonDeletionConfiguratorTaxonWithMisappliedName(){
1541

    
1542
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1543
        UUID uuid = service.save(testTaxon).getUuid();
1544

    
1545
        Taxon misappliedName = Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()), null);
1546

    
1547
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1548
        TaxonNode node =nodes.next();
1549
        testTaxon.addMisappliedName(misappliedName, null, null);
1550
        UUID misappliedNameUUID = service.save(misappliedName).getUuid();
1551

    
1552
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1553
        config.setDeleteMisappliedNamesAndInvalidDesignations(true);
1554

    
1555
        DeleteResult result  = service.deleteTaxon(testTaxon.getUuid(), config, node.getClassification().getUuid());
1556
        if(!result.isOk()){
1557
         	Assert.fail();
1558
       	}
1559
        commitAndStartNewTransaction(null);
1560
        Taxon tax = (Taxon)service.find(uuid);
1561
        assertNull(tax);
1562
        tax = (Taxon)service.find(misappliedNameUUID);
1563
        //TODO: is that correct or should it be deleted because there is no relation to anything
1564
        assertNull(tax);
1565

    
1566
    }
1567
    @Test
1568
    @DataSet(value="BlankDataSet.xml")
1569
    public final void testTaxonDeletionConfiguratorTaxonWithMisappliedNameDoNotDelete(){
1570

    
1571
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1572
        UUID uuid = service.save(testTaxon).getUuid();
1573

    
1574
        Taxon misappliedName = Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()), null);
1575

    
1576
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1577
        TaxonNode node =nodes.next();
1578
        testTaxon.addMisappliedName(misappliedName, null, null);
1579
        UUID misappliedNameUUID = service.save(misappliedName).getUuid();
1580

    
1581
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1582
        config.setDeleteMisappliedNamesAndInvalidDesignations(false);
1583

    
1584
        DeleteResult result = service.deleteTaxon(testTaxon.getUuid(), config, node.getClassification().getUuid());
1585
        if(!result.isOk()){
1586
         	Assert.fail();
1587
       	}
1588
        commitAndStartNewTransaction(null);
1589
        Taxon tax = (Taxon)service.find(uuid);
1590
        assertNull(tax);
1591
        tax = (Taxon)service.find(misappliedNameUUID);
1592
        //TODO: is that correct or should it be deleted because there is no relation to anything
1593
        assertNotNull(tax);
1594

    
1595
    }
1596

    
1597
    @Test
1598
    @DataSet(value="BlankDataSet.xml")
1599
    public final void testTaxonDeletionConfiguratorTaxonMisappliedName(){
1600

    
1601
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1602
        UUID uuid = service.save(testTaxon).getUuid();
1603

    
1604
        Taxon misappliedNameTaxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()), null);
1605

    
1606
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1607
        TaxonNode node =nodes.next();
1608
        testTaxon.addMisappliedName(misappliedNameTaxon, null, null);
1609
        UUID misappliedNameUUID = service.save(misappliedNameTaxon).getUuid();
1610
        misappliedNameTaxon = (Taxon)service.find(misappliedNameUUID);
1611
        UUID misNameUUID = misappliedNameTaxon.getName().getUuid();
1612

    
1613
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1614

    
1615

    
1616
       // try {
1617
            service.deleteTaxon(misappliedNameTaxon.getUuid(), config,null);
1618
       // } catch (DataChangeNoRollbackException e) {
1619
         //   e.printStackTrace();
1620

    
1621
        //}
1622

    
1623
        commitAndStartNewTransaction(null);
1624
        Taxon tax = (Taxon)service.find(uuid);
1625
        assertNotNull(tax);
1626
        tax = (Taxon)service.find(misappliedNameUUID);
1627
        BotanicalName name = (BotanicalName) nameService.find(misNameUUID);
1628

    
1629
        assertNull(tax);
1630
        assertNull(name);
1631

    
1632
    }
1633

    
1634
    @Test
1635
    @DataSet(value="BlankDataSet.xml")
1636
    public final void testLlistIncludedTaxa(){
1637
    	Reference citation = null;
1638
    	String microcitation = null;
1639

    
1640
    	//Data
1641
    	Classification cl1 = Classification.NewInstance("testClassification1");
1642
    	Classification cl2 = Classification.NewInstance("testClassification2");
1643
    	Classification cl3 = Classification.NewInstance("testClassification3");
1644

    
1645
    	Taxon c1Genus = Taxon.NewInstance(null, null);c1Genus.setUuid(UUID.fromString("daa24f6f-7e38-4668-b385-10c789212e4e"));
1646
    	Taxon c1Species = Taxon.NewInstance(null, null);c1Species.setUuid(UUID.fromString("1c1d0566-67d0-4806-bf23-ecf55f4b9118"));
1647
    	Taxon c1SubSpecies1 = Taxon.NewInstance(null, null);c1SubSpecies1.setUuid(UUID.fromString("96ae2fad-76df-429f-b179-42e00838fea4"));
1648
    	Taxon c1SubSpecies2 = Taxon.NewInstance(null, null);c1SubSpecies2.setUuid(UUID.fromString("5d3f6147-ca72-40e0-be8a-6c835a09a579"));
1649
    	cl1.addParentChild(c1Genus, c1Species, null, null);
1650
    	cl1.addParentChild(c1Species, c1SubSpecies1, null, null);
1651
    	cl1.addParentChild(c1Species, c1SubSpecies2, null, null);
1652

    
1653
    	Taxon c2Genus = Taxon.NewInstance(null, null);c2Genus.setUuid(UUID.fromString("ed0ec006-3ac8-4a12-ae13-fdf2a13dedbe"));
1654
    	Taxon c2Species = Taxon.NewInstance(null, null);c2Species.setUuid(UUID.fromString("1027eb18-1c26-450e-a299-981b775ebc3c"));
1655
    	Taxon c2SubSpecies1 = Taxon.NewInstance(null, null);c2SubSpecies1.setUuid(UUID.fromString("61f039c8-01f3-4f5d-8e16-1602139774e7"));
1656
    	Taxon c2SubSpecies2 = Taxon.NewInstance(null, null);c2SubSpecies2.setUuid(UUID.fromString("2ed6b6f8-05f9-459a-a075-2bca57e3013e"));
1657
    	cl2.addParentChild(c2Genus, c2Species, null, null);
1658
    	cl2.addParentChild(c2Species, c2SubSpecies1, null, null);
1659
    	cl2.addParentChild(c2Species, c2SubSpecies2, null, null);
1660

    
1661
    	Taxon c3Genus = Taxon.NewInstance(null, null);c3Genus.setUuid(UUID.fromString("407dfc8d-7a4f-4370-ada4-76c1a8279d1f"));
1662
    	Taxon c3Species = Taxon.NewInstance(null, null);c3Species.setUuid(UUID.fromString("b6d34fc7-4aa7-41e5-b633-86f474edbbd5"));
1663
    	Taxon c3SubSpecies1 = Taxon.NewInstance(null, null);c3SubSpecies1.setUuid(UUID.fromString("01c07585-a422-40cd-9339-a74c56901d9f"));
1664
    	Taxon c3SubSpecies2 = Taxon.NewInstance(null, null);c3SubSpecies2.setUuid(UUID.fromString("390c8e23-e05f-4f89-b417-50cf080f4c91"));
1665
    	cl3.addParentChild(c3Genus, c3Species, null, null);
1666
    	cl3.addParentChild(c3Species, c3SubSpecies1, null, null);
1667
    	cl3.addParentChild(c3Species, c3SubSpecies2, null, null);
1668

    
1669
    	classificationService.save(cl1);
1670
    	classificationService.save(cl2);
1671
    	classificationService.save(cl3);
1672

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

    
1677
    	TaxonRelationship rel = c1Species.addTaxonRelation(c2Species, TaxonRelationshipType.CONGRUENT_TO(), citation, microcitation);
1678
    	rel.setDoubtful(true);
1679
    	c1Species.addTaxonRelation(c4Species, TaxonRelationshipType.INCLUDES(), citation, microcitation);
1680
    	c2Species.addTaxonRelation(c1SubSpecies2, TaxonRelationshipType.INCLUDES(), citation, microcitation);
1681

    
1682
    	service.saveOrUpdate(c1Species);
1683
       	service.saveOrUpdate(c2Species);
1684

    
1685
    	//Tests
1686
       	//default starting at species 1
1687
       	IncludedTaxaDTO dto = service.listIncludedTaxa(c1Species.getUuid(), new IncludedTaxonConfiguration(null, true, false));
1688
    	Assert.assertNotNull("IncludedTaxaDTO", dto);
1689
    	Assert.assertEquals("Result should contain 7 taxa: c1Species", 7, dto.getIncludedTaxa().size());
1690
    	Assert.assertNotNull("date should not be null", dto.getDate());
1691
//    	Assert.assertTrue(dto.contains(taxonUuid));
1692
        //same without doubtful
1693
    	dto = service.listIncludedTaxa(c1Species.getUuid(), new IncludedTaxonConfiguration(null, false, false));
1694
    	Assert.assertEquals(4, dto.getIncludedTaxa().size());
1695

    
1696
    	//other example starting at Genus2
1697
    	dto = service.listIncludedTaxa(c2Genus.getUuid(), new IncludedTaxonConfiguration(null, true, false));
1698
    	Assert.assertEquals(8, dto.getIncludedTaxa().size());
1699
    	//same without doubtful
1700
    	dto = service.listIncludedTaxa(c2Genus.getUuid(), new IncludedTaxonConfiguration(null, false, false));
1701
    	Assert.assertEquals(5, dto.getIncludedTaxa().size());
1702

    
1703
    	//only congruent
1704
    	dto = service.listIncludedTaxa(c1Species.getUuid(), new IncludedTaxonConfiguration(null, true, true));
1705
    	Assert.assertEquals(2, dto.getIncludedTaxa().size());
1706
    	//same without doubtful
1707
    	dto = service.listIncludedTaxa(c1Species.getUuid(), new IncludedTaxonConfiguration(null, false, true));
1708
    	Assert.assertEquals(1, dto.getIncludedTaxa().size());
1709

    
1710

    
1711

    
1712

    
1713
    }
1714

    
1715
    @Test
1716
    public void testDeleteDescriptions(){
1717
    	try {
1718
			createTestDataSet();
1719
		} catch (FileNotFoundException e) {
1720
			// TODO Auto-generated catch block
1721
			e.printStackTrace();
1722
		}
1723
    	TaxonDescription description = TaxonDescription.NewInstance(taxWithoutSyn);
1724
    	SpecimenOrObservationBase<IIdentifiableEntityCacheStrategy<FieldUnit>> specimen = FieldUnit.NewInstance();
1725
    	UUID uuid = occurenceService.saveOrUpdate(specimen);
1726
    	DescriptionElementBase element = IndividualsAssociation.NewInstance(specimen);
1727
    	description.addElement(element);
1728
    	service.saveOrUpdate(taxWithoutSyn);
1729

    
1730

    
1731
    	Taxon tax = (Taxon)service.find(uuidTaxWithoutSyn);
1732
    	Set<TaxonDescription> descr =  tax.getDescriptions();
1733
    	assertEquals(1, descr.size());
1734
    	description = descr.iterator().next();
1735
    	UUID uuidDescr = description.getUuid();
1736
    	UUID uuidDescEl = description.getElements().iterator().next().getUuid();
1737

    
1738
    	descriptionService.deleteDescription(description);
1739
    	service.saveOrUpdate(tax);
1740

    
1741
    	description = (TaxonDescription) descriptionService.find(uuidDescr);
1742
    	specimen = occurenceService.find(uuid);
1743
    	assertNull(description);
1744
    	DeleteResult result = occurenceService.delete(specimen);
1745
    	assertTrue(result.isOk());
1746

    
1747
    }
1748

    
1749
    @Test
1750
    public void testRemoveDescriptionsFromTaxa(){
1751
        try {
1752
            createTestDataSet();
1753
        } catch (FileNotFoundException e) {
1754
            // TODO Auto-generated catch block
1755
            e.printStackTrace();
1756
        }
1757
        TaxonDescription description = TaxonDescription.NewInstance(taxWithoutSyn);
1758
        SpecimenOrObservationBase<IIdentifiableEntityCacheStrategy<FieldUnit>> specimen = FieldUnit.NewInstance();
1759
        UUID uuid = occurenceService.saveOrUpdate(specimen);
1760
        DescriptionElementBase element = IndividualsAssociation.NewInstance(specimen);
1761
        description.addElement(element);
1762
        service.saveOrUpdate(taxWithoutSyn);
1763

    
1764

    
1765
        Taxon tax = (Taxon)service.find(uuidTaxWithoutSyn);
1766
        Set<TaxonDescription> descr =  tax.getDescriptions();
1767
        assertEquals(1, descr.size());
1768
        description = descr.iterator().next();
1769
        UUID uuidDescr = description.getUuid();
1770

    
1771

    
1772
        tax.removeDescription(description, true);
1773
        service.saveOrUpdate(tax);
1774

    
1775
        description = (TaxonDescription) descriptionService.find(uuidDescr);
1776
        specimen = occurenceService.find(uuid);
1777
        assertNotNull(description);
1778
        DeleteResult result = occurenceService.delete(specimen);
1779
        assertTrue(result.isOk());
1780

    
1781
    }
1782

    
1783

    
1784
    /* (non-Javadoc)
1785
     * @see eu.etaxonomy.cdm.test.integration.CdmIntegrationTest#createTestData()
1786
     */
1787
    @Override
1788
    public void createTestDataSet() throws FileNotFoundException {
1789
    	Rank rank = Rank.SPECIES();
1790

    
1791
        taxWithoutSyn = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test1", null, null, null, null, null, null, null), null);
1792
        taxWithSyn = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test3", null, null, null, null, null, null, null), null);
1793
        tax2WithSyn = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test5", null, null, null, null, null, null, null), null);
1794
        synonym = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test2", null, null, null, null, null, null, null), null);
1795
        synonym2 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test4", null, null, null, null, null, null, null), null);
1796
        synonym2.getName().setHomotypicalGroup(synonym.getHomotypicGroup());
1797

    
1798
        taxWithSyn.addSynonym(synonym, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
1799
        taxWithSyn.addSynonym(synonym2, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
1800

    
1801
        uuidTaxWithoutSyn = service.save(taxWithoutSyn).getUuid();
1802
        uuidSyn = service.save(synonym).getUuid();
1803
        uuidSyn2 = service.save(synonym2).getUuid();
1804
        uuidTaxWithSyn =service.save(taxWithSyn).getUuid();
1805

    
1806
    }
1807

    
1808

    
1809
}
1810

    
1811

    
1812

    
(25-25/31)