Project

General

Profile

Download (79 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.util.ArrayList;
18
import java.util.Iterator;
19
import java.util.List;
20
import java.util.Set;
21
import java.util.UUID;
22

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

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

    
66
/**
67
 * @author a.mueller
68
 */
69

    
70

    
71
public class TaxonServiceImplTest extends CdmTransactionalIntegrationTest {
72
    private static final Logger logger = Logger.getLogger(TaxonServiceImplTest.class);
73

    
74
    @SpringBeanByType
75
    private ITaxonService service;
76

    
77
    @SpringBeanByType
78
    private INameService nameService;
79

    
80
    @SpringBeanByType
81
    private IReferenceService referenceService;
82

    
83
    @SpringBeanByType
84
    private IClassificationService classificationService;
85

    
86
    @SpringBeanByType
87
    private ITaxonNodeService nodeService;
88

    
89
    @SpringBeanByType
90
    private IDescriptionService descriptionService;
91
    
92
    @SpringBeanByType
93
    private IMarkerService markerService;
94

    
95
    @SpringBeanByType
96
    private IEventBaseService eventService;
97
    
98
    @SpringBeanByType
99
    private IOccurrenceService occurenceService;
100

    
101

    
102

    
103
/****************** TESTS *****************************/
104

    
105

    
106
    /**
107
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#getTaxonByUuid(java.util.UUID)}.
108
     */
109
    @Test
110
    public final void testGetTaxonByUuid() {
111
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
112
        UUID uuid = service.save(expectedTaxon);
113
        TaxonBase<?> actualTaxon = service.find(uuid);
114
        assertEquals(expectedTaxon, actualTaxon);
115
    }
116

    
117
    /**
118
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#saveTaxon(eu.etaxonomy.cdm.model.taxon.TaxonBase)}.
119
     */
120
    @Test
121
    public final void testSaveTaxon() {
122
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
123
        UUID uuid = service.save(expectedTaxon);
124
        TaxonBase<?> actualTaxon = service.find(uuid);
125
        assertEquals(expectedTaxon, actualTaxon);
126
    }
127

    
128
    @Test
129
    public final void testSaveOrUpdateTaxon() {
130
        Taxon expectedTaxon = Taxon.NewInstance(null, null);
131
        UUID uuid = service.save(expectedTaxon);
132
        TaxonBase<?> actualTaxon = service.find(uuid);
133
        assertEquals(expectedTaxon, actualTaxon);
134

    
135
        actualTaxon.setName(BotanicalName.NewInstance(Rank.SPECIES()));
136
        try{
137
            service.saveOrUpdate(actualTaxon);
138
        }catch(Exception e){
139
            Assert.fail();
140
        }
141
    }
142
    /**
143
     * Test method for {@link eu.etaxonomy.cdm.api.service.TaxonServiceImpl#removeTaxon(eu.etaxonomy.cdm.model.taxon.TaxonBase)}.
144
     */
145
    @Test
146
    public final void testRemoveTaxon() {
147
        Taxon taxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.UNKNOWN_RANK()), null);
148
        UUID uuid = service.save(taxon);
149
       // try {
150
			service.deleteTaxon(taxon, null, null);
151
		/*} catch (DataChangeNoRollbackException e) {
152
			// TODO Auto-generated catch block
153
			e.printStackTrace();
154
		}*/
155
        TaxonBase<?> actualTaxon = service.find(uuid);
156
        assertNull(actualTaxon);
157
    }
158

    
159

    
160
    @Test
161
    public final void testMakeTaxonSynonym() {
162
        Rank rank = Rank.SPECIES();
163
        Taxon tax1 = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test1", null, null, null, null, null, null, null), null);
164
        Synonym synonym = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test2", null, null, null, null, null, null, null), null);
165
        tax1.addHomotypicSynonym(synonym, null, null);
166
        UUID uuidTaxon = service.save(tax1);
167
        UUID uuidSyn = service.save(synonym);
168

    
169
        service.swapSynonymAndAcceptedTaxon(synonym, tax1);
170

    
171
        // find forces flush
172
        TaxonBase<?> tax = service.find(uuidTaxon);
173
        TaxonBase<?> syn = service.find(uuidSyn);
174

    
175
        assertTrue(tax.getName().getTitleCache().equals("Test2"));
176

    
177
        HomotypicalGroup groupTest = tax.getHomotypicGroup();
178
        HomotypicalGroup groupTest2 = syn.getHomotypicGroup();
179
        assertEquals(groupTest, groupTest2);
180
        
181
    }
182

    
183
    @Test
