Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdmlib / cdmlib-services / src / test / java / eu / etaxonomy / cdm / api / service / NameServiceImplTest.java @ bfa30d38

History | View | Annotate | Download (54.9 KB)

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
package eu.etaxonomy.cdm.api.service;
10

    
11
import static org.junit.Assert.assertEquals;
12
import static org.junit.Assert.assertTrue;
13

    
14
import java.io.FileNotFoundException;
15
import java.lang.reflect.Field;
16
import java.util.Arrays;
17
import java.util.List;
18
import java.util.Set;
19
import java.util.UUID;
20

    
21
import org.apache.log4j.Logger;
22
import org.junit.Assert;
23
import org.junit.Ignore;
24
import org.junit.Test;
25
import org.springframework.security.authentication.AbstractAuthenticationToken;
26
import org.springframework.security.authentication.AuthenticationManager;
27
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
28
import org.springframework.security.core.Authentication;
29
import org.springframework.security.core.context.SecurityContextHolder;
30
import org.springframework.security.core.context.SecurityContextImpl;
31
import org.unitils.dbunit.annotation.DataSet;
32
import org.unitils.spring.annotation.SpringBeanByName;
33
import org.unitils.spring.annotation.SpringBeanByType;
34

    
35
import eu.etaxonomy.cdm.api.service.config.IdentifiableServiceConfiguratorFactory;
36
import eu.etaxonomy.cdm.api.service.config.IdentifiableServiceConfiguratorImpl;
37
import eu.etaxonomy.cdm.api.service.config.NameDeletionConfigurator;
38
import eu.etaxonomy.cdm.api.service.pager.Pager;
39
import eu.etaxonomy.cdm.model.common.CdmBase;
40
import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
41
import eu.etaxonomy.cdm.model.common.Language;
42
import eu.etaxonomy.cdm.model.description.DescriptionElementSource;
43
import eu.etaxonomy.cdm.model.description.Feature;
44
import eu.etaxonomy.cdm.model.description.TaxonDescription;
45
import eu.etaxonomy.cdm.model.description.TaxonNameDescription;
46
import eu.etaxonomy.cdm.model.description.TextData;
47
import eu.etaxonomy.cdm.model.name.HybridRelationship;
48
import eu.etaxonomy.cdm.model.name.HybridRelationshipType;
49
import eu.etaxonomy.cdm.model.name.NameRelationshipType;
50
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
51
import eu.etaxonomy.cdm.model.name.NameTypeDesignationStatus;
52
import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
53
import eu.etaxonomy.cdm.model.name.NomenclaturalStatusType;
54
import eu.etaxonomy.cdm.model.name.Rank;
55
import eu.etaxonomy.cdm.model.name.Registration;
56
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
57
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
58
import eu.etaxonomy.cdm.model.name.TaxonName;
59
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
60
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
61
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
62
import eu.etaxonomy.cdm.model.taxon.Taxon;
63
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
64
import eu.etaxonomy.cdm.persistence.dao.common.Restriction;
65
import eu.etaxonomy.cdm.persistence.dao.common.Restriction.Operator;
66
import eu.etaxonomy.cdm.persistence.query.MatchMode;
67
import eu.etaxonomy.cdm.persistence.query.OrderHint;
68
import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
69
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
70

    
71
/**
72
 * @author a.mueller
73
 *
74
 */
75
public class NameServiceImplTest extends CdmTransactionalIntegrationTest {
76

    
77
    private static final Logger logger = Logger.getLogger(NameServiceImplTest.class);
78

    
79
    private static final UUID NAME1_UUID = UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384");
80
    private static final UUID NAME2_UUID = UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e");
81
    private static final UUID NAME3_UUID = UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28");
82

    
83
    @SpringBeanByType
84
    private INameService nameService;
85

    
86
    @SpringBeanByType
87
    private IOccurrenceService occurrenceService;
88

    
89
    @SpringBeanByType
90
    private IRegistrationService registrationService;
91

    
92
    @SpringBeanByType
93
    private ITaxonService taxonService;
94

    
95
    @SpringBeanByType
96
    private ITermService termService;
97

    
98
    @SpringBeanByName
99
    private AuthenticationManager authenticationManager;
100

    
101
    private void setAuthentication(AbstractAuthenticationToken token) {
102
       Authentication authentication = authenticationManager.authenticate(token);
103

    
104
       SecurityContextImpl secureContext = new SecurityContextImpl();
105
       SecurityContextHolder.setContext(secureContext);
106
       secureContext.setAuthentication(authentication);
107
    }
108

    
109
    private void unsetAuthentication() {
110

    
111
        SecurityContextImpl secureContext = new SecurityContextImpl();
112
        SecurityContextHolder.setContext(secureContext);
113
        secureContext.setAuthentication(null);
114
     }
115

    
116

    
117
/* ******************** TESTS ********************************************/
118

    
119
    /**
120
     * Test method for {@link eu.etaxonomy.cdm.api.service.NameServiceImpl#setDao(eu.etaxonomy.cdm.persistence.dao.name.ITaxonNameDao)}.
121
     */
122
    @Test
123
    public void testSetDao() {
124
//                Assert.assertNotNull(((NameServiceImpl)nameService).dao);
125
    }
126

    
127
    /**
128
     * Test method for {@link eu.etaxonomy.cdm.api.service.NameServiceImpl#setVocabularyDao(eu.etaxonomy.cdm.persistence.dao.common.ITermVocabularyDao)}.
129
     */
130
    @Test
131
    public void testSetVocabularyDao() {
132
//        Assert.assertNotNull(( (NameServiceImpl)nameService.vocabularyDao);
133
    }
134

    
135
    /**
136
     * Test method for {@link eu.etaxonomy.cdm.api.service.NameServiceImpl#getNamesByName(java.lang.String)}.
137
     */
138
    @Test
139
    public void testGetNamesByName() {
140
        logger.warn("Not yet implemented");
141
    }
142

    
143

    
144
    @Test
145
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class)
146
    public void testDeleteTaxonNameWithNameRelations() {
147

    
148
        final String[] tableNames = new String[]{"USERACCOUNT", "TaxonName","NameRelationship","HybridRelationship","DescriptionBase","NomenclaturalStatus","TaxonBase","SpecimenOrObservationBase","OriginalSourceBase","DescriptionElementBase"};
149
//        printDataSetWithNull(System.err, true, null);
150

    
151
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
152
        name1.setTitleCache("Name1", true);
153
        TaxonName nameWithBasionym = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
154
        nameWithBasionym.setTitleCache("nameWithBasionym", true);
155

    
156
        NameRelationshipType nameRelType = (NameRelationshipType)termService.find(NameRelationshipType.BASIONYM().getUuid());
157
        name1.addRelationshipToName(nameWithBasionym,nameRelType , null, null, null);
158
//                nameWithBasionym.addBasionym(name1);
159
        nameService.save(name1);
160
        nameService.save(nameWithBasionym);
161
        commitAndStartNewTransaction(tableNames);
162

    
163

    
164
        name1 = nameService.find(name1.getUuid());
165
        DeleteResult result = nameService.delete(name1);
166
        if (!result.isOk()){
167
                Exception e = result.getExceptions().iterator().next();
168
                Assert.assertEquals("The Ecxeption should be a ReferencedObjectException because it is a basionym", "Name can't be deleted as it is a basionym.", e.getMessage());
169
        } else{
170
                Assert.fail();
171
        }
172
        name1 = nameService.find(name1.getUuid());
173
        Assert.assertNotNull("Name should still be in database",name1);
174
        nameWithBasionym = name1.getNameRelations().iterator().next().getToName();
175
        nameWithBasionym.removeBasionyms();
176

    
177
        result = nameService.delete(name1); //should throw now exception
178

    
179

    
180

    
181
        commitAndStartNewTransaction(tableNames);
182
        name1 = nameService.find(name1.getUuid());
183
        Assert.assertNull("Name should not be in database anymore",name1);
184

    
185
    }
