Project

General

Profile

Download (50.8 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2007 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.persistence.dao.hibernate.common;
10

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

    
13
import java.io.FileNotFoundException;
14
import java.util.ArrayList;
15
import java.util.Arrays;
16
import java.util.List;
17
import java.util.Map;
18
import java.util.Set;
19
import java.util.UUID;
20

    
21
import org.apache.log4j.Logger;
22
import org.hibernate.MappingException;
23
import org.hibernate.internal.SessionFactoryImpl;
24
import org.hibernate.persister.collection.CollectionPersister;
25
import org.hibernate.stat.Statistics;
26
import org.hibernate.type.Type;
27
import org.junit.Assert;
28
import org.junit.Before;
29
import org.junit.Test;
30
import org.unitils.dbunit.annotation.DataSet;
31
import org.unitils.dbunit.annotation.DataSets;
32
import org.unitils.spring.annotation.SpringBeanByType;
33

    
34
import eu.etaxonomy.cdm.common.URI;
35
import eu.etaxonomy.cdm.model.agent.Address;
36
import eu.etaxonomy.cdm.model.agent.AgentBase;
37
import eu.etaxonomy.cdm.model.agent.Contact;
38
import eu.etaxonomy.cdm.model.agent.Institution;
39
import eu.etaxonomy.cdm.model.agent.InstitutionalMembership;
40
import eu.etaxonomy.cdm.model.agent.Person;
41
import eu.etaxonomy.cdm.model.agent.Team;
42
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
43
import eu.etaxonomy.cdm.model.common.Annotation;
44
import eu.etaxonomy.cdm.model.common.AnnotationType;
45
import eu.etaxonomy.cdm.model.common.CdmBase;
46
import eu.etaxonomy.cdm.model.common.Credit;
47
import eu.etaxonomy.cdm.model.common.Extension;
48
import eu.etaxonomy.cdm.model.common.ExtensionType;
49
import eu.etaxonomy.cdm.model.common.ICdmBase;
50
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
51
import eu.etaxonomy.cdm.model.common.Identifier;
52
import eu.etaxonomy.cdm.model.common.IntextReference;
53
import eu.etaxonomy.cdm.model.common.LSIDAuthority;
54
import eu.etaxonomy.cdm.model.common.Language;
55
import eu.etaxonomy.cdm.model.common.LanguageString;
56
import eu.etaxonomy.cdm.model.common.Marker;
57
import eu.etaxonomy.cdm.model.common.MarkerType;
58
import eu.etaxonomy.cdm.model.common.RelationshipTermBase;
59
import eu.etaxonomy.cdm.model.common.TimePeriod;
60
import eu.etaxonomy.cdm.model.common.VerbatimTimePeriod;
61
import eu.etaxonomy.cdm.model.description.CategoricalData;
62
import eu.etaxonomy.cdm.model.description.CommonTaxonName;
63
import eu.etaxonomy.cdm.model.description.DescriptionBase;
64
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
65
import eu.etaxonomy.cdm.model.description.Distribution;
66
import eu.etaxonomy.cdm.model.description.Feature;
67
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
68
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
69
import eu.etaxonomy.cdm.model.description.MediaKey;
70
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
71
import eu.etaxonomy.cdm.model.description.QuantitativeData;
72
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
73
import eu.etaxonomy.cdm.model.description.State;
74
import eu.etaxonomy.cdm.model.description.StateData;
75
import eu.etaxonomy.cdm.model.description.StatisticalMeasure;
76
import eu.etaxonomy.cdm.model.description.StatisticalMeasurementValue;
77
import eu.etaxonomy.cdm.model.description.TaxonDescription;
78
import eu.etaxonomy.cdm.model.description.TaxonInteraction;
79
import eu.etaxonomy.cdm.model.description.TaxonNameDescription;
80
import eu.etaxonomy.cdm.model.description.TextData;
81
import eu.etaxonomy.cdm.model.description.TextFormat;
82
import eu.etaxonomy.cdm.model.location.Country;
83
import eu.etaxonomy.cdm.model.location.NamedArea;
84
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
85
import eu.etaxonomy.cdm.model.location.NamedAreaType;
86
import eu.etaxonomy.cdm.model.location.Point;
87
import eu.etaxonomy.cdm.model.location.ReferenceSystem;
88
import eu.etaxonomy.cdm.model.media.AudioFile;
89
import eu.etaxonomy.cdm.model.media.ImageFile;
90
import eu.etaxonomy.cdm.model.media.Media;
91
import eu.etaxonomy.cdm.model.media.MediaRepresentation;
92
import eu.etaxonomy.cdm.model.media.MediaRepresentationPart;
93
import eu.etaxonomy.cdm.model.media.MovieFile;
94
import eu.etaxonomy.cdm.model.media.Rights;
95
import eu.etaxonomy.cdm.model.media.RightsType;
96
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
97
import eu.etaxonomy.cdm.model.molecular.Amplification;
98
import eu.etaxonomy.cdm.model.molecular.DnaSample;
99
import eu.etaxonomy.cdm.model.molecular.PhylogeneticTree;
100
import eu.etaxonomy.cdm.model.molecular.Primer;
101
import eu.etaxonomy.cdm.model.molecular.Sequence;
102
import eu.etaxonomy.cdm.model.molecular.SingleRead;
103
import eu.etaxonomy.cdm.model.molecular.SingleReadAlignment;
104
import eu.etaxonomy.cdm.model.name.HomotypicalGroup;
105
import eu.etaxonomy.cdm.model.name.HybridRelationship;
106
import eu.etaxonomy.cdm.model.name.HybridRelationshipType;
107
import eu.etaxonomy.cdm.model.name.IBotanicalName;
108
import eu.etaxonomy.cdm.model.name.NameRelationship;
109
import eu.etaxonomy.cdm.model.name.NameRelationshipType;
110
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
111
import eu.etaxonomy.cdm.model.name.NameTypeDesignationStatus;
112
import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
113
import eu.etaxonomy.cdm.model.name.NomenclaturalStatusType;
114
import eu.etaxonomy.cdm.model.name.Rank;
115
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
116
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
117
import eu.etaxonomy.cdm.model.name.TaxonName;
118
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
119
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
120
import eu.etaxonomy.cdm.model.occurrence.Collection;
121
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
122
import eu.etaxonomy.cdm.model.occurrence.DerivationEventType;
123
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
124
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
125
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
126
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
127
import eu.etaxonomy.cdm.model.occurrence.PreservationMethod;
128
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
129
import eu.etaxonomy.cdm.model.permission.GrantedAuthorityImpl;
130
import eu.etaxonomy.cdm.model.permission.Group;
131
import eu.etaxonomy.cdm.model.permission.User;
132
import eu.etaxonomy.cdm.model.reference.IBook;
133
import eu.etaxonomy.cdm.model.reference.IBookSection;
134
import eu.etaxonomy.cdm.model.reference.OriginalSourceBase;
135
import eu.etaxonomy.cdm.model.reference.OriginalSourceType;
136
import eu.etaxonomy.cdm.model.reference.Reference;
137
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
138
import eu.etaxonomy.cdm.model.taxon.Classification;
139
import eu.etaxonomy.cdm.model.taxon.Synonym;
140
import eu.etaxonomy.cdm.model.taxon.SynonymType;
141
import eu.etaxonomy.cdm.model.taxon.Taxon;
142
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
143
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
144
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
145
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
146
import eu.etaxonomy.cdm.model.term.DefinedTerm;
147
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
148
import eu.etaxonomy.cdm.model.term.OrderedTermBase;
149
import eu.etaxonomy.cdm.model.term.OrderedTermVocabulary;
150
import eu.etaxonomy.cdm.model.term.Representation;
151
import eu.etaxonomy.cdm.model.term.TermNode;
152
import eu.etaxonomy.cdm.model.term.TermTree;
153
import eu.etaxonomy.cdm.model.term.TermVocabulary;
154
import eu.etaxonomy.cdm.model.view.AuditEvent;
155
import eu.etaxonomy.cdm.persistence.dao.agent.IAgentDao;
156
import eu.etaxonomy.cdm.persistence.dao.common.ICdmGenericDao;
157
import eu.etaxonomy.cdm.persistence.dao.name.ITaxonNameDao;
158
import eu.etaxonomy.cdm.persistence.dao.occurrence.IOccurrenceDao;
159
import eu.etaxonomy.cdm.persistence.dao.reference.IReferenceDao;
160
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonDao;
161
import eu.etaxonomy.cdm.persistence.dto.ReferencingObjectDto;
162
import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
163
import eu.etaxonomy.cdm.strategy.match.IMatchStrategyEqual;
164
import eu.etaxonomy.cdm.strategy.match.MatchException;
165
import eu.etaxonomy.cdm.strategy.merge.DefaultMergeStrategy;
166
import eu.etaxonomy.cdm.strategy.merge.IMergeStrategy;
167
import eu.etaxonomy.cdm.strategy.merge.MergeException;
168
import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
169
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
170

    
171
/**
172
 * @author a.mueller
173
 * @since 27.07.2009
174
 */
175
public class CdmGenericDaoImplTest extends CdmTransactionalIntegrationTest {
176

    
177
    private static final Logger logger = Logger.getLogger(CdmGenericDaoImplTest.class);
178

    
179
	@SpringBeanByType
180
	private ICdmGenericDao cdmGenericDao;
181

    
182
	@SpringBeanByType
183
	private ITaxonDao taxonDao;
184

    
185
	@SpringBeanByType
186
	private IOccurrenceDao occurrenceDao;
187

    
188
	@SpringBeanByType
189
	private ITaxonNameDao nameDao;
190

    
191
	@SpringBeanByType
192
	private IAgentDao agentDao;
193

    
194
    @SpringBeanByType
195
    private IReferenceDao referenceDao;
196

    
197
	@Before
198
	public void setUp() throws Exception {}
199

    
200
// ***************** TESTS **************************************************
201

    
202
	@Test
203
	@DataSets({
204
      @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
205
      @DataSet("/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml")}
206
	)
207
	public void testDelete(){
208
		Reference ref1 = ReferenceFactory.newBook();
209
		Reference ref2 = ReferenceFactory.newBook();
210
		Annotation annotation = Annotation.NewInstance("Anno1", null);
211
		ref1.addAnnotation(annotation);
212
		cdmGenericDao.saveOrUpdate(ref1);
213
		cdmGenericDao.saveOrUpdate(ref2);
214
		List<Reference> list = cdmGenericDao.list(Reference.class, 10, 0, null, null);
215

    
216
		try {
217
			cdmGenericDao.merge(ref2, ref1, null);
218

    
219
		} catch (MergeException e) {
220
			Assert.fail();
221
		}
222
		commitAndStartNewTransaction(null);
223
		list = cdmGenericDao.list(Reference.class, 10, 0, null, null);
224
		Assert.assertEquals(1, list.size());
225
	}
226

    
227
	@Test
228
	public void testGetCdmBasesByFieldAndClass() {
229
		logger.warn("Not yet implemented");
230
	}
231

    
232
	@Test
233
	public void testGetCdmBasesWithItemInCollection() {
234
		logger.warn("Not yet implemented");
235
	}
236

    
237
	@Test
238
	public void testGetAllPersistedClasses() {
239
		Class<?>[] existingClassesArray = {
240
				Address.class,
241
				AgentBase.class,
242
				Institution.class,
243
				InstitutionalMembership.class,
244
				Person.class,
245
				Team.class,
246
				TeamOrPersonBase.class,
247
				Annotation.class,
248
				AnnotationType.class,
249
				Credit.class,
250
				DefinedTermBase.class,
251
				Extension.class,
252
				ExtensionType.class,
253
				GrantedAuthorityImpl.class,
254
				Group.class,
255
				IdentifiableSource.class,
256
				Identifier.class,
257
				IntextReference.class,
258
				Language.class,
259
				LanguageString.class,
260
				LSIDAuthority.class,
261
				Marker.class,
262
				MarkerType.class,
263
				OrderedTermBase.class,
264
				OrderedTermVocabulary.class,
265
				OriginalSourceBase.class,
266
				RelationshipTermBase.class,
267
				Representation.class,
268
				TermVocabulary.class,
269
				User.class,
270
				DefinedTerm.class,
271

    
272
				CategoricalData.class,
273
				CommonTaxonName.class,
274
				DescriptionBase.class,
275
				DescriptionElementBase.class,
276
				Distribution.class,
277
				Feature.class,
278
				TermNode.class,
279
				TermTree.class,
280
				MediaKey.class,
281
				IndividualsAssociation.class,
282
				MeasurementUnit.class,
283
				PresenceAbsenceTerm.class,
284
				QuantitativeData.class,
285
				SpecimenDescription.class,
286
				State.class,
287
				StateData.class,
288
				StatisticalMeasure.class,
289
				StatisticalMeasurementValue.class,
290
				TaxonDescription.class,
291
				TaxonInteraction.class,
292
				TaxonNameDescription.class,
293
				TextData.class,
294
				TextFormat.class,
295
				NamedArea.class,
296
				NamedAreaLevel.class,
297
				NamedAreaType.class,
298
				ReferenceSystem.class,
299
				Country.class,
300
				AudioFile.class,
301
				ImageFile.class,
302
				Media.class,
303
				MediaRepresentation.class,
304
				MediaRepresentationPart.class,
305
				MovieFile.class,
306
				Rights.class,
307
				RightsType.class,
308
				Amplification.class,
309
				DnaSample.class,
310
				SingleRead.class,
311
				SingleReadAlignment.class,
312
				Primer.class,
313
				Sequence.class,
314
				PhylogeneticTree.class,
315
				Sequence.class,
316
				HomotypicalGroup.class,
317
				HybridRelationship.class,
318
				HybridRelationshipType.class,
319
				NameRelationship.class,
320
				NameRelationshipType.class,
321
				NameTypeDesignation.class,
322
				NameTypeDesignationStatus.class,
323
				NomenclaturalStatus.class,
324
				NomenclaturalStatusType.class,
325
				Rank.class,
326
				SpecimenTypeDesignation.class,
327
				SpecimenTypeDesignationStatus.class,
328
				TaxonName.class,
329
				TypeDesignationBase.class,
330
				Collection.class,
331
				DerivationEvent.class,
332
				DerivationEventType.class,
333
				DerivedUnit.class,
334
				DeterminationEvent.class,
335
				FieldUnit.class,
336
				GatheringEvent.class,
337
				PreservationMethod.class,
338
				SpecimenOrObservationBase.class,
339
				Reference.class,
340
				Synonym.class,
341
				SynonymType.class,
342
				Taxon.class,
343
				TaxonBase.class,
344
				TaxonNode.class,
345
				Classification.class,
346
				TaxonRelationship.class,
347
				TaxonRelationshipType.class ,
348
				//Contact.class,  //these are embedabble classes
349
				//LSID.class,
350
				//Point.class,
351
				//NomenclaturalCode.class,
352
		}	;
353
		List<Class<?>> existingClassesList = new ArrayList<>();
354
		existingClassesList.addAll(Arrays.asList(existingClassesArray));
355
		boolean includeAbstractClasses = true;
356
		Set<Class<? extends CdmBase>> foundClasses = cdmGenericDao.getAllPersistedClasses(includeAbstractClasses);
357

    
358
		//for debugging only
359
		//		for (Class existingClass : existingClassesList){
360
		//			if (! foundClasses.contains(existingClass)){
361
		//				logger.warn("Class not found: " + existingClass.getCanonicalName());
362
		//			}
363
		//		}
364

    
365
		//All classes must be found
366
		Assert.assertTrue("all classes must be found by getAllCdmClasses() method", foundClasses.containsAll(existingClassesList));
367

    
368
		//No extra classes must be found
369
		for (Class<?> clazz : foundClasses){
370
			if (! CdmBase.class.isAssignableFrom(clazz)&& !( AuditEvent.class == clazz) && !( CdmPreference.class == clazz)  ){ //OLD: && !( LSID.class == clazz)&& !( NomenclaturalCode.class == clazz) && !( Point.class == clazz) && !( Modifier.class == clazz) && !( Contact.class == clazz)
371
				Assert.fail("Class " + clazz.getName() + " is not assignable from CdmBase");
372
			}
373
		}
374

    
375
		includeAbstractClasses = false;
376
		Set<Class<? extends CdmBase>> noAbstractClasses = cdmGenericDao.getAllPersistedClasses(includeAbstractClasses);
377
		Class<?> abstractClassToTest = TaxonBase.class;
378
		Assert.assertFalse("Abstract class " + abstractClassToTest.getName() + " may not be in set ", noAbstractClasses.contains(abstractClassToTest));
379
	}
380

    
381
	@Test
382
	@DataSets({
383
	     @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
384
	     @DataSet("/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml")})
385
	public void testGetReferencingObjectsCdmBase() {
386
		IBotanicalName name = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
387
		name.setTitleCache("A name", true);
388
		Reference ref1 = ReferenceFactory.newArticle();
389
		Taxon taxon = Taxon.NewInstance(name, ref1);
390
		Person author = Person.NewInstance();
391
		author.setTitleCache("Author", true);
392
		ref1.addAnnotation(Annotation.NewInstance("A1", Language.DEFAULT()));
393
		ref1.setAuthorship(author);
394
		name.setBasionymAuthorship(author);
395

    
396
		name.setNomenclaturalReference(ref1);
397

    
398
		taxonDao.save(taxon);
399
//		UUID uuid = UUID.fromString("613980ac-9bd5-43b9-a374-d71e1794688f");
400
//		Reference ref1 = referenceService.findByUuid(uuid);
401
		commitAndStartNewTransaction(null);
402

    
403
		Set<CdmBase> referencedObjects = cdmGenericDao.getReferencingObjects(ref1);
404
		String debug = "############## RESULT ###################";
405
		for (CdmBase obj: referencedObjects){
406
			debug += "Object1: " + obj.getClass().getSimpleName() + " - " + obj;
407
		}
408
		//was 3 before bidirectionality was removed for supplemental data
409
		assertEquals(2, referencedObjects.size());
410
		debug += "############## END ###################";
411

    
412
//		UUID uuidAuthor = UUID.fromString("4ce66544-a5a3-4601-ab0b-1f0a1338327b");
413
//		AgentBase author = agentService.findByUuid(uuidAuthor);
414

    
415
		referencedObjects = cdmGenericDao.getReferencingObjects(author);
416
		debug += "############## RESULT ###################";
417
		for (CdmBase obj: referencedObjects){
418
			debug += "Object2: " + obj.getClass().getSimpleName() + " - " + obj;
419
		}
420
		assertEquals(2, referencedObjects.size());
421
		debug += "############## END ###################";
422
		logger.info(debug);
423
	}
424

    
425

    
426
	//similar to testGetReferencingObjectsCdmBase but with DTO
427
	@Test
428
    @DataSets({
429
         @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
430
         @DataSet("/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml")})
431
    public void testGetReferencingObjectsDto() {
432

    
433
	    IBotanicalName name = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
434
        name.setTitleCache("A name", true);
435
        Reference ref1 = ReferenceFactory.newArticle();
436
        Taxon taxon = Taxon.NewInstance(name, ref1);
437
        Person author = Person.NewInstance();
438
        author.setTitleCache("Author", true);
439
        ref1.addAnnotation(Annotation.NewInstance("A1", Language.DEFAULT()));
440
        ref1.setAuthorship(author);
441
        name.setCombinationAuthorship(author);
442
        name.setBasionymAuthorship(author);  //to test deduplication
443

    
444
        name.setNomenclaturalReference(ref1);
445

    
446
        taxonDao.save(taxon);
447
//	      UUID uuid = UUID.fromString("613980ac-9bd5-43b9-a374-d71e1794688f");
448
//	      Reference ref1 = referenceService.findByUuid(uuid);
449
        commitAndStartNewTransaction(null);
450

    
451
        int i = 1;
452
        Set<ReferencingObjectDto> referencedObjects = cdmGenericDao.getReferencingObjectsDto(ref1);
453
        String debug = "############## RESULT for ref1 ###################\n";
454
        for (ReferencingObjectDto dto: referencedObjects){
455
            debug += "Object"+ i++ +": " + dto.getType().getSimpleName() + " - " + dto + "\n";
456
        }
457
        //was 3 before bidirectionality was removed for supplemental data
458
        assertEquals(2, referencedObjects.size());
459
        debug += "############## END ###################\n";
460

    
461
//	      UUID uuidAuthor = UUID.fromString("4ce66544-a5a3-4601-ab0b-1f0a1338327b");
462
//	      AgentBase author = agentService.findByUuid(uuidAuthor);
463

    
464
        referencedObjects = cdmGenericDao.getReferencingObjectsDto(author);
465
        i = 1;
466
        debug += "############## RESULT for author ###################\n";
467
        for (ReferencingObjectDto dto: referencedObjects){
468
            debug += "Object"+ i++ +": " + dto.getType().getSimpleName() + " - " + dto + "\n";
469
        }
470
        assertEquals("The both taxon names should be dedulicated", 2, referencedObjects.size());
471
        debug += "############## END ###################\n";
472
        logger.warn(debug);
473
    }
474

    
475
	/**
476
	 * 2nd test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getReferencingObjects(CdmBase)}.
477
	 */
478
	@Test
479
	@DataSet
480
	public final void testGetReferencingObjects2() {
481
//		SpecimenDescription desc1 = SpecimenDescription.NewInstance();
482
//		desc1.setTitleCache("desc1");
483
//		SpecimenDescription desc2 = SpecimenDescription.NewInstance();
484
//		desc2.setTitleCache("desc2");
485
//
486
//		SpecimenOrObservationBase spec1 = Specimen.NewInstance();
487
//
488
//		desc1.addDescribedSpecimenOrObservation(spec1);
489
//		//Taxon taxon = Taxon.NewInstance(taxonName, sec)
490
//		spec1.addDescription(desc2);
491
//
492
//		occurrenceService.save(spec1);
493

    
494
		UUID uuidSpec = UUID.fromString("41539e9c-3764-4f14-9712-2d07d00c8e4c");
495
		SpecimenOrObservationBase<?> spec1 = occurrenceDao.findByUuid(uuidSpec);
496

    
497
		Set<CdmBase> referencingObjects = cdmGenericDao.getReferencingObjects(spec1);
498
//		System.out.println("############## RESULT ###################");
499
//		for (CdmBase obj: referencingObjects){
500
//			System.out.println("Object: " + obj.getClass().getSimpleName() + " - " + obj);
501
//		}
502
//		System.out.println("############## END ###################");
503
		assertEquals("Number of referencing objects must be 2.", 2, referencingObjects.size());
504
	}
505

    
506
	/**
507
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
508
	 * @throws MergeException
509
	 */
510
	@Test
511
	public void testMergeCdmBaseReferenceAndIdentifiable() throws MergeException {
512

    
513
		TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
514
		name1.setTitleCache("BotanicalName1", true);
515

    
516
		TaxonName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
517
		name2.setTitleCache("BotanicalName2", true);
518

    
519
		TaxonName zooName1 = TaxonNameFactory.NewZoologicalInstance(Rank.SPECIES());
520
		name1.setTitleCache("ZoologicalName1", true);
521

    
522
		Reference article1 = ReferenceFactory.newArticle();
523
		Reference article2 = ReferenceFactory.newArticle();
524

    
525
		name1.setNomenclaturalReference(article1);
526
		name2.setNomenclaturalReference(article2);
527

    
528
		Taxon taxon1 = Taxon.NewInstance(name1, article1);
529
		Taxon taxon2 = Taxon.NewInstance(name2, article2);
530

    
531
//		Person author = Person.NewInstance();
532
//		author.setTitleCache("Author");
533
		Annotation annotation1 = Annotation.NewInstance("A1", Language.DEFAULT());
534
		Annotation annotation2 = Annotation.NewInstance("A2", Language.DEFAULT());
535

    
536
		article1.addAnnotation(annotation1);
537
		article2.addAnnotation(annotation2);
538

    
539
		Marker marker1 = Marker.NewInstance(MarkerType.COMPLETE(), false);
540
		Marker marker2 = Marker.NewInstance(MarkerType.IMPORTED(), false);
541

    
542
		article1.addMarker(marker1);
543
		article2.addMarker(marker2);
544

    
545
		Rights rights1 = Rights.NewInstance();
546
		Rights rights2 = Rights.NewInstance();
547

    
548
		article1.addRights(rights1);
549
		article2.addRights(rights2);
550

    
551
		Credit credit1 = Credit.NewInstance(Team.NewInstance(), "credit1");
552
		Credit credit2 = Credit.NewInstance(Team.NewInstance(), "credit2");
553

    
554
		article1.addCredit(credit1);
555
		article2.addCredit(credit2);
556

    
557
		Extension extension1 = Extension.NewInstance();
558
		Extension extension2 = Extension.NewInstance();
559

    
560
		article1.addExtension(extension1);
561
		article2.addExtension(extension2);
562

    
563
		IdentifiableSource source1 = IdentifiableSource.NewInstance(OriginalSourceType.Unknown);
564
		IdentifiableSource source2 = IdentifiableSource.NewInstance(OriginalSourceType.Unknown);
565

    
566
		article1.addSource(source1);
567
		article2.addSource(source2);
568

    
569
		Media media1 = Media.NewInstance();
570
		Media media2 = Media.NewInstance();
571

    
572
		article1.addMedia(media1);
573
		article2.addMedia(media2);
574

    
575
//		ref1.setAuthorship(author);
576
//		name1.setBasionymAuthorship(author);
577

    
578
		name1.setNomenclaturalReference(article1);
579

    
580
		nameDao.save(name1);
581
		nameDao.save(name2);
582
		nameDao.save(zooName1);
583

    
584
		TaxonDescription taxDesc = TaxonDescription.NewInstance(taxon1);
585
		taxDesc.setTitleCache("taxDesc", true);
586
		taxDesc.addSource(OriginalSourceType.Unknown, null, null, article2, null);
587

    
588
		taxonDao.save(taxon1);
589

    
590
		//unidircetional reference to the merged object should be redirected
591
		cdmGenericDao.merge(article1, article2, null);
592
		Assert.assertEquals("Name2 must have article 1 as new nomRef", article1 ,name2.getNomenclaturalReference());
593
		//TODO microCitations!! -> warning
594

    
595
		//Annotations
596
		Assert.assertEquals("Annotation number should be 2 (1 from each of the merged objects)", 2, article1.getAnnotations().size());
597

    
598
		//Marker
599
		Assert.assertEquals("Marker number should be 2 (1 from each of the merged objects)", 2, article1.getMarkers().size());
600

    
601
		//Rights
602
		Assert.assertEquals("Rights number should be 2 (1 from each of the merged objects)", 2, article1.getRights().size());
603

    
604
		//Credits
605
		Assert.assertEquals("Credits number should be 2 (1 from each of the merged objects)", 2, article1.getCredits().size());
606

    
607
		//Extensions
608
		Assert.assertEquals("Extensions number should be 2 (1 from each of the merged objects)", 2, article1.getExtensions().size());
609

    
610
		//Sources
611
		Assert.assertEquals("Sources number should be 2 (1 from each of the merged objects)", 2, article1.getSources().size());
612

    
613
		//Media
614
		Assert.assertEquals("Media number should be 2 (1 from each of the merged objects)", 2, article1.getMedia().size());
615

    
616
		//Description sources
617
		Assert.assertEquals("Number of sources for taxon description must be 1", 1, taxDesc.getSources().size());
618
		Assert.assertEquals("Taxon description must have article1 as source", taxDesc.getSources().iterator().next().getCitation(),article1);
619

    
620
		//test exceptions
621

    
622
		testMergeExceptions(name1, name2, taxon1, zooName1);
623

    
624
		//FIXME TO BE IMPLEMENTED
625
		//current defalt implementation for rights, credits and media is ADD_CLONE and therefore the below tests don't work
626
		//TODO is this the wanted default behaviour?
627
//		Assert.assertTrue("Rights2 must be contained in the rights", article1.getRights().contains(rights2));
628
//		Assert.assertTrue("Credits2 must be contained in the credits", article1.getCredits().contains(credit2));
629
//		Assert.assertTrue("Media2 must be contained in the media", article1.getMedia().contains(media2));
630

    
631
	}
632

    
633
	@Test
634
	public void testMergeTaxonNameAndTaxon() throws MergeException {
635
	    TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
636
		name1.setTitleCache("BotanicalName1", true);
637

    
638
		TaxonName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
639
		name2.setTitleCache("BotanicalName2", true);
640

    
641
		IBotanicalName name3 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
642
		name3.setTitleCache("BotanicalName3", true);
643

    
644
		Reference database = ReferenceFactory.newDatabase();
645

    
646
		Taxon taxon1 = Taxon.NewInstance(name1, database);
647
		Taxon taxon2 = Taxon.NewInstance(name2, database);
648
		Taxon taxon3 = Taxon.NewInstance(name3, database);
649

    
650
		taxonDao.save(taxon1);
651
		taxonDao.save(taxon2);
652
		taxonDao.save(taxon3);
653

    
654
		cdmGenericDao.merge(name1, name2, null);
655
		Assert.assertEquals("Name1 must have 2 taxa attached now.", 2 ,name1.getTaxonBases().size());
656
		Assert.assertEquals("Taxon2 must have name1 as new name.", name1 ,taxon2.getName());
657

    
658
//TODO
659
//		cdmGenericDao.merge(taxon1, taxon3, null);
660
//		Assert.assertEquals("Name1 must have 3 taxa attached now.", 3 ,name1.getTaxonBases().size());
661
	}
662

    
663
	@Test
664
	public void testMergeAuthors() throws MergeException {
665

    
666
		IBotanicalName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
667
		name1.setTitleCache("BotanicalName1", true);
668

    
669
		IBotanicalName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
670
		name2.setTitleCache("BotanicalName2", true);
671

    
672
		IBook book1 = ReferenceFactory.newBook();
673
		IBook book2 = ReferenceFactory.newBook();
674

    
675
		Team team1 = Team.NewInstance();
676
		Team team2 = Team.NewInstance();
677
		Team team3 = Team.NewInstance();
678
		team1.setTitleCache("team1", true);
679
		team2.setTitleCache("team2", true);
680
		team3.setTitleCache("team3", true);
681

    
682
		Person person1 = Person.NewTitledInstance("person1");
683
		Person person2 = Person.NewTitledInstance("person2");
684
		Person person3 = Person.NewTitledInstance("person3");
685

    
686
		team1.setNomenclaturalTitleCache("T.1", true);
687
		String street1 = "Strasse1";
688
		team1.setContact(Contact.NewInstance(street1, "12345", "Berlin", Country.ARGENTINAARGENTINEREPUBLIC(),"pobox" , "Region", "a@b.de", "f12345", "+49-30-123456", URI.create("www.abc.de"), Point.NewInstance(2.4, 3.2, ReferenceSystem.WGS84(), 3)));
689
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
690
		String street3 = "Street3";
691
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
692
		String emailAddress1 = "Email1";
693
		team1.addEmailAddress(emailAddress1);
694

    
695
		team2.addTeamMember(person1);
696
		team2.addTeamMember(person2);
697
		String emailAddress2 = "Email2";
698
		team2.addEmailAddress(emailAddress2);
699

    
700
		team3.addTeamMember(person3);
701
		team3.addEmailAddress("emailAddress3");
702

    
703
		book1.setAuthorship(team2);
704
		book2.setAuthorship(team3);
705

    
706
		Credit credit1 = Credit.NewInstance(team3, "credit1");
707
		book2.addCredit(credit1);
708

    
709
		agentDao.save(team1);
710
		agentDao.save(team2);
711
		agentDao.save(team3);
712
		cdmGenericDao.save((Reference)book1);
713
		cdmGenericDao.save((Reference)book2);
714

    
715
		cdmGenericDao.merge(team2, team3, null);
716

    
717
		Assert.assertSame("Author of book1 must be team2.", team2, book1.getAuthorship());
718
		Assert.assertSame("Author of book2 must be team2.", team2, book2.getAuthorship());
719
		Assert.assertSame("Agent of credit1 must be team2.", team2, credit1.getAgent());
720

    
721
		Assert.assertEquals("Team2 must have 3 persons as members.",3, team2.getTeamMembers().size());
722
		Assert.assertTrue("Team2 must have person3 as new member.", team2.getTeamMembers().contains(person3));
723
		Assert.assertSame("Team2 must have person3 as third member.",person3, team2.getTeamMembers().get(2));
724

    
725
		//Contact
726
		cdmGenericDao.merge(team2, team1, null);
727
		Contact team2Contact = team2.getContact();
728
		Assert.assertNotNull("team2Contact must not be null", team2Contact);
729
		Assert.assertNotNull("Addresses must not be null", team2Contact.getAddresses());
730
		Assert.assertEquals("Number of addresses must be 3", 3, team2Contact.getAddresses().size());
731
		Assert.assertEquals("Number of email addresses must be 4", 4, team2Contact.getEmailAddresses().size());
732

    
733
		boolean street1Exists = false;
734
		boolean street3Exists = false;
735
		boolean country1Exists = false;
736
		for  (Address address : team2Contact.getAddresses()){
737
			if (street1.equals(address.getStreet())){
738
				street1Exists = true;
739
			}
740
			if (street3.equals(address.getStreet())){
741
				street3Exists = true;
742
			}
743
			if (Country.ARGENTINAARGENTINEREPUBLIC() == address.getCountry()){
744
				country1Exists = true;
745
			}
746
		}
747
		Assert.assertTrue("Street1 must be one of the streets in team2's addresses", street1Exists);
748
		Assert.assertTrue("Street3 must be one of the streets in team2's addressesss", street3Exists);
749
		Assert.assertTrue("Argentina must be one of the countries in team2's addresses", country1Exists);
750

    
751
		//Person
752
		Institution institution1 = Institution.NewInstance();
753
		institution1.setTitleCache("inst1", true);
754
		Institution institution2 = Institution.NewInstance();
755
		institution2.setTitleCache("inst2", true);
756

    
757
		TimePeriod period1 = TimePeriod.NewInstance(2002, 2004);
758
		TimePeriod period2 = TimePeriod.NewInstance(2004, 2006);
759

    
760
		person1.addInstitutionalMembership(institution1, period1, "departement1", "role1");
761
		person2.addInstitutionalMembership(institution2, period2, "departement2", "role2");
762

    
763
		IMergeStrategy personMergeStrategy = DefaultMergeStrategy.NewInstance(Person.class);
764
		personMergeStrategy.invoke(person1, person2);
765

    
766
		Assert.assertEquals("Number of institutional memberships must be 2", 2, person1.getInstitutionalMemberships().size());
767
		for (InstitutionalMembership institutionalMembership : person1.getInstitutionalMemberships()){
768
			Assert.assertSame("Person of institutional memebership must be person1", person1, institutionalMembership.getPerson());
769
		}
770
	}
771

    
772
	/**
773
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
774
     *
775
     * Test for https://dev.e-taxonomy.eu/redmine/issues/5652
776
     *
777
     * @throws MergeException
778
     */
779
    @Test
780
    public void testMergePersons() throws MergeException {
781
        Team team1 = Team.NewInstance();
782
        Team team2 = Team.NewInstance();
783
        Team team3 = Team.NewInstance();
784
        team1.setTitleCache("team1", true);
785
        team2.setTitleCache("team2", true);
786
        team3.setTitleCache("team3", true);
787

    
788
        Person person1a = Person.NewTitledInstance("person1a");
789
        Person person1b = Person.NewTitledInstance("person1b");
790
        Person person2 = Person.NewTitledInstance("person2");
791
        Person person3 = Person.NewTitledInstance("person3");
792

    
793
        team1.addTeamMember(person1a);
794
        team1.addTeamMember(person2);
795

    
796
        team2.addTeamMember(person2);
797
        team2.addTeamMember(person1a);
798
        team2.addTeamMember(person3);
799

    
800
        team3.addTeamMember(person3);
801

    
802
        agentDao.save(team1);
803
        agentDao.save(team2);
804
        agentDao.save(team3);
805
        agentDao.save(person1b);
806
        commitAndStartNewTransaction(null);
807

    
808
        IMergeStrategy personMergeStrategy = DefaultMergeStrategy.NewInstance(Person.class);
809
        cdmGenericDao.merge(person1b, person1a, personMergeStrategy);
810

    
811
        team1 = (Team)agentDao.load(team1.getUuid());
812
        team2 = (Team)agentDao.load(team2.getUuid());
813

    
814
        //order should not change and 1a should be replaced by 1b
815
        Assert.assertEquals("person1b", team1.getTeamMembers().get(0).getTitleCache());
816
        Assert.assertEquals("person2", team1.getTeamMembers().get(1).getTitleCache());
817

    
818
        Assert.assertEquals("person2", team2.getTeamMembers().get(0).getTitleCache());
819
        Assert.assertEquals("person1b", team2.getTeamMembers().get(1).getTitleCache());
820
        Assert.assertEquals("person3", team2.getTeamMembers().get(2).getTitleCache());
821
    }
822

    
823
    @Test
824
    public void testReallocateIntextReferenceForReferenceAndLanguageString() throws MergeException {
825
        UUID uuidRef1 = UUID.fromString("41743cec-b893-4e8b-b06c-91f9b9ba8fee");
826
        UUID uuidRef2 = UUID.fromString("8fd56b43-7cca-4c3b-bb90-7576da81c072");
827

    
828
        // CREATE DATA
829

    
830
        Reference ref1 = ReferenceFactory.newGeneric();
831
        ref1.setTitle("Reference1");
832
        ref1.setUuid(uuidRef1);
833
        Reference ref2 = ReferenceFactory.newGeneric();
834
        ref2.setTitle("Reference2");
835
        ref2.setUuid(uuidRef2);
836
        referenceDao.save(ref2);
837
        Taxon taxon = Taxon.NewInstance(null, null);
838

    
839
        TaxonDescription desc = TaxonDescription.NewInstance(taxon);
840
        Language language = Language.DEFAULT();
841
        TextData textData = TextData.NewInstance(Feature.DESCRIPTION(), "And here is a citation" , language, null);
842
        LanguageString languageString = textData.getLanguageText(language);
843
        IntextReference intextRefRef = languageString.addIntextReference(ref1, 4, 8);
844
        String uuidIntextRefRef = intextRefRef.getUuid().toString();
845
        desc.addElement(textData);
846
        Assert.assertEquals("And <cdm:reference cdmId='"+uuidRef1+"' intextId='"+uuidIntextRefRef+"'>here</cdm:reference> is a citation",
847
                    languageString.getText());
848

    
849
        //SAVE AND COMMIT
850
        taxonDao.save(taxon);
851
        commitAndStartNewTransaction(null);
852

    
853
        //MERGE
854
        DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(Reference.class);
855
        ref1 = referenceDao.findByUuid(uuidRef1);
856
        ref2 = referenceDao.findByUuid(uuidRef2);
857
        cdmGenericDao.merge(ref2, ref1, strategy);
858

    
859
        taxon = (Taxon)taxonDao.findByUuid(taxon.getUuid());
860
        textData = (TextData)taxon.getDescriptions().iterator().next().getElements().iterator().next();
861
        languageString = textData.getLanguageText(language);
862
        Assert.assertEquals("And <cdm:reference cdmId='"+uuidRef2+"' intextId='"+uuidIntextRefRef+"'>here</cdm:reference> is a citation",
863
                languageString.getText());
864
    }
865

    
866
    @Test
867
    public void testReallocateIntextReferenceForNameAndAnnotation() throws MergeException {
868
        UUID uuidPinusAlba = UUID.fromString("52743cec-b893-4e8b-b06c-91f9b9ba8fee");
869
        UUID uuidAbiesAlba = UUID.fromString("6ed56b43-7cca-4c3b-bb90-7576da81c072");
870

    
871
        // CREATE DATA
872
        TaxonName pinusAlba = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
873
        pinusAlba.setTitleCache("BotanicalName1", true);
874
        pinusAlba.setUuid(uuidPinusAlba);
875

    
876
        TaxonName abiesAlba = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
877
        abiesAlba.setTitleCache("Abies alba", true);
878
        abiesAlba.setUuid(uuidAbiesAlba);
879

    
880
        Taxon taxon = Taxon.NewInstance(null, null);
881

    
882
        Annotation annotation = Annotation.NewDefaultLanguageInstance("My annotation on Abies alba and its habit.");
883
        taxon.addAnnotation(annotation);
884
        IntextReference intextRefName = annotation.addIntextReference(abiesAlba, "My annotation on ", "Abies alba", " and its habit.");
885
        String uuidIntextRefName = intextRefName.getUuid().toString();
886
        Assert.assertEquals("My annotation on <cdm:name cdmId='"+uuidAbiesAlba+"' intextId='"+uuidIntextRefName+"'>Abies alba</cdm:name> and its habit.",
887
                annotation.getText());
888

    
889
        //SAVE AND COMMIT
890
        taxonDao.save(taxon);
891
        nameDao.save(abiesAlba);
892
        nameDao.save(pinusAlba);
893
        commitAndStartNewTransaction(null);
894

    
895
        //MERGE
896
        DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(TaxonName.class);
897
        abiesAlba = nameDao.findByUuid(uuidAbiesAlba);
898
        pinusAlba = nameDao.findByUuid(uuidPinusAlba);
899
        cdmGenericDao.merge(pinusAlba, abiesAlba, strategy);
900

    
901
        taxon = (Taxon)taxonDao.findByUuid(taxon.getUuid());
902
        annotation = taxon.getAnnotations().iterator().next();
903

    
904
        Assert.assertEquals("My annotation on <cdm:name cdmId='"+uuidPinusAlba+"' intextId='"+uuidIntextRefName+"'>Abies alba</cdm:name> and its habit.",
905
                annotation.getText());
906
    }
907

    
908
	@Test
909
	public void testReallocatePersonTeam() throws MergeException {
910

    
911
	    TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
912
		name1.setTitleCache("BotanicalName1", true);
913

    
914
		IBook book1 = ReferenceFactory.newBook();
915

    
916
		Team team1 = Team.NewInstance();
917
		Team team2 = Team.NewInstance();
918
		team1.setTitleCache("team1", true);
919
		team2.setTitleCache("team2", true);
920

    
921
		Person person1 = Person.NewTitledInstance("person1");
922
		Person person2 = Person.NewTitledInstance("person2");
923

    
924
		team1.setNomenclaturalTitleCache("T.1", true);
925
		String street1 = "Strasse1";
926
		person1.setContact(Contact.NewInstance(street1, "12345", "Berlin", Country.ARGENTINAARGENTINEREPUBLIC(),"pobox" , "Region", "a@b.de", "f12345", "+49-30-123456", URI.create("www.abc.de"), Point.NewInstance(2.4, 3.2, ReferenceSystem.WGS84(), 3)));
927
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
928
		String street3 = "Street3";
929
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
930
		String emailAddress1 = "Email1";
931
		team1.addEmailAddress(emailAddress1);
932

    
933
		//FIXME
934
//		team2.addTeamMember(person1);
935
		team2.addTeamMember(person2);
936
		String emailAddress2 = "Email2";
937
		team2.addEmailAddress(emailAddress2);
938

    
939
		Credit credit1 = Credit.NewInstance(team2, "credit1");
940
		book1.addCredit(credit1);
941

    
942
		agentDao.save(team1);
943
		agentDao.save(team2);
944
		agentDao.save(person1);
945
		agentDao.save(person2);
946

    
947
		cdmGenericDao.save((Reference)book1);
948

    
949
		//starting condition
950
		name1.setCombinationAuthorship(person1);
951
		Assert.assertEquals("Name1 should have person1 as combination author", person1, name1.getCombinationAuthorship());
952

    
953
		DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(TeamOrPersonBase.class);
954
//		strategy.setOnlyReallocateLinks(true);
955

    
956
		FieldUnit fieldUnit1 = FieldUnit.NewInstance();
957
		fieldUnit1.setPrimaryCollector(person1);
958
		cdmGenericDao.save(fieldUnit1);
959
		try {
960
			cdmGenericDao.merge(team2, person1, strategy);
961
			Assert.fail("We expect exception because fieldunit.primaryCollector is of type person");
962
		} catch (MergeException e) {
963
			if (! e.getMessage().contains("Object can not be merged into new object as it is referenced in a way that does not allow merging")){
964
				Assert.fail("The exception should be the one thrown by DeduplicationHelper.reallocateByHolder(...)");
965
			}
966
			fieldUnit1.setPrimaryCollector(null);  //clean up for next test
967
		} catch (Exception e) {
968
			Assert.fail("Unhandled exception during merge");
969
		}
970
		Assert.assertEquals("Name1 should still have person1 as combination author", person1, name1.getCombinationAuthorship());
971

    
972
		//test collections
973
		team1.addTeamMember(person1);
974
		try {
975
			cdmGenericDao.merge(team2, person1, strategy);
976
			Assert.fail("We expect exception because fieldunit.primaryCollector is of type person");
977
		} catch (MergeException e) {
978
			if (! e.getMessage().contains("Object can not be merged into new object as it is referenced in a way that does not allow merging")){
979
				Assert.fail("The exception should be the one thrown by DeduplicationHelper.reallocateByHolder(...)");
980
			}
981
			team1.removeTeamMember(person1); //clean up for next test
982
		} catch (Exception e) {
983
			Assert.fail("Unhandled exception during merge");
984
		}
985
		Assert.assertEquals("Name1 should still have person1 as combination author", person1, name1.getCombinationAuthorship());
986

    
987
		//test successful merge
988
		cdmGenericDao.save(name1);
989
		cdmGenericDao.merge(team2, person1, strategy);
990
		Assert.assertEquals("Name1 should have team2 as combination author now", team2, name1.getCombinationAuthorship());
991
	}
992

    
993
	private void testMergeExceptions(CdmBase name1, CdmBase name2, CdmBase taxon, ICdmBase zooName1) throws MergeException{
994
		//
995
		try {
996
			cdmGenericDao.merge(name1, null, null);
997
			Assert.fail("Merging of 2 objects one or both of them null must throw an exception");
998
		} catch (NullPointerException e) {
999
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
1000
		}
1001
		//
1002
		try {
1003
			cdmGenericDao.merge(null, name1, null);
1004
			Assert.fail("Merging of 2 objects one or both of them null must throw an exception");
1005
		} catch (NullPointerException e) {
1006
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
1007
		}
1008
		//exceptions to be thrown
1009
		try {
1010
			cdmGenericDao.merge(name1, taxon, null);
1011
			//this is not fully true anymore !! In certain cases merging of objects of different classes is allowed
1012
			Assert.fail("Merging of 2 objects of different types must throw an exception");
1013
		} catch (MergeException e) {
1014
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
1015
		}
1016
		//next exception
1017
		//for names this is not the case anymore
1018
//		try {
1019
//			cdmGenericDao.merge(name1, zooName1, null);
1020
//			Assert.fail("Merging of 2 objects of different types must throw an exception");
1021
//		} catch (MergeException e) {
1022
//			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
1023
//		}
1024
	}
1025

    
1026
	@Test
1027
	public void findMatching(){
1028
		IBook book1 = ReferenceFactory.newBook();
1029
		IBook book2 = ReferenceFactory.newBook();
1030
		IBook book3 = ReferenceFactory.newBook();
1031

    
1032
		String title1 = "title1";
1033
		String title2 = "title2";
1034
		book1.setTitle(title1);
1035
		book2.setTitle(title2);
1036
		book3.setTitle(title1);
1037

    
1038
		cdmGenericDao.saveOrUpdate((Reference)book1);
1039
		cdmGenericDao.saveOrUpdate((Reference)book2);
1040
		cdmGenericDao.saveOrUpdate((Reference)book3);
1041

    
1042
		IMatchStrategyEqual matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1043

    
1044
		try {
1045
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1046
			Assert.assertNotNull("Resultlist must not be null", matchResult);
1047
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1048
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
1049

    
1050
			book1.setDatePublished(VerbatimTimePeriod.NewVerbatimInstance(1999, 2002));
1051
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1052
			Assert.assertTrue("Resultlist must have no entries", matchResult.isEmpty());
1053

    
1054
			book3.setDatePublished(VerbatimTimePeriod.NewVerbatimInstance(1999));
1055
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1056
			Assert.assertTrue("Resultlist must have no entries", matchResult.isEmpty());
1057

    
1058
			book3.setDatePublished(VerbatimTimePeriod.NewVerbatimInstance(1999,2002));
1059
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1060
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1061
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
1062

    
1063
			//BookSection
1064
			IBookSection section1 = ReferenceFactory.newBookSection();
1065
			section1.setInBook(book1);
1066
			section1.setTitle("SecTitle");
1067
			section1.setPages("22-33");
1068
			IBookSection section2 = ReferenceFactory.newBookSection();
1069
			section2.setInBook(book2);
1070
			section2.setTitle("SecTitle");
1071
			section2.setPages("22-33");
1072
			IBookSection section3 = ReferenceFactory.newBookSection();
1073
			section3.setInBook(book1);
1074
			section3.setTitle("SecTitle");
1075
			section3.setPages("22-33");
1076
			cdmGenericDao.saveOrUpdate((Reference)section1);
1077
			cdmGenericDao.saveOrUpdate((Reference)section2);
1078
			cdmGenericDao.saveOrUpdate((Reference)section3);
1079

    
1080
			List<IBookSection> sectionResult = cdmGenericDao.findMatching(section3, null);
1081
			Assert.assertEquals("Resultlist must have 1 entries", 1, sectionResult.size());
1082
			Assert.assertSame("Resultlist entry must be section1", section1, sectionResult.get(0));
1083

    
1084
			section2.setInBook(book2 = (IBook)book1.clone());
1085
			cdmGenericDao.saveOrUpdate((Reference)book2);
1086
			cdmGenericDao.saveOrUpdate((Reference)book1);
1087
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1088
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1089
			sectionResult = cdmGenericDao.findMatching(section3, null);
1090
			Assert.assertEquals("Resultlist must have 1 entries", 2, sectionResult.size());
1091

    
1092
			Person person1 = Person.NewTitledInstance("person");
1093
			Person person2 = Person.NewTitledInstance("person");
1094
			Person person3 = Person.NewTitledInstance("person");
1095

    
1096
			person1.setPrefix("pre1");
1097
			person2.setPrefix("pre2");
1098
			person3.setPrefix("pre3");
1099

    
1100
//			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1101
//			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1102

    
1103
			book1.setAuthorship(person1);
1104
			book2.setAuthorship(person1);
1105
			book3.setAuthorship(person1);
1106

    
1107
			boolean m = matchStrategy.invoke(book1, book3).isSuccessful();
1108
			boolean m2 = matchStrategy.invoke(book2, book3).isSuccessful();
1109

    
1110
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1111
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1112

    
1113
			book2.setAuthorship(person2);
1114
			book3.setAuthorship(person3);
1115
			matchResult = cdmGenericDao.findMatching(book3, null);
1116
			Assert.assertEquals("Resultlist must have no entries", 0, matchResult.size());
1117

    
1118
			person3.setPrefix("pre1");
1119
			matchResult = cdmGenericDao.findMatching(book3, null);
1120
			Assert.assertEquals("Resultlist must have 1 entry", 1, matchResult.size());
1121
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
1122

    
1123
		} catch (MatchException e) {
1124
			Assert.fail("Find match must not throw Exception: " + e.getMessage());
1125
			e.printStackTrace();
1126
		}
1127
	}
1128

    
1129
	@Test
1130
	public void findMatchingCache(){
1131
		IBook book1 = ReferenceFactory.newBook();
1132
		Team team1 = Team.NewInstance();
1133
		Team team2 = Team.NewInstance();
1134
		team1.setTitleCache("Team1", true);
1135
		team2.setTitleCache("Team1", true);
1136

    
1137
		book1.setTitle("Title1");
1138
		book1.setEdition("Edition1");
1139
		book1.setAuthorship(team1);
1140

    
1141

    
1142
		IBook book2 = ((Reference)book1).clone();
1143
		IBook book3 = ((Reference)book1).clone();
1144

    
1145
//		Assert.assertTrue("Cloned book should match", matchStrategy.invoke(book1, bookClone));
1146
//		book1.setTitleCache("cache1");
1147
//		Assert.assertFalse("Cached book should not match", matchStrategy.invoke(book1, bookClone));
1148
//
1149
//		bookClone.setTitleCache("cache1");
1150
//		Assert.assertTrue("Cached book with same cache should match", matchStrategy.invoke(book1, bookClone));
1151
//
1152
//		bookClone.setTitleCache("cache2");
1153
//		Assert.assertFalse("Cached book with differings caches should not match", matchStrategy.invoke(book1, bookClone));
1154
//		bookClone.setTitleCache("cache1"); //restore
1155
//
1156
//		bookClone.setEdition(null);
1157
//		Assert.assertTrue("Cached book with a defined and a null edition should match", matchStrategy.invoke(book1, bookClone));
1158

    
1159
		cdmGenericDao.saveOrUpdate((Reference)book1);
1160
		cdmGenericDao.saveOrUpdate((Reference)book2);
1161
		cdmGenericDao.saveOrUpdate((Reference)book3);
1162
		cdmGenericDao.saveOrUpdate(team1);
1163
		cdmGenericDao.saveOrUpdate(team2);
1164

    
1165
		IMatchStrategyEqual matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1166

    
1167
		try {
1168
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1169
			Assert.assertNotNull("Resultlist must not be null", matchResult);
1170
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1171
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1172
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1173

    
1174
			book1.setTitleCache("cache1", true);
1175
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1176
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1177
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1178

    
1179
			book2.setTitleCache("cache2", false);
1180
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1181
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1182
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1183

    
1184
			book2.setEdition(null);
1185
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1186
			Assert.assertEquals("Resultlist must have 0 entries", 0, matchResult.size());
1187

    
1188
			book3.setTitleCache("cache1", true);
1189
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1190
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1191
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1192

    
1193
			IMatchStrategyEqual teamMatcher = DefaultMatchStrategy.NewInstance(Team.class);
1194
			boolean teamsMatch = teamMatcher.invoke(team1, team2).isSuccessful();
1195
			Assert.assertTrue("Team1 and team2 should match" ,teamsMatch);
1196

    
1197
			book3.setAuthorship(team2);
1198
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1199
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1200
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1201

    
1202
			book3.setAuthorship(null);
1203
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1204
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1205
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1206

    
1207
			book2.setTitleCache(book3.getTitleCache(), true);
1208
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1209
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1210
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1211
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1212

    
1213
			team2.setTitleCache("team2", true);
1214
			teamsMatch = teamMatcher.invoke(team1, team2).isSuccessful();
1215
			Assert.assertFalse("Team1 and team2 should not match" ,teamsMatch);
1216

    
1217
			book3.setAuthorship(team1);
1218
			book2.setAuthorship(team2);
1219
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1220
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1221
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1222

    
1223
		} catch (MatchException e) {
1224
			Assert.fail("Find match must not throw Exception: " + e.getMessage());
1225
			e.printStackTrace();
1226
		}
1227
	}
1228

    
1229
	//from original testing within class, can be removed if not needed anymore
1230
	private void test() {
1231
		SessionFactoryImpl factory = (SessionFactoryImpl)((CdmGenericDaoImpl)cdmGenericDao).getSession().getSessionFactory();
1232
		Type propType = factory.getReferencedPropertyType(TaxonName.class.getCanonicalName(), "titleCache");
1233
		Map<?,?> collMetadata = factory.getAllCollectionMetadata();
1234
		Object roles = factory.getCollectionRolesByEntityParticipant("eu.etaxonomy.cdm.model.name.BotanicalName");
1235
		CollectionPersister collPersister;
1236
		try {
1237
			collPersister = factory.getCollectionPersister(TaxonName.class.getCanonicalName()+".annotations");
1238
		} catch (MappingException e) {
1239
			// TODO Auto-generated catch block
1240
			e.printStackTrace();
1241
		}
1242
		Statistics statistics = factory.getStatistics();
1243
		Map<?,?> allClassMetadata = factory.getAllClassMetadata();
1244
		logger.debug("");
1245
	}
1246

    
1247
	@Test
1248
	public void testGetHqlResult() {
1249
		logger.warn("Not yet implemented");
1250
	}
1251

    
1252
    @Override
1253
    public void createTestDataSet() throws FileNotFoundException {}
1254
}
(4-4/7)