184
    public final void testChangeSynonymToAcceptedTaxon(){
185
        Rank rank = Rank.SPECIES();
186
        //HomotypicalGroup group = HomotypicalGroup.NewInstance();
187
        Taxon taxWithoutSyn = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test1", null, null, null, null, null, null, null), null);
188
        Taxon taxWithSyn = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test3", null, null, null, null, null, null, null), null);
189
        Synonym synonym = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test2", null, null, null, null, null, null, null), null);
190
        Synonym synonym2 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test4", null, null, null, null, null, null, null), null);
191
        synonym2.getName().setHomotypicalGroup(synonym.getHomotypicGroup());
192
        //tax2.addHeterotypicSynonymName(synonym.getName());
193
        taxWithSyn.addSynonym(synonym, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
194
        taxWithSyn.addSynonym(synonym2, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
195

    
196
        service.save(taxWithoutSyn);
197
        UUID uuidSyn = service.save(synonym);
198
        service.save(synonym2);
199
        UUID uuidTaxWithSyn =service.save(taxWithSyn);
200

    
201
        Taxon taxon = null;
202
        try {
203
            taxon = service.changeSynonymToAcceptedTaxon(synonym, taxWithSyn, true, true, null, null);
204
        } catch (HomotypicalGroupChangeException e) {
205
            Assert.fail("Invocation of change method should not throw an exception");
206
        }
207
        taxWithSyn = null;
208
        //test flush (resave deleted object)
209
        TaxonBase<?> syn = service.find(uuidSyn);
210
        taxWithSyn = (Taxon)service.find(uuidTaxWithSyn);
211
        Taxon taxNew = (Taxon)service.find(taxon.getUuid());
212
        assertNull(syn);
213
        assertNotNull(taxWithSyn);
214
        assertNotNull(taxNew);
215

    
216
        Assert.assertEquals("New taxon should have 1 synonym relationship (the old homotypic synonym)", 1, taxon.getSynonymRelations().size());
217
    }
218

    
219

    
220

    
221
    @Test
222
    public final void testChangeSynonymToAcceptedTaxonSynonymForTwoTaxa(){
223
        Rank rank = Rank.SPECIES();
224
        //HomotypicalGroup group = HomotypicalGroup.NewInstance();
225
        Taxon taxWithoutSyn = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test1", null, null, null, null, null, null, null), null);
226
        Taxon tax2WithSyn = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test5", null, null, null, null, null, null, null), null);
227
        Taxon taxWithSyn = Taxon.NewInstance(BotanicalName.NewInstance(rank, "Test3", null, null, null, null, null, null, null), null);
228
        Synonym synonym = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test2", null, null, null, null, null, null, null), null);
229
        Synonym synonym2 = Synonym.NewInstance(BotanicalName.NewInstance(rank, "Test4", null, null, null, null, null, null, null), null);
230
        //synonym2.getName().setHomotypicalGroup(taxWithSyn.getHomotypicGroup());
231
        //tax2.addHeterotypicSynonymName(synonym.getName());
232
        taxWithSyn.addSynonym(synonym, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
233
        taxWithSyn.addSynonym(synonym2, SynonymRelationshipType.HOMOTYPIC_SYNONYM_OF());
234
        tax2WithSyn.addSynonym(synonym, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
235

    
236
        service.save(taxWithoutSyn);
237

    
238
        UUID uuidSyn = service.save(synonym);
239
        service.save(synonym2);
240
        UUID uuidTaxWithSyn =service.save(taxWithSyn);
241
        service.save(tax2WithSyn);
242

    
243

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

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

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

    
265
    /**
266
     * Old implementation taken from {@link TaxonServiceImplBusinessTest} for old version of method.
267
     * 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)}.
268
     */
269
    @Test
270
    public final void testMoveSynonymToAnotherTaxon_OLD() {
271
        SynonymRelationshipType heteroTypicSynonymRelationshipType = SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF();
272
        Reference<?> reference = ReferenceFactory.newGeneric();
273
        String referenceDetail = "test";
274

    
275
        NonViralName<?> t1n = NonViralName.NewInstance(null);
276
        Taxon t1 = Taxon.NewInstance(t1n, reference);
277
        NonViralName<?> t2n = NonViralName.NewInstance(null);
278
        Taxon t2 = Taxon.NewInstance(t2n, reference);
279
        NonViralName<?> s1n = NonViralName.NewInstance(null);
280
        Synonym s1 = Synonym.NewInstance(s1n, reference);
281
        t1.addSynonym(s1, heteroTypicSynonymRelationshipType);
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
        
593

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

    
596

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

    
603
        this.commitAndStartNewTransaction(tableNames);
604

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

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

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

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

    
629

    
630
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
631
        service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
632

    
633
        this.commitAndStartNewTransaction(tableNames);
634

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

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

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

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

    
662

    
663
        Taxon taxon2 = (Taxon)service.load(uuidTaxon2);
664
        
665
        List<String> initStrat = new ArrayList<String>();
666
        initStrat.add("markers");
667
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1, initStrat);
668

    
669
        taxon2.removeSynonym(synonym1, false);
670
        service.saveOrUpdate(taxon2);
671

    
672
        commitAndStartNewTransaction(null);
673

    
674
        nSynonyms = service.count(Synonym.class);
675
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
676
        nNames = nameService.count(TaxonNameBase.class);
677
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
678
        int nRelations = service.countAllRelationships();
679
        Assert.assertEquals("There should be 1 relationship left in the database", 1, nRelations);
680
        Marker marker1 = Marker.NewInstance(MarkerType.IMPORTED(), true);
681
        Marker marker2 = Marker.NewInstance(MarkerType.COMPUTED(), true);
682
        synonym1.addMarker(marker1);
683
        synonym1.addMarker(marker2);
684
        service.update(synonym1);
685
        synonym1 =(Synonym) service.load(uuidSynonym1);
686
       
687
        
688
        Set<Marker> markers = synonym1.getMarkers();
689
        Marker marker = markers.iterator().next();
690
        UUID markerUUID = marker.getUuid();
691
       // taxon2 = (Taxon)service.load(uuidTaxon2);
692
        synonym1 = (Synonym)service.load(uuidSynonym1);
693

    
694
        String result = service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
695
        try {
696
        	UUID uuid = UUID.fromString(result);
697
        }catch(IllegalArgumentException e){
698
        	
699
        }
700
        commitAndStartNewTransaction(tableNames);
701
        synonym1.removeMarker(marker1);
702
        synonym1.removeMarker(marker2);
703
        service.update(synonym1);
704
        result = service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
705
        try {
706
        	UUID uuid = UUID.fromString(result);
707
        }catch(IllegalArgumentException e){
708
        	Assert.fail();
709
        }
710
        commitAndStartNewTransaction(tableNames);
711
        nSynonyms = service.count(Synonym.class);
712
        Assert.assertEquals("There should be 1 synonym left in the database", 1, nSynonyms);
713
        nNames = nameService.count(TaxonNameBase.class);
714
        Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
715
        nRelations = service.countAllRelationships();
716
        Assert.assertEquals("There should be no relationship left in the database", 0, nRelations);
717
        marker = markerService.load(markerUUID);
718
        assertNull(marker);
719

    
720
    }
721

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

    
730

    
731
        int nSynonyms = service.count(Synonym.class);
732
        Assert.assertEquals("There should be 2 synonyms in the database", 2, nSynonyms);
733
        int nNames = nameService.count(TaxonNameBase.class);
734
        Assert.assertEquals("There should  be 4 names in the database", 4, nNames);
735

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

    
741
        Taxon taxon1 = (Taxon)service.load(uuidTaxon1);
742
        Taxon taxon2 = (Taxon)service.load(uuidTaxon2);
743
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
744
       
745
        service.deleteSynonym(synonym1, taxon1, new SynonymDeletionConfigurator());
746

    
747
        this.commitAndStartNewTransaction(tableNames);
748

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

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

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

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

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

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

    
784
        service.saveOrUpdate(synonym1);
785

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

    
791
        service.deleteSynonym(synonym1, config);
792

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

    
805

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

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

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

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

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

    
839
        service.saveOrUpdate(synonym1);
840

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

    
849
        service.deleteSynonym(synonym1, config);
850

    
851
        this.commitAndStartNewTransaction(tableNames);
852

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

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

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

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

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

    
888
        service.saveOrUpdate(synonym1);
889

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

    
898
        String result =service.deleteSynonym(synonym1, config);
899
        logger.debug(result);
900
        this.commitAndStartNewTransaction(tableNames);
901

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

    
913

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

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

    
927

    
928
        //may change with better implementation of countAllRelationships (see #2653)
929

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

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

    
936
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
937
        TaxonNameBase name2 = nameService.load(uuidSynonymName2);
938
        synonym1.getName().addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
939

    
940
        service.deleteSynonym(synonym1, new SynonymDeletionConfigurator());
941

    
942
        this.rollback();
943
//		printDataSet(System.out, tableNames);
944
        this.startNewTransaction();
945

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

    
954
    }
955

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

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

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

    
974
        Synonym synonym1 = (Synonym)service.load(uuidSynonym1);
975
        TaxonNameBase name2 = nameService.load(uuidSynonymName2);
976
        synonym1.getName().addRelationshipFromName(name2, NameRelationshipType.LATER_HOMONYM(), null);
977

    
978
        service.saveOrUpdate(synonym1);
979

    
980
        this.setComplete();
981
        this.endTransaction();
982

    
983
//        printDataSet(System.out, tableNames);
984

    
985
        //out of wrapping transaction
986
        service.deleteSynonym(synonym1,  new SynonymDeletionConfigurator());
987

    
988
        this.startNewTransaction();
989

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

    
999
    }
1000

    
1001
    @Test
1002
    @DataSet("TaxonServiceImplTest.testInferredSynonyms.xml")
1003
    public void testCreateInferredSynonymy(){
1004

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

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

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

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

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

    
1049
        UUID uuidParent=UUID.fromString("b5271d4f-e203-4577-941f-00d76fa9f4ca");
1050
        UUID uuidChild1=UUID.fromString("326167f9-0b97-4e7d-b1bf-4ca47b82e21e");
1051
        UUID uuidSameAs=UUID.fromString("c2bb0f01-f2dd-43fb-ba12-2a85727ccb8d");
1052
        commitAndStartNewTransaction(tableNames);
1053
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1054
        service.save(testTaxon);
1055
        commitAndStartNewTransaction(tableNames);
1056
        int nTaxa = service.count(Taxon.class);
1057
        
1058
        Assert.assertEquals("There should be 4 taxa in the database", 4, nTaxa);
1059
        Taxon parent = (Taxon)service.find(TaxonGenerator.GENUS_UUID);
1060
        Assert.assertNotNull("Parent taxon should exist", parent);
1061
        Taxon child1 = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1062
        Assert.assertNotNull("Child taxon should exist", child1);
1063
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1064
        config.setDeleteTaxonNodes(false);
1065
        config.setDeleteMisappliedNamesAndInvalidDesignations(false);
1066
        //try {
1067
            //commitAndStartNewTransaction(tableNames);
1068

    
1069
            service.deleteTaxon(child1, config, null);
1070
            
1071
            //Assert.fail("Delete should throw an error as long as name is used in classification.");
1072
        /*} catch (DataChangeNoRollbackException e) {
1073
            if (e.getMessage().contains("Taxon can't be deleted as it is used in a classification node")){
1074
                //ok
1075
                commitAndStartNewTransaction(tableNames);
1076
            }else{
1077
                Assert.fail("Unexpected error occurred when trying to delete taxon: " + e.getMessage());
1078
            }
1079
        }*/
1080

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

    
1087
        TaxonNode node = child1.getTaxonNodes().iterator().next();
1088
        child1.addSource(IdentifiableSource.NewInstance(OriginalSourceType.Import));
1089
        
1090
        SpecimenOrObservationBase<IIdentifiableEntityCacheStrategy> identifiedUnit = DerivedUnit.NewInstance(SpecimenOrObservationType.DerivedUnit);
1091
        DeterminationEvent determinationEvent = DeterminationEvent.NewInstance(child1, identifiedUnit);
1092
        //UUID eventUUID = eventService.save(determinationEvent);
1093
        UUID identifiedUnitUUID = occurenceService.save(identifiedUnit);
1094
        
1095
        
1096
        TaxonNode parentNode = node.getParent();
1097
        parentNode =CdmBase.deproxy(parentNode, TaxonNode.class);
1098
        parentNode.deleteChildNode(node);
1099
        nodeService.save(parentNode);
1100
        //commitAndStartNewTransaction(tableNames);
1101

    
1102
       // try {
1103

    
1104
            String uuidString = service.deleteTaxon(child1, config, null);
1105
            try{
1106
            	UUID uuid = UUID.fromString(uuidString);
1107
            	 Assert.fail("Delete should throw an exception because of the determination event");
1108
            }catch(IllegalArgumentException e){
1109
            	logger.debug(uuidString);
1110
            }
1111
            
1112
           // Assert.fail("Delete should throw an exception because of the determination event");
1113
        /*} catch (DataChangeNoRollbackException e) {
1114
        	commitAndStartNewTransaction(tableNames);
1115
        }*/
1116
       
1117
        //determinationEvent = (DeterminationEvent)eventService.load(eventUUID);
1118
        commitAndStartNewTransaction(tableNames);
1119
        identifiedUnit = occurenceService.load(identifiedUnitUUID);
1120
        
1121
        occurenceService.delete(identifiedUnit);
1122
       
1123
        commitAndStartNewTransaction(tableNames);
1124
        child1 = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1125

    
1126
        assertEquals(0, child1.getTaxonNodes().size());
1127
       // try {
1128

    
1129
         uuidString = service.deleteTaxon(child1, config, null);
1130
        /*} catch (DataChangeNoRollbackException e) {
1131
            Assert.fail("Delete should not throw an exception anymore");
1132
        }*/
1133
        try{
1134
        	UUID uuid = UUID.fromString(uuidString);
1135
        	 
1136
        }catch(IllegalArgumentException e){
1137
        	 Assert.fail("Delete should not throw an exception anymore");
1138
        }
1139
        nTaxa = service.count(Taxon.class);
1140
        Assert.assertEquals("There should be 3 taxa in the database", 3, nTaxa);
1141

    
1142
        config.setDeleteTaxonNodes(true);
1143
        Taxon child2 =(Taxon) service.find(TaxonGenerator.SPECIES2_UUID);
1144

    
1145
       // try {
1146
        uuidString = service.deleteTaxon(child2, config, null);
1147
        /*} catch (DataChangeNoRollbackException e) {
1148
            Assert.fail("Delete should not throw an exception");
1149
        }*/
1150
        try{
1151
        	UUID uuid = UUID.fromString(uuidString);
1152
        }catch(IllegalArgumentException e){
1153
        	Assert.fail("Delete should not throw an exception");
1154
        }
1155
        
1156
        //service.find(uuid);
1157

    
1158
        nTaxa = service.count(Taxon.class);
1159
        Assert.assertEquals("There should be 2 taxa in the database",2, nTaxa);
1160
//		nNames = nameService.count(TaxonNameBase.class);
1161
//		Assert.assertEquals("There should be 3 names left in the database", 3, nNames);
1162
//		int nRelations = service.countAllRelationships();
1163
//		Assert.assertEquals("There should be no relationship left in the database", 0, nRelations);
1164
    }
1165

    
1166

    
1167
    @Test
1168
    @DataSet(value="BlankDataSet.xml")
1169
    public final void testDeleteTaxon(){
1170

    
1171
        //create a small classification
1172
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1173

    
1174
        UUID uuid = service.save(testTaxon);
1175

    
1176
        Taxon speciesTaxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1177
        Iterator<TaxonDescription> descriptionIterator = speciesTaxon.getDescriptions().iterator();
1178
        UUID descrUUID = null;
1179
        UUID descrElementUUID = null;
1180
        if (descriptionIterator.hasNext()){
1181
            TaxonDescription descr = descriptionIterator.next();
1182
            descrUUID = descr.getUuid();
1183
            descrElementUUID = descr.getElements().iterator().next().getUuid();
1184
        }
1185
        BotanicalName taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1186
        assertNotNull(taxonName);
1187

    
1188
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1189
        config.setDeleteNameIfPossible(false);
1190
        
1191
        
1192

    
1193
       // try {
1194
       String uuidString = service.deleteTaxon(speciesTaxon, config, null);
1195
        /*} catch (DataChangeNoRollbackException e) {
1196
            e.printStackTrace();
1197
            Assert.fail();
1198

    
1199
        }*/
1200
            
1201
        try{
1202
        	uuid = UUID.fromString(uuidString);
1203
        }catch (IllegalArgumentException e){
1204
        	Assert.fail();
1205
        }
1206
        commitAndStartNewTransaction(null);
1207

    
1208
        taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1209
        Taxon taxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1210

    
1211
        //descriptionService.find(descrUUID);
1212
        assertNull(descriptionService.find(descrUUID));
1213
        assertNull(descriptionService.getDescriptionElementByUuid(descrElementUUID));
1214
        //assertNull(synName);
1215
        assertNotNull(taxonName);
1216
        assertNull(taxon);
1217

    
1218
    }
1219

    
1220
    @Test
1221
    
1222
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="BlankDataSet.xml")
1223
    public final void testDeleteTaxonDeleteSynonymRelations(){
1224
    	
1225
    	 final String[]tableNames = {
1226
                 "Classification", "Classification_AUD",
1227
                 "TaxonBase","TaxonBase_AUD",
1228
                 "TaxonNode","TaxonNode_AUD",
1229
                 "TaxonNameBase","TaxonNameBase_AUD"};
1230
    	 commitAndStartNewTransaction(tableNames);
1231
        //create a small classification
1232
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1233

    
1234
        UUID uuid = service.save(testTaxon);
1235

    
1236
        Taxon speciesTaxon = (Taxon)service.find(TaxonGenerator.SPECIES2_UUID);
1237

    
1238
        SynonymRelationship synRel = speciesTaxon.getSynonymRelations().iterator().next();
1239
        UUID synonymRelationUuid = synRel.getUuid();
1240
        UUID synonymUuid = synRel.getSynonym().getUuid();
1241
        int i = service.getAllRelationships(1000, 0).size();
1242
        
1243
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1244
        config.setDeleteSynonymsIfPossible(false);
1245

    
1246
       // try {
1247
       String uuidString = service.deleteTaxon(speciesTaxon, config, null);
1248
        /*} catch (DataChangeNoRollbackException e) {
1249
            e.printStackTrace();
1250
            Assert.fail();
1251

    
1252
        }*/
1253
        try{
1254
        	uuid = UUID.fromString(uuidString);
1255
        }catch(IllegalArgumentException e){
1256
        	Assert.fail();
1257
        }
1258
        commitAndStartNewTransaction(null);
1259

    
1260
        Taxon taxon = (Taxon)service.find(TaxonGenerator.SPECIES2_UUID);
1261
        assertNull("The deleted taxon should no longer exist", taxon);
1262

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

    
1265
        for(RelationshipBase rel : service.getAllRelationships(1000, 0)){
1266
            if(rel instanceof SynonymRelationship && rel.getUuid().equals(synonymRelationUuid)){
1267
                Assert.fail("The SynonymRelationship should no longer exist");
1268
            }
1269
        }
1270
    }
1271

    
1272

    
1273
    @Test
1274
    @DataSet(value="BlankDataSet.xml")
1275
    public final void testDeleteTaxonNameUsedInOtherContext(){
1276

    
1277
        //create a small classification
1278
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1279

    
1280
        UUID uuid = service.save(testTaxon);
1281

    
1282
        Taxon speciesTaxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1283

    
1284
        BotanicalName taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1285
        assertNotNull(taxonName);
1286
        BotanicalName fromName = BotanicalName.NewInstance(Rank.SPECIES());
1287
        taxonName.addRelationshipFromName(fromName, NameRelationshipType.VALIDATED_BY_NAME(), null);
1288

    
1289
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1290
        config.setDeleteNameIfPossible(true);
1291
        //try {
1292
        String uuidString = service.deleteTaxon(speciesTaxon, config, null);
1293
        /*} catch (DataChangeNoRollbackException e) {
1294

    
1295
            Assert.fail();
1296
            e.printStackTrace();
1297
        }*/
1298
        
1299
        try{
1300
        	uuid = UUID.fromString(uuidString);
1301
        }catch(IllegalArgumentException e){
1302
        	Assert.fail();
1303
        }
1304
        commitAndStartNewTransaction(null);
1305

    
1306
        taxonName = (BotanicalName) nameService.find(TaxonGenerator.SPECIES1_NAME_UUID);
1307
        Taxon taxon = (Taxon)service.find(TaxonGenerator.SPECIES1_UUID);
1308
        //because of the namerelationship the name cannot be deleted
1309
        assertNotNull(taxonName);
1310
        assertNull(taxon);
1311

    
1312
    }
1313

    
1314
    @Test
1315
    @DataSet(value="BlankDataSet.xml")
1316
    public final void testDeleteTaxonNameUsedInTwoClassificationsDeleteAllNodes(){
1317
        commitAndStartNewTransaction(null);
1318
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
1319
        //create a small classification
1320
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1321

    
1322
        UUID uuid = service.save(testTaxon);
1323
        //BotanicalName name = nameService.find(uuid);
1324
        Set<TaxonNode> nodes = testTaxon.getTaxonNodes();
1325
        TaxonNode node = nodes.iterator().next();
1326
        List<TaxonNode> childNodes = node.getChildNodes();
1327
        TaxonNode childNode = childNodes.iterator().next();
1328
        UUID childUUID = childNode.getTaxon().getUuid();
1329
        Classification secondClassification = TaxonGenerator.getTestClassification("secondClassification");
1330

    
1331
        secondClassification.addChildTaxon(testTaxon, null, null);
1332
        //delete the taxon in all classifications
1333
        //try {
1334
        String uuidString = service.deleteTaxon(testTaxon, config, null);
1335
        /*} catch (DataChangeNoRollbackException e) {
1336
            Assert.fail();
1337
        }*/
1338
        
1339
        try{
1340
        	uuid = UUID.fromString(uuidString);
1341
        }catch(IllegalArgumentException e){
1342
        	Assert.fail();
1343
        }
1344
        commitAndStartNewTransaction(null);
1345
        Taxon tax = (Taxon)service.find(uuid);
1346
        assertNull(tax);
1347
        Taxon childTaxon = (Taxon)service.find(childUUID);
1348
        assertNull(tax);
1349
        commitAndStartNewTransaction(null);
1350

    
1351

    
1352

    
1353

    
1354

    
1355
    }
1356

    
1357
    @Test
1358
    @DataSet(value="BlankDataSet.xml")
1359
    public final void testDeleteTaxonNameUsedInTwoClassificationsDoNotDeleteAllNodes(){
1360
        // delete the taxon only in second classification, this should delete only the nodes, not the taxa
1361
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1362
        UUID uuid = service.save(testTaxon);
1363
        Classification secondClassification = TaxonGenerator.getTestClassification("secondClassification");
1364
        Set<TaxonNode> nodes = testTaxon.getTaxonNodes();
1365
        TaxonNode node = nodes.iterator().next();
1366
        List<TaxonNode> childNodes = node.getChildNodes();
1367
        TaxonNode childNode = childNodes.iterator().next();
1368
        UUID childUUID = childNode.getTaxon().getUuid();
1369
        childNode = secondClassification.addChildTaxon(testTaxon, null, null);
1370
        UUID childNodeUUID = childNode.getUuid();
1371

    
1372
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1373
        config.setDeleteInAllClassifications(false);
1374
       //     try {
1375
       String uuidString = service.deleteTaxon(testTaxon, config, secondClassification);
1376
/*                Assert.fail("The taxon should not be deletable because it is used in a second classification and the configuration is set to deleteInAllClassifications = false");
1377
            } catch (DataChangeNoRollbackException e) {
1378
                logger.debug(e.getMessage());
1379
            }
1380
  */          
1381
            
1382
        try{
1383
           	uuid = UUID.fromString(uuidString);
1384
           	Assert.fail("The taxon should not be deletable because it is used in a second classification and the configuration is set to deleteInAllClassifications = false");
1385
        }catch(IllegalArgumentException e){
1386
            	logger.debug(uuidString);
1387
        }
1388

    
1389
        //commitAndStartNewTransaction(null);
1390
        Taxon tax = (Taxon)service.find(uuid);
1391
        assertNotNull(tax);
1392
        Taxon childTaxon = (Taxon)service.find(childUUID);
1393
        assertNotNull(tax);
1394
        node = nodeService.find(childNodeUUID);
1395
        assertNull(node);
1396
    }
1397

    
1398
    @Test
1399
    @DataSet(value="BlankDataSet.xml")
1400
    public final void testTaxonNodeDeletionConfiguratorMoveToParent(){
1401
        //test childHandling MOVE_TO_PARENT:
1402
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1403
        UUID uuid = service.save(testTaxon);
1404

    
1405
        Taxon topMost = Taxon.NewInstance(BotanicalName.NewInstance(Rank.FAMILY()), null);
1406

    
1407
    Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1408
        TaxonNode node =nodes.next();
1409
        Classification classification = node.getClassification();
1410
        classification.addParentChild(topMost, testTaxon, null, null);
1411
        UUID topMostUUID = service.save(topMost);
1412

    
1413
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1414
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.MOVE_TO_PARENT);
1415

    
1416
      //  try {
1417
        String uuidString = service.deleteTaxon(testTaxon, config, null);
1418
        /*} catch (DataChangeNoRollbackException e) {
1419
            Assert.fail();
1420
        }*/
1421
            
1422
        try{
1423
        	uuid = UUID.fromString(uuidString);
1424
        }catch (IllegalArgumentException e){
1425
        	Assert.fail();
1426
        }
1427
        
1428
        commitAndStartNewTransaction(null);
1429
        Taxon tax = (Taxon)service.find(uuid);
1430
        assertNull(tax);
1431
        tax = (Taxon)service.find(topMostUUID);
1432
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1433
        assertNotNull(topMostNodes);
1434
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1435
        nodes = topMostNodes.iterator();
1436
        TaxonNode topMostNode = nodes.next();
1437
        int size = topMostNode.getChildNodes().size();
1438

    
1439
        assertEquals(2, size);
1440
    }