186

    
187
    @Test
188
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class)
189
    public void testDeleteTaxonNameConfiguratorWithNameRelations() {
190
        final String[] tableNames = new String[]{"TaxonName","NameRelationship","HybridRelationship"};
191

    
192
//        printDataSet(System.err, new String[]{"TaxonName","NameRelationship","HybridRelationship","DescriptionBase","NomenclaturalStatus","TaxonBase","SpecimenOrObservationBase","OriginalSourceBase",
193
//                "DescriptionElementBase",
194
//                "AGENTBASE", "USERACCOUNT", "PERMISSIONGROUP", "USERACCOUNT_PERMISSIONGROUP", "USERACCOUNT_GRANTEDAUTHORITYIMPL", "GRANTEDAUTHORITYIMPL"});
195

    
196
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
197
        name1.setTitleCache("Name1", true);
198
        TaxonName nameWithBasionym = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
199
        nameWithBasionym.setTitleCache("nameWithBasionym", true);
200

    
201
        NameRelationshipType nameRelType = (NameRelationshipType)termService.find(NameRelationshipType.BASIONYM().getUuid());
202
        name1.addRelationshipToName(nameWithBasionym,nameRelType , null, null, null);
203
        nameService.save(name1);
204
        nameService.save(nameWithBasionym);
205
        commitAndStartNewTransaction(tableNames);
206
        NameDeletionConfigurator config = new NameDeletionConfigurator();
207

    
208
        name1 = nameService.find(name1.getUuid());
209
        DeleteResult result = nameService.delete(name1.getUuid(), config);
210
        if (result.isOk()){
211
                Assert.fail("This should throw an error as long as name relationships exist.");
212
        }
213

    
214

    
215
        name1 = nameService.find(name1.getUuid());
216
        Assert.assertNotNull("Name should still be in database",name1);
217

    
218
        //ignore is basionym for
219
        config.setIgnoreIsBasionymFor(true);
220

    
221
        name1 = nameService.find(name1.getUuid());
222
        nameService.delete(name1.getUuid(),  config);
223
        commitAndStartNewTransaction(tableNames);
224
        name1 = nameService.find(name1.getUuid());
225
        Assert.assertNull("Name should not be in database anymore",name1);
226

    
227
    }
228

    
229
    @Test
230
    public void testDeleteTaxonNameConfiguratorWithNameRelationsAll() {
231
        final String[] tableNames = new String[]{"TaxonName","NameRelationship","HybridRelationship"};
232

    
233
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
234
        name1.setTitleCache("Name1", true);
235
        TaxonName nameWithBasionym = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
236
        nameWithBasionym.setTitleCache("nameWithBasionym", true);
237

    
238
        NameRelationshipType nameRelType = (NameRelationshipType)termService.find(NameRelationshipType.BASIONYM().getUuid());
239
        name1.addRelationshipToName(nameWithBasionym,nameRelType , null, null, null);
240
        nameService.save(name1);
241
        nameService.save(nameWithBasionym);
242
        commitAndStartNewTransaction(tableNames);
243
        NameDeletionConfigurator config = new NameDeletionConfigurator();
244

    
245
        name1 = nameService.find(name1.getUuid());
246
        DeleteResult result = nameService.delete(name1.getUuid(), config);
247
        if (result.isOk()){
248
               Assert.fail("Delete should throw an error as long as name relationships exist.");
249
        }
250

    
251
        name1 = nameService.find(name1.getUuid());
252
        Assert.assertNotNull("Name should still be in database",name1);
253

    
254
        //ignore all name relationships
255
        config.setRemoveAllNameRelationships(true);
256

    
257
        name1 = nameService.find(name1.getUuid());
258
        result = nameService.delete(name1.getUuid(), config);
259
        logger.debug(result);
260
        commitAndStartNewTransaction(tableNames);
261
        name1 = nameService.find(name1.getUuid());
262
        Assert.assertNull("Name should not be in database anymore",name1);
263

    
264
    }
265

    
266
    @Test
267
    public void testDeleteTaxonNameConfiguratorWithHasBasionym() {
268
        final String[] tableNames = new String[]{"TaxonName","NameRelationship","HybridRelationship"};
269

    
270
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
271
        name1.setTitleCache("Name1", true);
272
        TaxonName basionym = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
273
        basionym.setTitleCache("basionym", true);
274

    
275
        NameRelationshipType nameRelType = (NameRelationshipType)termService.find(NameRelationshipType.BASIONYM().getUuid());
276
        basionym.addRelationshipToName(name1,nameRelType , null, null, null);
277
        nameService.save(name1);
278
        nameService.save(basionym);
279
        commitAndStartNewTransaction(tableNames);
280
        NameDeletionConfigurator config = new NameDeletionConfigurator();
281
        config.setIgnoreHasBasionym(false);
282

    
283
       name1 = nameService.find(name1.getUuid());
284
       DeleteResult result = nameService.delete(name1.getUuid(), config);
285
       if (result.isOk()){
286
              Assert.fail("Delete should throw an error as long as name relationships exist.");
287
        }
288

    
289

    
290
        name1 = nameService.find(name1.getUuid());
291
        Assert.assertNotNull("Name should still be in database",name1);
292

    
293
        //ignore has basionym
294
        config.setIgnoreHasBasionym(true);
295
        try {
296
            name1 = nameService.find(name1.getUuid());
297
            result = nameService.delete(name1.getUuid(), config);
298
            logger.debug(result);
299
            commitAndStartNewTransaction(tableNames);
300
            name1 = nameService.find(name1.getUuid());
301
            Assert.assertNull("Name should not be in database anymore",name1);
302
        } catch (Exception e) {
303
            Assert.fail("Delete should not throw an error for .");
304
        }
305
    }
306

    
307
    @Test
308
   // @Ignore //currently does not run in suite
309
    public void testDeleteTaxonNameWithHybridRelations() {
310
        final String[] tableNames = new String[]{"TaxonName","NameRelationship","HybridRelationship"};
311

    
312
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
313
        name1.setTitleCache("Name1", true);
314
        TaxonName parent = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
315
        parent.setTitleCache("parent", true);
316
        TaxonName child = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
317
        child.setTitleCache("child", true);
318

    
319
        TaxonName hybrid = TaxonNameFactory.PARSED_BOTANICAL("Abies alba x Pinus beta");
320

    
321
        Set<HybridRelationship> childRelations = hybrid.getHybridChildRelations();
322
       for (HybridRelationship rel : childRelations){
323
           TaxonName name = rel.getHybridName();
324
           TaxonName parentName = rel.getParentName();
325
           nameService.save(rel.getHybridName());
326
           nameService.save(rel.getParentName());
327
       }
328

    
329

    
330

    
331
        commitAndStartNewTransaction(tableNames); //otherwise first save is rolled back with following failing delete
332
        HybridRelationshipType relType = (HybridRelationshipType)termService.find(HybridRelationshipType.FIRST_PARENT().getUuid());
333
        name1.addHybridParent(parent, relType, null);
334
        nameService.save(name1);
335
        nameService.save(parent);
336
        commitAndStartNewTransaction(tableNames); //otherwise first save is rolled back with following failing delete
337
        Assert.assertEquals("'Parent' should be a parent in a hybrid relation.", 1,parent.getHybridParentRelations().size());
338

    
339
        //parent
340

    
341
        name1 = nameService.find(name1.getUuid());
342
        DeleteResult result = nameService.delete(name1);
343
        if (result.isError()){
344
            Assert.fail("Delete should throw NO exception when deleting a hybrid child: " + result.getExceptions().iterator().next().getMessage());
345
        }
346
        commitAndStartNewTransaction(tableNames);
347
        name1 = nameService.find(name1.getUuid());
348
        Assert.assertNull("Name should not be in database anymore",name1);
349
        parent = nameService.find(parent.getUuid());
350
        Assert.assertEquals("'Parent' should not be a parent anymore.", 0,parent.getHybridParentRelations().size());
351

    
352
        //child
353
        name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
354
        name1.addHybridChild(child, relType, null);
355
        nameService.save(name1);
356
        nameService.save(child);
357
        commitAndStartNewTransaction(tableNames);
358

    
359

    
360
        result = nameService.delete(name1);
361
        if (result.isOk()){
362
            Assert.fail("Delete should throw an error as long as hybrid child exist.");
363
        }
364
        name1 = nameService.find(name1.getUuid());
365
        Assert.assertNotNull("Name should still be in database",name1);
366
        name1.removeHybridChild(child);
367

    
368
        result = nameService.delete(name1); //should throw now exception
369
        if (result.isError()){
370
                Assert.fail("Delete should throw NO exception when deleting a hybrid child: " +result.getExceptions().iterator().next().getMessage());
371
        }
372

    
373
        commitAndStartNewTransaction(tableNames);
374
        name1 = nameService.find(name1.getUuid());
375
        Assert.assertNull("Name should not be in database anymore",name1);
376
    }
377

    
378
    @Test
379
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class)
380
    public void testDeleteTaxonNameInConcept() {
381
        final String[] tableNames = new String[]{"TaxonName","TaxonBase"};
382

    
383
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
384
        name1.setTitleCache("Name1", true);
385
        TaxonName basionym = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
386
        basionym.setTitleCache("basionym", true);
387

    
388
        Taxon taxon = Taxon.NewInstance(name1, null);
389
        nameService.save(name1);
390
        taxonService.save(taxon);
391
        commitAndStartNewTransaction(tableNames);
392

    
393
        DeleteResult result = nameService.delete(name1);
394

    
395
        if (result.isOk()){
396
                Assert.fail("Delete should throw an error as long as name is used in a concept.");
397
        }
398
        TaxonName nameBase =nameService.find(name1.getUuid());
399
        Assert.assertNotNull("Name should still be in database",nameBase);
400
        TaxonBase<?> taxonBase = taxonService.find(taxon.getUuid());
401
        Assert.assertNotNull("Taxon should still be in database",taxonBase);
402
        taxon = (Taxon)taxonBase;
403
        taxon.setName(basionym);
404
        taxonService.save(taxon);
405
        nameBase =nameService.find(name1.getUuid());
406

    
407

    
408
        result = nameService.delete(nameBase); //should throw no exception
409
        if (result.isError()){
410
                Assert.fail("Delete should throw NO error ");
411
        }
412
        commitAndStartNewTransaction(tableNames);
413
        name1 = nameService.find(name1.getUuid());
414
        Assert.assertNull("Name should still be in database",name1);
415
        taxon = (Taxon)taxonService.find(taxon.getUuid());
416
        Assert.assertNotNull("Taxon should still be in database",taxon);
417
    }
418

    
419
    @Test
420
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class)
421
    public void testDeleteTaxonNameAsStoredUnder() {
422
        final String[] tableNames = new String[]{"TaxonName","SpecimenOrObservationBase"};
423

    
424
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
425
        name1.setTitleCache("Name1", true);
426
        DerivedUnit specimen = DerivedUnit.NewPreservedSpecimenInstance();
427
        specimen.setStoredUnder(name1);
428

    
429
        occurrenceService.save(specimen);
430
        UUID uuidName1 = nameService.save(name1).getUuid();
431

    
432
        commitAndStartNewTransaction(tableNames);
433
        DeleteResult result = nameService.delete(name1);
434
        if (result.isOk()){
435
               Assert.fail("This should throw an error because name is used for specimen#storedUnder.");
436
        }
437
        commitAndStartNewTransaction(tableNames);
438

    
439
        name1 = nameService.find(uuidName1);
440
        Assert.assertNotNull("Name should still be in database",name1);
441
        specimen = (DerivedUnit)occurrenceService.find(specimen.getUuid());
442
        Assert.assertNotNull("Specimen should still be in database",name1);
443
        specimen.setStoredUnder(null);
444
        occurrenceService.saveOrUpdate(specimen);
445

    
446
        nameService.delete(name1); //should throw no exception
447
        commitAndStartNewTransaction(tableNames);
448

    
449
        name1 = nameService.find(uuidName1);
450
        Assert.assertNull("Name should not be in database anymore",name1);
451
        specimen = (DerivedUnit)occurrenceService.find(specimen.getUuid());
452
        Assert.assertNotNull("Specimen should still be in database",specimen);
453

    
454
        occurrenceService.delete(specimen); //this is to better run this test in the test suit
455

    
456
    }
457

    
458
    @Test
459
    @Ignore //currently does not run in suite