1441

    
1442
    @Test
1443
    @DataSet(value="BlankDataSet.xml")
1444
    public final void testTaxonNodeDeletionConfiguratorDeleteChildren(){
1445
        //test childHandling DELETE:
1446
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1447
        UUID uuid = service.save(testTaxon);
1448

    
1449
        Taxon topMost = Taxon.NewInstance(BotanicalName.NewInstance(Rank.FAMILY()), null);
1450

    
1451
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1452
        TaxonNode node =nodes.next();
1453
        UUID taxonNodeUUID = node.getUuid();
1454
        Classification classification = node.getClassification();
1455
        classification.addParentChild(topMost, testTaxon, null, null);
1456
        UUID topMostUUID = service.save(topMost);
1457

    
1458
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1459
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.DELETE);
1460

    
1461
       // try {
1462
        String uuidString = service.deleteTaxon(testTaxon, config, null);
1463
        /*} catch (DataChangeNoRollbackException e) {
1464
            Assert.fail();
1465
        }*/
1466
        try{
1467
        	uuid = UUID.fromString(uuidString);
1468
        }catch(IllegalArgumentException e){
1469
        	Assert.fail();
1470
        }
1471
        commitAndStartNewTransaction(null);
1472
        Taxon tax = (Taxon)service.find(uuid);