460
    public void testDeleteTaxonNameInSource() {
461
        final String[] tableNames = new String[]{"TaxonName","DescriptionBase","TaxonBase","OriginalSourceBase","DescriptionElementBase"};
462

    
463
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
464
        name1.setTitleCache("Name1", true);
465
        TaxonName taxonName = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
466
        taxonName.setTitleCache("taxonName", true);
467
        Taxon taxon = Taxon.NewInstance(taxonName, null);
468

    
469
        TaxonDescription taxonDescription = TaxonDescription.NewInstance(taxon);
470
        Feature feature = (Feature)termService.find(Feature.DESCRIPTION().getUuid());
471
        Language lang = (Language)termService.find(Language.DEFAULT().getUuid());
472
        TextData textData = TextData.NewInstance("Any text", lang, null);
473
        textData.setFeature(feature);
474
        taxonDescription.addElement(textData);
475
        DescriptionElementSource source = DescriptionElementSource.NewPrimarySourceInstance(null, null, name1, "");
476
        textData.addSource(source);
477
        taxonService.saveOrUpdate(taxon);
478
        nameService.save(name1);
479
        try {
480
            commitAndStartNewTransaction(tableNames);
481
            name1 = nameService.find(name1.getUuid());
482
            nameService.delete(name1);
483
            Assert.fail("Delete should throw an error as long as name is used in a source.");
484
        } catch (Exception e) {
485
            if (e.getMessage().contains("Name can't be deleted as it is used as descriptionElementSource#nameUsedInSource")){
486
                //ok
487
                endTransaction();  //exception rolls back transaction!
488
                startNewTransaction();
489
            }else{
490
                Assert.fail("Unexpected error occurred when trying to delete taxon name: " + e.getMessage());
491
            }
492
        }
493
        name1 = nameService.find(name1.getUuid());
494
        Assert.assertNotNull("Name should still be in database",name1);
495
        taxon = (Taxon)taxonService.find(taxon.getUuid());
496
        Assert.assertNotNull("Taxon should still be in database",name1);
497
        source = taxon.getDescriptions().iterator().next().getElements().iterator().next().getSources().iterator().next();
498
        source.setNameUsedInSource(null);
499
        taxonService.saveOrUpdate(taxon);
500

    
501
        nameService.delete(name1);  //should throw now exception
502

    
503
        commitAndStartNewTransaction(tableNames);
504
        name1 = nameService.find(name1.getUuid());
505
        Assert.assertNull("Name should not be in database anymore",name1);
506
        taxon = (Taxon)taxonService.find(taxon.getUuid());
507
        Assert.assertNotNull("Taxon should still be in database",taxon);
508
        source = taxon.getDescriptions().iterator().next().getElements().iterator().next().getSources().iterator().next();
509
        Assert.assertNull("Source should not have a nameUsedInSource anymore",source.getNameUsedInSource());
510
    }
511

    
512

    
513
    @Test
514
    public void testDeleteTaxonNameAsType() {
515
        final String[] tableNames = new String[]{"TaxonName","TypeDesignationBase","TaxonName_TypeDesignationBase"};
516

    
517
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
518
        name1.setTitleCache("Name used as type", true);
519

    
520
        TaxonName higherName = TaxonNameFactory.NewBotanicalInstance(getGenusRank());
521
        higherName.setTitleCache("genus name", true);
522
        NameTypeDesignationStatus typeStatus = (NameTypeDesignationStatus)termService.find(NameTypeDesignationStatus.AUTOMATIC().getUuid());
523
        boolean addToAllHomotypicNames = true;
524
        higherName.addNameTypeDesignation(name1, null, null, null, typeStatus, addToAllHomotypicNames);
525
        nameService.save(higherName);
526

    
527
       commitAndStartNewTransaction(tableNames);
528
       name1 = nameService.find(name1.getUuid());
529
       DeleteResult result = nameService.delete(name1);
530
       if (result.isOk()){
531
               Assert.fail("This should throw an error because name is used in a type designation.");
532
        }
533

    
534
        commitAndStartNewTransaction(tableNames);
535
        name1 = nameService.find(name1.getUuid());
536
        Assert.assertNotNull("Name should still be in database",name1);
537
        higherName = nameService.find(higherName.getUuid());
538
        higherName.getNameTypeDesignations().iterator().next().removeType();  //keeps the designation but removes the name from it
539
//                nameService.deleteTypeDesignation(higherName,commitAndStartNewTransaction(tableNames) );  //deletes the complete designation  //both options can be used
540

    
541
            nameService.delete(name1);  //should throw now exception
542

    
543
            commitAndStartNewTransaction(tableNames);
544
        name1 = nameService.find(name1.getUuid());
545
        Assert.assertNull("Name should not be in database anymore",name1);
546
        higherName = nameService.find(higherName.getUuid());
547
        Assert.assertNotNull("Higher name should still exist in database",higherName);
548
        Assert.assertEquals("Higher name should not have type designations anymore",1, higherName.getTypeDesignations().size());
549
    }
550

    
551

    
552
    @Test
553
    public void testDeleteTaxonName() {
554
        final String[] tableNames = new String[]{"TaxonName","NameRelationship","HybridRelationship","DescriptionBase","NomenclaturalStatus","TaxonBase","SpecimenOrObservationBase","OriginalSourceBase","DescriptionElementBase","TypeDesignationBase","TaxonName_TypeDesignationBase"};
555

    
556
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
557
        name1.setTitleCache("Name1", true);
558

    
559
        //TaxonNameDescription
560
        name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
561
        TaxonNameDescription.NewInstance(name1);
562
        nameService.saveOrUpdate(name1);
563
        commitAndStartNewTransaction(tableNames);
564

    
565
        name1 = nameService.find(name1.getUuid());
566
        DeleteResult result = nameService.delete(name1);//should throw now exception
567

    
568
        setComplete();
569
        endTransaction();
570
        name1 = nameService.find(name1.getUuid());
571
        Assert.assertNull("Name should not be in database anymore",name1);
572

    
573
//                printDataSet(System.out, tableNames);
574

    
575

    
576
        //NomenclaturalStatus
577
        name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
578
        NomenclaturalStatusType nomStatusType = (NomenclaturalStatusType)termService.find(NomenclaturalStatusType.ILLEGITIMATE().getUuid());
579
        NomenclaturalStatus status = NomenclaturalStatus.NewInstance(nomStatusType);
580
        name1.addStatus(status);
581
        nameService.saveOrUpdate(name1);
582
        commitAndStartNewTransaction(tableNames);
583

    
584
        name1 = nameService.find(name1.getUuid());
585

    
586
        nameService.delete(name1);  //should throw now exception
587
        if (!result.isOk()){
588
                Assert.fail();
589
        }
590
        setComplete();
591
        endTransaction();
592
//                printDataSet(System.out, tableNames);
593

    
594

    
595
        //Type Designations
596
        name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
597
        name1.setTitleCache("Name with type designation", true);
598
        SpecimenTypeDesignation typeDesignation = SpecimenTypeDesignation.NewInstance();
599
        SpecimenTypeDesignationStatus typeStatus = (SpecimenTypeDesignationStatus)termService.find(SpecimenTypeDesignationStatus.HOLOTYPE().getUuid());
600
        typeDesignation.setTypeStatus(typeStatus);
601
        DerivedUnit specimen = DerivedUnit.NewPreservedSpecimenInstance();
602
        specimen.setTitleCache("Type specimen", true);
603
        occurrenceService.save(specimen);
604
        typeDesignation.setTypeSpecimen(specimen);
605

    
606
        name1.addTypeDesignation(typeDesignation, true);
607
        nameService.save(name1);
608
        commitAndStartNewTransaction(tableNames);
609
//                printDataSet(System.out, tableNames);
610

    
611
        name1 = nameService.find(name1.getUuid());
612

    
613
        result = nameService.delete(name1);  //should throw now exception
614
        if (!result.isOk()){
615
                Assert.fail();
616
        }
617
        setComplete();
618
        endTransaction();
619
//                printDataSet(System.out, tableNames);
620

    
621
    }
622

    
623
    @Test