1473
        assertNull(tax);
1474
        tax = (Taxon)service.find(topMostUUID);
1475
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1476
        assertNotNull(topMostNodes);
1477
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1478
        nodes = topMostNodes.iterator();
1479
        TaxonNode topMostNode = nodes.next();
1480
        int size = topMostNode.getChildNodes().size();
1481
        node = nodeService.find(taxonNodeUUID);
1482
        assertNull(node);
1483
        assertEquals(0, size);
1484
    }
1485

    
1486

    
1487
    @Test
1488
    @DataSet(value="BlankDataSet.xml")
1489
    public final void testTaxonDeletionConfiguratorDeleteMarker(){
1490
        //test childHandling DELETE:
1491
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1492
        UUID uuid = service.save(testTaxon);
1493

    
1494
        Taxon topMost = Taxon.NewInstance(BotanicalName.NewInstance(Rank.FAMILY()), null);
1495

    
1496
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1497
        TaxonNode node =nodes.next();
1498
        Classification classification = node.getClassification();
1499
        classification.addParentChild(topMost, testTaxon, null, null);
1500
        UUID topMostUUID = service.save(topMost);
1501
        Marker marker = Marker.NewInstance(testTaxon, true, MarkerType.IS_DOUBTFUL());
1502
        testTaxon.addMarker(marker);
1503
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1504
        config.getTaxonNodeConfig().setChildHandling(ChildHandling.DELETE);
1505

    
1506
     //   try {
1507
        String uuidString = service.deleteTaxon(testTaxon, config, null);
1508
       /* } catch (DataChangeNoRollbackException e) {
1509
            Assert.fail();
1510
        }*/
1511

    
1512
        try{
1513
        	uuid = UUID.fromString(uuidString);
1514
        }catch(IllegalArgumentException e){
1515
        	Assert.fail();
1516
        }
1517
        commitAndStartNewTransaction(null);
1518
        Taxon tax = (Taxon)service.find(uuid);
1519
        assertNull(tax);
1520
        tax = (Taxon)service.find(topMostUUID);
1521
        Set<TaxonNode> topMostNodes = tax.getTaxonNodes();
1522
        assertNotNull(topMostNodes);
1523
        assertEquals("there should be one taxon node", 1, topMostNodes.size());
1524
        nodes = topMostNodes.iterator();
1525
        TaxonNode topMostNode = nodes.next();
1526
        int size = topMostNode.getChildNodes().size();
1527

    
1528
        assertEquals(0, size);
1529
    }
1530

    
1531

    
1532
    @Test
1533
    @DataSet(value="BlankDataSet.xml")
1534
    public final void testTaxonDeletionConfiguratorTaxonWithMisappliedName(){
1535

    
1536
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1537
        UUID uuid = service.save(testTaxon);
1538

    
1539
        Taxon misappliedName = Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()), null);
1540

    
1541
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1542
        TaxonNode node =nodes.next();
1543
        testTaxon.addMisappliedName(misappliedName, null, null);
1544
        UUID misappliedNameUUID = service.save(misappliedName);
1545

    
1546
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1547
        config.setDeleteMisappliedNamesAndInvalidDesignations(true);
1548

    
1549
       // try {
1550
       String uuidString = service.deleteTaxon(testTaxon, config, null);
1551
        /*} catch (DataChangeNoRollbackException e) {
1552
            Assert.fail();
1553
        }*/
1554

    
1555
        try{
1556
        	uuid = UUID.fromString(uuidString);
1557
        }catch(IllegalArgumentException e){
1558
        	Assert.fail();
1559
        }
1560
        commitAndStartNewTransaction(null);
1561
        Taxon tax = (Taxon)service.find(uuid);
1562
        assertNull(tax);
1563
        tax = (Taxon)service.find(misappliedNameUUID);