624
    public void testDeleteTaxonNameWithTypeInHomotypicalGroup() {
625
        final String[] tableNames = new String[]{"TaxonName","NameRelationship","HybridRelationship","DescriptionBase","NomenclaturalStatus","TaxonBase","SpecimenOrObservationBase","OriginalSourceBase","DescriptionElementBase","TypeDesignationBase","TaxonName_TypeDesignationBase"};
626

    
627
        //Type Designations for homotypical group with > 1 names
628
        TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
629
        name1.setTitleCache("Name1 with type designation", true);
630
        TaxonName name2 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
631
        name2.setTitleCache("Name2 with type designation", true);
632
        name2.setHomotypicalGroup(name1.getHomotypicalGroup());
633

    
634
        DerivedUnit specimen = DerivedUnit.NewPreservedSpecimenInstance();
635
        specimen.setTitleCache("Type specimen 2", true);
636
        occurrenceService.save(specimen);
637
        SpecimenTypeDesignationStatus typeStatus = (SpecimenTypeDesignationStatus)termService.find(SpecimenTypeDesignationStatus.HOLOTYPE().getUuid());
638

    
639
        SpecimenTypeDesignation typeDesignation = SpecimenTypeDesignation.NewInstance();
640
        typeDesignation.setTypeStatus(typeStatus);
641
        typeDesignation.setTypeSpecimen(specimen);
642

    
643
        boolean addToAllNames = true;
644
        name1.addTypeDesignation(typeDesignation, addToAllNames);
645
        nameService.saveOrUpdate(name1);
646
        commitAndStartNewTransaction(tableNames);
647

    
648
        name1 = nameService.find(name1.getUuid());
649

    
650
                nameService.delete(name1);  //should throw now exception
651

    
652
        setComplete();
653
        endTransaction();
654
//                printDataSet(System.out, tableNames);
655

    
656
    }
657

    
658
    @Test
659
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class)
660
    public void testDeleteTypeDesignation() {
661
        final String[] tableNames = new String[]{
662
                "TaxonName","TypeDesignationBase","TaxonName_TypeDesignationBase",
663
                "SpecimenOrObservationBase"};
664

    
665
//                IBotanicalName name1 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
666
//                name1.setTitleCache("Name1");
667
//                name1.setUuid(UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384"));
668
//
669
//                IBotanicalName name2 = TaxonNameFactory.NewBotanicalInstance(getSpeciesRank());
670
//                name2.setTitleCache("Name2");
671
//                name2.setUuid(UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e"));
672
//
673
//                IBotanicalName name3 = TaxonNameFactory.NewBotanicalInstance(getGenusRank());
674
//                name3.setTitleCache("Name3");
675
//                name3.setUuid(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
676
//
677
//
678
//                SpecimenTypeDesignation desig1 = SpecimenTypeDesignation.NewInstance();
679
//                desig1.setUuid(UUID.fromString("1357c307-00c3-499c-8e20-0849d4706125"));
680
//                name1.addTypeDesignation(desig1, true);
681
//                name2.addTypeDesignation(desig1, true);
682
//
683
//                SpecimenTypeDesignation desig2 = SpecimenTypeDesignation.NewInstance();
684
//                desig2.setUuid(UUID.fromString("9bbda70b-7272-4e65-a807-852a3f2eba63"));
685
//                name1.addTypeDesignation(desig2, true);
686
//
687
//                Specimen specimen1 = Specimen.NewInstance();
688
//                Fossil specimen2 = Fossil.NewInstance();
689
//
690
//                desig1.setTypeSpecimen(specimen1);
691
//                desig2.setTypeSpecimen(specimen2);
692
//
693
//                NameTypeDesignation nameDesig = NameTypeDesignation.NewInstance();
694
//                nameDesig.setTypeName(name1);
695
//                name3.addTypeDesignation(nameDesig, true);
696
//
697
//                nameService.save(name1);
698
//                nameService.save(name2);
699
//                nameService.save(name3);
700
//
701
//                commitAndStartNewTransaction(tableNames);
702
//
703
//                printDataSet(System.out, tableNames);
704
//
705

    
706

    
707
        TaxonName name1 =  this.nameService.load(UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384"));
708
        TaxonName name2 = this.nameService.load(UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e"));
709
        TaxonName name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
710
        DerivedUnit specimen1 = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("0d19a9ca-21a7-4adb-8640-8d6719e15eea")), DerivedUnit.class);
711
        DerivedUnit fossil = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("4c48b7c8-4c8d-4e48-b083-0837fe51a0a9")), DerivedUnit.class);
712

    
713
        Set<TypeDesignationBase> desigs1 = name1.getTypeDesignations();
714
        Set<TypeDesignationBase> desigs2 = name2.getTypeDesignations();
715
        Set<TypeDesignationBase> desigs3 = name3.getTypeDesignations();
716

    
717
        Assert.assertEquals("name1 should have 2 type designations", 2, desigs1.size());
718
        Assert.assertEquals("name2 should have 1 type designations", 1, desigs2.size());
719
        Assert.assertEquals("name3 should have 1 type designations", 1, desigs3.size());
720
        Assert.assertEquals("Specimen1 should be used in 1 type designation", 1, specimen1.getSpecimenTypeDesignations().size());
721
        Assert.assertEquals("Fossil should be used in 1 type designation", 1, fossil.getSpecimenTypeDesignations().size());
722

    
723
        nameService.deleteTypeDesignation((TaxonName)null, null);
724

    
725
        commitAndStartNewTransaction(tableNames);
726

    
727
        name1 =  this.nameService.load(UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384"));
728
        name2 = this.nameService.load(UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e"));
729
        name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
730
        specimen1 = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("0d19a9ca-21a7-4adb-8640-8d6719e15eea")), DerivedUnit.class);
731
        fossil = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("4c48b7c8-4c8d-4e48-b083-0837fe51a0a9")), DerivedUnit.class);
732

    
733
        desigs1 = name1.getTypeDesignations();
734
        desigs2 = name2.getTypeDesignations();
735
        desigs3 = name3.getTypeDesignations();
736
        //nothing should be deleted
737
        Assert.assertEquals("name1 should have 2 type designations", 2, desigs1.size());
738
        Assert.assertEquals("name2 should have 1 type designations", 1, desigs2.size());
739
        Assert.assertEquals("name3 should have 1 type designations", 1, desigs3.size());
740
        Assert.assertEquals("Specimen1 should be used in 1 type designation", 1, specimen1.getSpecimenTypeDesignations().size());
741
        Assert.assertEquals("Fossil should be used in 1 type designation", 1, fossil.getSpecimenTypeDesignations().size());
742

    
743
        nameService.deleteTypeDesignation(name1, null);
744

    
745
        commitAndStartNewTransaction(tableNames);
746

    
747
        name1 =  this.nameService.load(UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384"));
748
        name2 = this.nameService.load(UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e"));
749
        name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
750
        specimen1 = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("0d19a9ca-21a7-4adb-8640-8d6719e15eea")), DerivedUnit.class);
751
        fossil = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("4c48b7c8-4c8d-4e48-b083-0837fe51a0a9")), DerivedUnit.class);
752

    
753
        desigs1 = name1.getTypeDesignations();
754
        desigs2 = name2.getTypeDesignations();
755
        desigs3 = name3.getTypeDesignations();
756
        //only the types of name1 should be deleted
757
        Assert.assertEquals("name1 should have 0 type designations", 0, desigs1.size());
758
        Assert.assertEquals("name2 should have 1 type designations", 1, desigs2.size());
759
        Assert.assertEquals("name3 should have 1 type designations", 1, desigs3.size());
760
        Assert.assertEquals("Specimen1 should be used in 1 type designation", 1, specimen1.getSpecimenTypeDesignations().size());
761
        Assert.assertEquals("Fossil should be used in 0 type designation", 0, fossil.getSpecimenTypeDesignations().size());
762

    
763
        SpecimenTypeDesignation desig2 = (SpecimenTypeDesignation)name2.getTypeDesignations().iterator().next();
764
        nameService.deleteTypeDesignation(name2, desig2);
765

    
766
        commitAndStartNewTransaction(tableNames);
767

    
768
        name1 =  this.nameService.load(UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384"));
769
        name2 = this.nameService.load(UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e"));
770
        name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
771
        specimen1 = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("0d19a9ca-21a7-4adb-8640-8d6719e15eea")), DerivedUnit.class);
772
        fossil = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("4c48b7c8-4c8d-4e48-b083-0837fe51a0a9")), DerivedUnit.class);
773

    
774
        desigs1 = name1.getTypeDesignations();
775
        desigs2 = name2.getTypeDesignations();
776
        desigs3 = name3.getTypeDesignations();
777

    
778
        Assert.assertEquals("name1 should have 0 type designations", 0, desigs1.size());
779
        Assert.assertEquals("name2 should have 0 type designations", 0, desigs2.size());
780
        Assert.assertEquals("name3 should have 1 type designations", 1, desigs3.size());
781
        Assert.assertEquals("Specimen1 should be used in 0 type designation", 0, specimen1.getSpecimenTypeDesignations().size());
782
        Assert.assertEquals("Fossil should be used in 0 type designation", 0, fossil.getSpecimenTypeDesignations().size());
783

    
784
        NameTypeDesignation desig3 = (NameTypeDesignation)name3.getTypeDesignations().iterator().next();
785
        name3.addTypeDesignation(SpecimenTypeDesignation.NewInstance(), false);
786
        this.nameService.update(name3);
787

    
788
        this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
789
        desigs3 = name3.getTypeDesignations();
790

    
791
        NameTypeDesignation desigNew = NameTypeDesignation.NewInstance();
792
        commitAndStartNewTransaction(tableNames);
793
        name3 = nameService.load(name3.getUuid());
794

    
795
        Assert.assertEquals("name3 should have 2 type designations", 2, desigs3.size());
796

    
797
        nameService.deleteTypeDesignation(name3, desig3);
798
        commitAndStartNewTransaction(tableNames);
799

    
800
        name1 =  this.nameService.load(UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384"));
801
        name2 = this.nameService.load(UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e"));
802
        name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
803
        specimen1 = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("0d19a9ca-21a7-4adb-8640-8d6719e15eea")), DerivedUnit.class);
804
        fossil = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("4c48b7c8-4c8d-4e48-b083-0837fe51a0a9")), DerivedUnit.class);
805

    
806

    
807
        desigs1 = name1.getTypeDesignations();
808
        desigs2 = name2.getTypeDesignations();
809
        desigs3 = name3.getTypeDesignations();
810

    
811
        Assert.assertEquals("name1 should have 0 type designations", 0, desigs1.size());
812
        Assert.assertEquals("name2 should have 0 type designations", 0, desigs2.size());
813
        Assert.assertEquals("name3 should have 0 type designations", 1, desigs3.size());
814
        Assert.assertEquals("Specimen1 should be used in 0 type designation", 0, specimen1.getSpecimenTypeDesignations().size());
815
        Assert.assertEquals("Fossil should be used in 0 type designation", 0, fossil.getSpecimenTypeDesignations().size());
816

    
817
    }
818

    
819
    @Test
820
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class)
821
    public void testDeleteTypeDesignationWithRegistration() {
822
        final String[] tableNames = new String[]{
823
                "TaxonName","TypeDesignationBase","TaxonName_TypeDesignationBase",
824
                "SpecimenOrObservationBase"};
825

    
826
        TaxonName name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
827

    
828
        Set<TypeDesignationBase> desigs3 = name3.getTypeDesignations();
829

    
830
        NameTypeDesignation desig3 = (NameTypeDesignation)name3.getTypeDesignations().iterator().next();
831
        name3.addTypeDesignation(SpecimenTypeDesignation.NewInstance(), false);
832
        this.nameService.update(name3);
833

    
834
        name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
835
        desigs3 = name3.getTypeDesignations();
836

    
837
        NameTypeDesignation desigNew = NameTypeDesignation.NewInstance();
838

    
839
        UsernamePasswordAuthenticationToken submiterToken = new UsernamePasswordAuthenticationToken("admin","sPePhAz6");
840
        setAuthentication(submiterToken);
841
        Registration registration = Registration.NewInstance("abc", "abc", name3, null);
842
        registration.addTypeDesignation(desigNew);
843
        UUID uuidReg = registrationService.saveOrUpdate(registration);
844
        unsetAuthentication();
845

    
846
        commitAndStartNewTransaction(tableNames);
847

    
848
        name3 = nameService.load(name3.getUuid());
849

    
850
        Set<Registration> regs = name3.getRegistrations();
851
        desigs3 = name3.getTypeDesignations();
852
        Assert.assertEquals("name3 should have 2 type designations", 2, desigs3.size());
853
        Assert.assertEquals("name should have 1 registrations", 1, regs.size());
854
        Assert.assertEquals("registration should have 1 type designations",1, regs.iterator().next().getTypeDesignations().size());
855

    
856
        nameService.deleteTypeDesignation(name3, desig3);
857
        commitAndStartNewTransaction(tableNames);
858

    
859
        name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
860

    
861
        regs = name3.getRegistrations();
862
        Assert.assertEquals("name3 should have 1 registration", 1, regs.size());
863
        Assert.assertEquals("registration should have 1 type designations",1, regs.iterator().next().getTypeDesignations().size());
864

    
865
        desigs3 = name3.getTypeDesignations();
866

    
867
        nameService.deleteTypeDesignation(name3, desigNew);
868
        commitAndStartNewTransaction(tableNames);
869
        name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
870
        regs = name3.getRegistrations();
871
        desigs3 = name3.getTypeDesignations();
872

    
873
        Assert.assertEquals("name3 should have 1 type designations", 1, desigs3.size());
874
        Assert.assertEquals("registration should have 0 type designations",0, regs.iterator().next().getTypeDesignations().size());
875
    }
876

    
877

    
878
    @Test
879
    @DataSet
880
    public void testDeleteTypeDesignationAllNames() {
881
        final String[] tableNames = new String[]{
882
                "TaxonName","TypeDesignationBase",
883
                "TaxonName_TypeDesignationBase","SpecimenOrObservationBase"};
884

    
885

    
886
        TaxonName name1 =  this.nameService.load(UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384"));
887
        TaxonName name2 = this.nameService.load(UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e"));
888
        TaxonName name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
889
        DerivedUnit specimen1 = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("0d19a9ca-21a7-4adb-8640-8d6719e15eea")), DerivedUnit.class);
890
        DerivedUnit fossil = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("4c48b7c8-4c8d-4e48-b083-0837fe51a0a9")), DerivedUnit.class);
891

    
892
        Set<TypeDesignationBase> desigs1 = name1.getTypeDesignations();