1564
        //TODO: is that correct or should it be deleted because there is no relation to anything
1565
        assertNull(tax);
1566

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

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

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

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

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

    
1585
        //try {
1586
        String uuidString = service.deleteTaxon(testTaxon, config, null);
1587
        /*} catch (DataChangeNoRollbackException e) {
1588
            Assert.fail();
1589
        }*/
1590
        try{
1591
        	uuid = UUID.fromString(uuidString);
1592
        }catch(IllegalArgumentException e){
1593
        	Assert.fail();
1594
        }
1595
        commitAndStartNewTransaction(null);
1596
        Taxon tax = (Taxon)service.find(uuid);
1597
        assertNull(tax);
1598
        tax = (Taxon)service.find(misappliedNameUUID);
1599
        //TODO: is that correct or should it be deleted because there is no relation to anything
1600
        assertNotNull(tax);
1601

    
1602
    }
1603

    
1604
    @Test
1605
    @DataSet(value="BlankDataSet.xml")
1606
    public final void testTaxonDeletionConfiguratorTaxonMisappliedName(){
1607

    
1608
        Taxon testTaxon = TaxonGenerator.getTestTaxon();
1609
        UUID uuid = service.save(testTaxon);
1610

    
1611
        Taxon misappliedNameTaxon = Taxon.NewInstance(BotanicalName.NewInstance(Rank.GENUS()), null);
1612

    
1613
        Iterator<TaxonNode> nodes = testTaxon.getTaxonNodes().iterator();
1614
        TaxonNode node =nodes.next();
1615
        testTaxon.addMisappliedName(misappliedNameTaxon, null, null);
1616
        UUID misappliedNameUUID = service.save(misappliedNameTaxon);
1617
        misappliedNameTaxon = (Taxon)service.find(misappliedNameUUID);
1618
        UUID misNameUUID = misappliedNameTaxon.getName().getUuid();
1619

    
1620
        TaxonDeletionConfigurator config = new TaxonDeletionConfigurator() ;
1621

    
1622

    
1623
       // try {
1624
            service.deleteTaxon(misappliedNameTaxon, config, null);
1625
       // } catch (DataChangeNoRollbackException e) {
1626
         //   e.printStackTrace();
1627

    
1628
        //}
1629

    
1630
        commitAndStartNewTransaction(null);
1631
        Taxon tax = (Taxon)service.find(uuid);
1632
        assertNotNull(tax);
1633
        tax = (Taxon)service.find(misappliedNameUUID);
1634
        BotanicalName name = (BotanicalName) nameService.find(misNameUUID);
1635

    
1636
        assertNull(tax);
1637
        assertNull(name);
1638

    
1639
    }
1640

    
1641

    
1642
}
1643

    
1644

    
1645

    
(21-21/25)