893
        Set<TypeDesignationBase> desigs2 = name2.getTypeDesignations();
894
        Set<TypeDesignationBase> desigs3 = name3.getTypeDesignations();
895

    
896
        Assert.assertEquals("name1 should have 2 type designations", 2, desigs1.size());
897
        Assert.assertEquals("name2 should have 1 type designations", 1, desigs2.size());
898
        Assert.assertEquals("name3 should have 1 type designations", 1, desigs3.size());
899
        Assert.assertEquals("Specimen1 should be used in 1 type designation", 1, specimen1.getSpecimenTypeDesignations().size());
900
        Assert.assertEquals("Fossil should be used in 1 type designation", 1, fossil.getSpecimenTypeDesignations().size());
901

    
902
        SpecimenTypeDesignation desig2 = (SpecimenTypeDesignation)name2.getTypeDesignations().iterator().next();
903

    
904
        nameService.deleteTypeDesignation(null, desig2);
905

    
906
        commitAndStartNewTransaction(tableNames);
907

    
908
        name1 =  this.nameService.load(UUID.fromString("6dbd41d1-fe13-4d9c-bb58-31f051c2c384"));
909
        name2 = this.nameService.load(UUID.fromString("f9e9c13f-5fa5-48d3-88cf-712c921a099e"));
910
        name3 = this.nameService.load(UUID.fromString("e1e66264-f16a-4df9-80fd-6ab5028a3c28"));
911
        specimen1 = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("0d19a9ca-21a7-4adb-8640-8d6719e15eea")), DerivedUnit.class);
912
        fossil = CdmBase.deproxy(this.occurrenceService.load(UUID.fromString("4c48b7c8-4c8d-4e48-b083-0837fe51a0a9")), DerivedUnit.class);
913

    
914
        desigs1 = name1.getTypeDesignations();
915
        desigs2 = name2.getTypeDesignations();
916
        desigs3 = name3.getTypeDesignations();
917

    
918
        Assert.assertEquals("name1 should have 1 type designations", 1, desigs1.size());
919
        Assert.assertEquals("name2 should have 0 type designations", 0, desigs2.size());
920
        Assert.assertEquals("name3 should have 1 type designations", 1, desigs3.size());
921
        Assert.assertEquals("Specimen1 should be used in 0 type designation", 0, specimen1.getSpecimenTypeDesignations().size());
922
        Assert.assertEquals("Fossil should be used in 1 type designation", 1, fossil.getSpecimenTypeDesignations().size());
923

    
924
    }
925

    
926
    @Test
927
    @DataSet
928
    public void findByTitleWithRestrictions(){
929

    
930
        // The following typeDesignations per name are assumed:
931
        // Name1 -> SpecimenTypeDesignation -> Specimen1
932
        //       -> SpecimenTypeDesignation -> Specimen2
933
        // Name2 -> SpecimenTypeDesignation -> Specimen2
934

    
935
        // Logger.getLogger("org.hibernate.SQL").setLevel(Level.TRACE);
936

    
937

    
938
        List<Restriction<?>> restrictions;
939
        Pager<TaxonName> result;
940

    
941
        result = nameService.findByTitleWithRestrictions(null, "Name1", MatchMode.EXACT, null, null, null, null, null);
942
        assertEquals(1l, result.getCount().longValue());
943
        assertEquals("Name1", result.getRecords().iterator().next().getTitleCache());
944

    
945
        result = nameService.findByTitleWithRestrictions(null, "Name", MatchMode.BEGINNING, null, null, null, null, null);
946
        assertEquals(3l, result.getCount().longValue());
947

    
948
        restrictions = Arrays.asList(new Restriction<UUID>("typeDesignations.uuid", null, UUID.fromString("9bbda70b-7272-4e65-a807-852a3f2eba63")));
949
        result = nameService.findByTitleWithRestrictions(null, "Name", MatchMode.BEGINNING, restrictions, null, null, null, null);
950
        assertEquals(1l, result.getCount().longValue());
951
        assertEquals("Name1", result.getRecords().iterator().next().getTitleCache());
952

    
953
        result = nameService.findByTitleWithRestrictions(null, "me1", MatchMode.END, restrictions, null, null, null, null);
954
        assertEquals(1l, result.getCount().longValue());
955
        assertEquals("Name1", result.getRecords().iterator().next().getTitleCache());
956

    
957
        result = nameService.findByTitleWithRestrictions(null, "Name2", MatchMode.EXACT, restrictions, null, null, null, null);
958
        assertEquals(0l, result.getCount().longValue());
959

    
960
        // Logger.getLogger("eu.etaxonomy.cdm.persistence.dao.hibernate.common").setLevel(Level.DEBUG);
961

    
962
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeSpecimen.titleCache", MatchMode.EXACT, "Specimen2"));
963
        result = nameService.findByTitleWithRestrictions(null, "Name2", MatchMode.EXACT, restrictions, null, null, null, null);
964
        assertEquals(1l, result.getCount().longValue());
965
        assertEquals("Name2", result.getRecords().iterator().next().getTitleCache());
966

    
967
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeSpecimen.titleCache", MatchMode.EXACT, "Specimen1"));
968
        result = nameService.findByTitleWithRestrictions(null, "Name2", MatchMode.EXACT, restrictions, null, null, null, null);
969
        assertEquals(0l, result.getCount().longValue());
970

    
971
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeSpecimen.titleCache", Restriction.Operator.OR, MatchMode.EXACT, "Specimen1"));
972
        result = nameService.findByTitleWithRestrictions(null, "Name2", MatchMode.EXACT, restrictions, null, null, null, null);
973
        assertEquals(2l, result.getCount().longValue());
974

    
975
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeSpecimen.titleCache", MatchMode.BEGINNING, "Specimen"));
976
        result = nameService.findByTitleWithRestrictions(null, "Name1", MatchMode.EXACT, restrictions, null, null, null, null);
977
        assertEquals("names with multiple matching typeSpecimens must be deduplicated", 1l, result.getCount().longValue());
978
        assertEquals("Name1", result.getRecords().iterator().next().getTitleCache());
979

    
980
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeSpecimen.titleCache", MatchMode.BEGINNING, "Specimen"));
981
        result = nameService.findByTitleWithRestrictions(null, "Name", MatchMode.BEGINNING, restrictions, null, null, null, null);
982
        assertEquals(2l, result.getCount().longValue());
983

    
984
    }
985

    
986
    @Test
987
    @DataSet
988
    public void testFindByTitleTitleWithRestrictionsMultiValue(){
989

    
990
        // The following typedesigbnations per name are assumed:
991
        // Name1 -> SpecimenTypeDesignation -> Specimen1
992
        //       -> SpecimenTypeDesignation -> Specimen2
993
        // Name2 -> SpecimenTypeDesignation -> Specimen2
994
        // Name3 -> NameTypeDesignaton-> typeName = Name1
995

    
996
        List<Restriction<?>> restrictions;
997
        Pager<TaxonName> result;
998

    
999
        restrictions = Arrays.asList(new Restriction<UUID>("typeDesignations.uuid", null, UUID.fromString("9bbda70b-7272-4e65-a807-852a3f2eba63"), UUID.fromString("1357c307-00c3-499c-8e20-0849d4706125")));
1000
        result = nameService.findByTitleWithRestrictions(null, "Name", MatchMode.BEGINNING, restrictions, null, null, null, null);
1001
        assertEquals(2l, result.getCount().longValue());
1002

    
1003
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeSpecimen.titleCache", null, "Specimen1", "Specimen2"));
1004
        result = nameService.findByTitleWithRestrictions(null, "Name1", MatchMode.EXACT, restrictions, null, null, null, null);
1005
        assertEquals("names with multiple matching typeSpecimens must be distinct", 1l, result.getCount().longValue());
1006
        assertEquals("Name1", result.getRecords().iterator().next().getTitleCache());
1007
    }
1008

    
1009
    @Test
1010
    @DataSet
1011
    public void testFindByTitleTitleWithRestrictionsLogicalOperators(){
1012

    
1013
        // The following typedesigbnations per name are assumed:
1014
        // Name1 -> SpecimenTypeDesignation -> Specimen1
1015
        //       -> SpecimenTypeDesignation -> Specimen2
1016
        // Name2 -> SpecimenTypeDesignation -> Specimen2
1017
        // Name3 -> NameTypeDesignaton-> typeName = Name1
1018

    
1019
        List<Restriction<?>> restrictions;
1020
        Pager<TaxonName> result;
1021

    
1022
        //Logger.getLogger("org.hibernate.SQL").setLevel(Level.TRACE);
1023

    
1024
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeName.titleCache", Operator.AND, null, "Name1"));
1025
        result = nameService.findByTitleWithRestrictions(null, "Name3", MatchMode.EXACT, restrictions, null, null, null, null);
1026
        assertEquals(1l, result.getCount().longValue());
1027

    
1028
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeName.titleCache", Operator.AND_NOT, null, "Name1"));
1029
        result = nameService.findByTitleWithRestrictions(null, "Name", MatchMode.BEGINNING, restrictions, null, null, null, null);
1030
        assertEquals(2l, result.getCount().longValue());
1031

    
1032
        restrictions = Arrays.asList(new Restriction<String>("titleCache", Operator.AND_NOT, null, "Name1", "Name2"));
1033
        result = nameService.findByTitleWithRestrictions(null, "Name", MatchMode.BEGINNING, restrictions, null, null, null, null);
1034
        assertEquals(1l, result.getCount().longValue());
1035
        assertEquals("Name3", result.getRecords().get(0).getTitleCache());
1036

    
1037
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeName.titleCache", Operator.OR, null, "Name1"));
1038
        result = nameService.findByTitleWithRestrictions(null, "Name1", MatchMode.EXACT, restrictions, null, null, null, null);
1039
        assertEquals(2l, result.getCount().longValue());
1040

    
1041
        restrictions = Arrays.asList(new Restriction<String>("typeDesignations.typeName.titleCache", Operator.OR_NOT, null, "Name1"));
1042
        result = nameService.findByTitleWithRestrictions(null, "Name1", MatchMode.EXACT, restrictions, null, null, null, null);
1043
        assertEquals(2l, result.getCount().longValue());
1044

    
1045
    }
1046

    
1047
    @Test
1048
    @DataSet
1049
    public void testFindByTitleTitle_using_Configurator(){
1050

    
1051
        String searchString = "*";
1052
        IdentifiableServiceConfiguratorImpl<TaxonName> searchConfigurator = new IdentifiableServiceConfiguratorImpl<TaxonName>();
1053

    
1054
        searchConfigurator = IdentifiableServiceConfiguratorFactory.getConfigurator(TaxonName.class);
1055
        searchConfigurator.setTitleSearchString(searchString);
1056
        searchConfigurator.setMatchMode(null);
1057
        searchConfigurator.setOrderHints(OrderHint.ORDER_BY_TITLE_CACHE.asList());
1058

    
1059
        Pager<TaxonName> results = nameService.findByTitle(searchConfigurator);
1060
        assertTrue(results.getRecords().size() > 0);
1061

    
1062
    }
1063

    
1064
    @Test  //7874 //8030
1065
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="NameServiceImplTest.testUpdateCaches.xml")
1066
    public void testUpdateCaches() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
1067

    
1068
        Field titleCacheField = IdentifiableEntity.class.getDeclaredField("titleCache");
1069
        titleCacheField.setAccessible(true);
1070
        Field nameCacheField = TaxonName.class.getDeclaredField("nameCache");
1071
        nameCacheField.setAccessible(true);
1072
        Field authorCacheField = TaxonName.class.getDeclaredField("authorshipCache");
1073
        authorCacheField.setAccessible(true);
1074
        Field fullTitleCacheField = TaxonName.class.getDeclaredField("fullTitleCache");
1075
        fullTitleCacheField.setAccessible(true);
1076

    
1077
        TaxonName name1 = nameService.load(NAME1_UUID);
1078
        TaxonName name2 = nameService.load(NAME2_UUID);
1079
        TaxonName name3 = nameService.load(NAME3_UUID);
1080

    
1081
        assertEquals("TitleCache should be the persisted one", "Name1", titleCacheField.get(name1));
1082
        assertEquals("NameCache should be the persisted one", "", nameCacheField.get(name1));
1083
        assertEquals("AuthorCache should be the persisted one", "", authorCacheField.get(name1));
1084
        assertEquals("FullTitleCache should be the persisted one", "", fullTitleCacheField.get(name1));
1085

    
1086
        assertEquals("TitleCache should be the persisted one", "Name2", titleCacheField.get(name2));
1087
        assertEquals("NameCache should be the persisted one", "Protected name", nameCacheField.get(name2));
1088
        assertEquals("AuthorCache should be the persisted one", null, authorCacheField.get(name2));
1089
        assertEquals("FullTitleCache should be the persisted one", "", fullTitleCacheField.get(name2));
1090

    
1091
        nameService.updateTitleCache();
1092

    
1093
        assertEquals("Expecting titleCache to be updated", "First name Turl.", titleCacheField.get(name1));
1094
        assertEquals("Expecting nameCache to be updated", "First name", nameCacheField.get(name1));
1095
        assertEquals("Expecting authorshipCache to be updated", "Turl.", authorCacheField.get(name1));
1096
        assertEquals("Expecting fullTitleCache to be updated", "First name Turl.", fullTitleCacheField.get(name1));
1097

    
1098
        assertEquals("Expecting titleCache to be updated", "Protected name", titleCacheField.get(name2));
1099
        assertEquals("Expecting nameCache to not be updated", "Protected name", nameCacheField.get(name2));
1100
        assertEquals("Expecting authorshipCache to be updated", "", authorCacheField.get(name2));
1101
        assertEquals("Expecting fullTitleCache to be updated", "Protected name", fullTitleCacheField.get(name2));
1102

    
1103
    }
1104

    
1105
    private Rank getSpeciesRank() {
1106
        return (Rank)termService.find(Rank.uuidSpecies);
1107
    }
1108

    
1109
    private Rank getGenusRank() {
1110
        return (Rank)termService.find(Rank.uuidGenus);
1111
    }
1112

    
1113
    @Override
1114
    public void createTestDataSet() throws FileNotFoundException {}
1115

    
1116

    
1117
}
Add picture from clipboard (Maximum size: 40 MB)