Project

General

Profile

Download (50.1 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

    
10
package eu.etaxonomy.cdm.persistence.dao.hibernate.common;
11

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

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

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

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

    
178
	@SpringBeanByType
179
	private ICdmGenericDao cdmGenericDao;
180

    
181
	@SpringBeanByType
182
	private ITaxonDao taxonDao;
183

    
184
	@SpringBeanByType
185
	private IOccurrenceDao occurrenceDao;
186

    
187
	@SpringBeanByType
188
	private ITaxonNameDao nameDao;
189

    
190
	@SpringBeanByType
191
	private IAgentDao agentDao;
192

    
193
    @SpringBeanByType
194
    private IReferenceDao referenceDao;
195

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

    
199
// ***************** TESTS **************************************************
200

    
201
	@Test
202
	@DataSets({
203
      @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
204
      @DataSet("/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml")})
205
	public void testDelete(){
206
		Reference ref1 = ReferenceFactory.newBook();
207
		Reference ref2 = ReferenceFactory.newBook();
208
		Annotation annotation = Annotation.NewInstance("Anno1", null);
209
		ref1.addAnnotation(annotation);
210
		UUID ref1Uuid = cdmGenericDao.saveOrUpdate(ref1);
211
		UUID ref2Uuid = cdmGenericDao.saveOrUpdate(ref2);
212
		List<Reference> list = cdmGenericDao.list(Reference.class, 10, 0, null, null);
213
//        System.out.println("ref1: " + ref1Uuid + " ref2: " + ref2Uuid);
214
        for (Reference ref: list){
215
            System.out.println("reference: " + ref.getUuid());
216
        }
217
		try {
218
			cdmGenericDao.merge(ref2, ref1, null);
219

    
220
		} catch (MergeException e) {
221
			Assert.fail();
222
		}
223
		commitAndStartNewTransaction(null);
224
		list = cdmGenericDao.list(Reference.class, 10, 0, null, null);
225
//		System.out.println("ref1: " + ref1Uuid + " ref2: " + ref2Uuid);
226
//        for (Reference ref: list){
227
//            System.out.println("reference: " + ref.getUuid());
228
//        }
229
		Assert.assertEquals(1, list.size());
230

    
231
	}
232

    
233

    
234
	/**
235
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getCdmBasesByFieldAndClass(java.lang.Class, java.lang.String, eu.etaxonomy.cdm.model.common.CdmBase)}.
236
	 */
237
	@Test
238
	public void testGetCdmBasesByFieldAndClass() {
239
		logger.warn("Not yet implemented");
240
	}
241

    
242
	/**
243
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getCdmBasesWithItemInCollection(java.lang.Class, java.lang.Class, java.lang.String, eu.etaxonomy.cdm.model.common.CdmBase)}.
244
	 */
245
	@Test
246
	public void testGetCdmBasesWithItemInCollection() {
247
		logger.warn("Not yet implemented");
248
	}
249

    
250
	/**
251
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getAllPersistedClasses(boolean)}.
252
	 */
253
	@Test
254
	public void testGetAllPersistedClasses() {
255
		Class<?>[] existingClassesArray = {
256
				Address.class,
257
				AgentBase.class,
258
				Institution.class,
259
				InstitutionalMembership.class,
260
				Person.class,
261
				Team.class,
262
				TeamOrPersonBase.class,
263
				Annotation.class,
264
				AnnotationType.class,
265
				Credit.class,
266
				DefinedTermBase.class,
267
				Extension.class,
268
				ExtensionType.class,
269
				GrantedAuthorityImpl.class,
270
				Group.class,
271
				IdentifiableSource.class,
272
				Identifier.class,
273
				IntextReference.class,
274
				Language.class,
275
				LanguageString.class,
276
				LSIDAuthority.class,
277
				Marker.class,
278
				MarkerType.class,
279
				OrderedTermBase.class,
280
				OrderedTermVocabulary.class,
281
				OriginalSourceBase.class,
282
				RelationshipTermBase.class,
283
				Representation.class,
284
				TermVocabulary.class,
285
				User.class,
286
				DefinedTerm.class,
287

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

    
374
		//for debugging only
375
		//		for (Class existingClass : existingClassesList){
376
		//			if (! foundClasses.contains(existingClass)){
377
		//				logger.warn("Class not found: " + existingClass.getCanonicalName());
378
		//			}
379
		//		}
380

    
381
		//All classes must be found
382
		Assert.assertTrue("all classes must be found by getAllCdmClasses() method", foundClasses.containsAll(existingClassesList));
383

    
384

    
385
		//No extra classes must be found
386
		for (Class<?> clazz : foundClasses){
387
			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)
388
				Assert.fail("Class " + clazz.getName() + " is not assignable from CdmBase");
389
			}
390
		}
391

    
392
		includeAbstractClasses = false;
393
		Set<Class<? extends CdmBase>> noAbstractClasses = cdmGenericDao.getAllPersistedClasses(includeAbstractClasses);
394
		Class<?> abstractClassToTest = TaxonBase.class;
395
		Assert.assertFalse("Abstract class " + abstractClassToTest.getName() + " may not be in set ", noAbstractClasses.contains(abstractClassToTest));
396
	}
397

    
398
	/**
399
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getReferencingObjects(CdmBase)}.
400
	 */
401
	@Test
402
	@DataSets({
403
	     @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
404
	     @DataSet("/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml")})
405
	public void testGetReferencingObjectsCdmBase() {
406
		IBotanicalName name = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
407
		name.setTitleCache("A name", true);
408
		Reference ref1 = ReferenceFactory.newArticle();
409
		Taxon taxon = Taxon.NewInstance(name, ref1);
410
		Person author = Person.NewInstance();
411
		author.setTitleCache("Author", true);
412
		ref1.addAnnotation(Annotation.NewInstance("A1", Language.DEFAULT()));
413
		ref1.setAuthorship(author);
414
		name.setBasionymAuthorship(author);
415

    
416
		name.setNomenclaturalReference(ref1);
417

    
418
		taxonDao.save(taxon);
419
//		UUID uuid = UUID.fromString("613980ac-9bd5-43b9-a374-d71e1794688f");
420
//		Reference ref1 = referenceService.findByUuid(uuid);
421
		commitAndStartNewTransaction(null);
422

    
423
		Set<CdmBase> referencedObjects = cdmGenericDao.getReferencingObjects(ref1);
424
		String debug = "############## RESULT ###################";
425
		for (CdmBase obj: referencedObjects){
426
			debug += "Object1: " + obj.getClass().getSimpleName() + " - " + obj;
427
		}
428
		//was 3 before bidirectionality was removed for supplemental data
429
		assertEquals(2, referencedObjects.size());
430
		debug += "############## ENDE ###################";
431

    
432
//		UUID uuidAuthor = UUID.fromString("4ce66544-a5a3-4601-ab0b-1f0a1338327b");
433
//		AgentBase author = agentService.findByUuid(uuidAuthor);
434

    
435
		referencedObjects = cdmGenericDao.getReferencingObjects(author);
436
		debug += "############## RESULT ###################";
437
		for (CdmBase obj: referencedObjects){
438
			debug += "Object2: " + obj.getClass().getSimpleName() + " - " + obj;
439
		}
440
		assertEquals(2, referencedObjects.size());
441
		debug += "############## ENDE ###################";
442
		logger.info(debug);
443
	}
444

    
445
	/**
446
	 * 2nd test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getReferencingObjects(CdmBase)}.
447
	 *
448
	 */
449
	@Test
450
	@DataSet
451
	public final void testGetReferencingObjects2() {
452
//		SpecimenDescription desc1 = SpecimenDescription.NewInstance();
453
//		desc1.setTitleCache("desc1");
454
//		SpecimenDescription desc2 = SpecimenDescription.NewInstance();
455
//		desc2.setTitleCache("desc2");
456
//
457
//		SpecimenOrObservationBase spec1 = Specimen.NewInstance();
458
//
459
//		desc1.addDescribedSpecimenOrObservation(spec1);
460
//		//Taxon taxon = Taxon.NewInstance(taxonName, sec)
461
//		spec1.addDescription(desc2);
462
//
463
//		occurrenceService.save(spec1);
464

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

    
468

    
469
		Set<CdmBase> referencingObjects = cdmGenericDao.getReferencingObjects(spec1);
470
//		System.out.println("############## RESULT ###################");
471
//		for (CdmBase obj: referencingObjects){
472
//			System.out.println("Object: " + obj.getClass().getSimpleName() + " - " + obj);
473
//		}
474
//		System.out.println("############## ENDE ###################");
475
		assertEquals("Number of referencing objects must be 2.", 2, referencingObjects.size());
476

    
477
	}
478

    
479
	/**
480
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
481
	 * @throws MergeException
482
	 */
483
	@Test
484
//	@Ignore
485
	public void testMergeCdmBaseReferenceAndIdentifiable() throws MergeException {
486

    
487
		TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
488
		name1.setTitleCache("BotanicalName1", true);
489

    
490
		TaxonName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
491
		name2.setTitleCache("BotanicalName2", true);
492

    
493
		TaxonName zooName1 = TaxonNameFactory.NewZoologicalInstance(Rank.SPECIES());
494
		name1.setTitleCache("ZoologicalName1", true);
495

    
496
		Reference article1 = ReferenceFactory.newArticle();
497
		Reference article2 = ReferenceFactory.newArticle();
498

    
499

    
500
		name1.setNomenclaturalReference(article1);
501
		name2.setNomenclaturalReference(article2);
502

    
503

    
504
		Taxon taxon1 = Taxon.NewInstance(name1, article1);
505
		Taxon taxon2 = Taxon.NewInstance(name2, article2);
506

    
507

    
508
//		Person author = Person.NewInstance();
509
//		author.setTitleCache("Author");
510
		Annotation annotation1 = Annotation.NewInstance("A1", Language.DEFAULT());
511
		Annotation annotation2 = Annotation.NewInstance("A2", Language.DEFAULT());
512

    
513
		article1.addAnnotation(annotation1);
514
		article2.addAnnotation(annotation2);
515

    
516
		Marker marker1 = Marker.NewInstance(MarkerType.COMPLETE(), false);
517
		Marker marker2 = Marker.NewInstance(MarkerType.IMPORTED(), false);
518

    
519
		article1.addMarker(marker1);
520
		article2.addMarker(marker2);
521

    
522
		Rights rights1 = Rights.NewInstance();
523
		Rights rights2 = Rights.NewInstance();
524

    
525
		article1.addRights(rights1);
526
		article2.addRights(rights2);
527

    
528
		Credit credit1 = Credit.NewInstance(Team.NewInstance(), "credit1");
529
		Credit credit2 = Credit.NewInstance(Team.NewInstance(), "credit2");
530

    
531
		article1.addCredit(credit1);
532
		article2.addCredit(credit2);
533

    
534
		Extension extension1 = Extension.NewInstance();
535
		Extension extension2 = Extension.NewInstance();
536

    
537
		article1.addExtension(extension1);
538
		article2.addExtension(extension2);
539

    
540
		IdentifiableSource source1 = IdentifiableSource.NewInstance(OriginalSourceType.Unknown);
541
		IdentifiableSource source2 = IdentifiableSource.NewInstance(OriginalSourceType.Unknown);
542

    
543
		article1.addSource(source1);
544
		article2.addSource(source2);
545

    
546
		Media media1 = Media.NewInstance();
547
		Media media2 = Media.NewInstance();
548

    
549
		article1.addMedia(media1);
550
		article2.addMedia(media2);
551

    
552
//		ref1.setAuthorship(author);
553
//		name1.setBasionymAuthorship(author);
554

    
555
		name1.setNomenclaturalReference(article1);
556

    
557
		nameDao.save(name1);
558
		nameDao.save(name2);
559
		nameDao.save(zooName1);
560

    
561
		TaxonDescription taxDesc = TaxonDescription.NewInstance(taxon1);
562
		taxDesc.setTitleCache("taxDesc", true);
563
		taxDesc.addSource(OriginalSourceType.Unknown, null, null, article2, null);
564

    
565
		taxonDao.save(taxon1);
566

    
567
		//unidircetional reference to the merged object should be redirected
568
		cdmGenericDao.merge(article1, article2, null);
569
		Assert.assertEquals("Name2 must have article 1 as new nomRef", article1 ,name2.getNomenclaturalReference());
570
		//TODO microCitations!! -> warning
571

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

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

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

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

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

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

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

    
593
		//Description sources
594
		Assert.assertEquals("Number of sources for taxon description must be 1", 1, taxDesc.getSources().size());
595
		Assert.assertEquals("Taxon description must have article1 as source", taxDesc.getSources().iterator().next().getCitation(),article1);
596

    
597
		//test exceptions
598

    
599
		testMergeExceptions(name1, name2, taxon1, zooName1);
600

    
601

    
602

    
603

    
604
		//FIXME TO BE IMPLEMENTED
605
		//current defalt implementation for rights, credits and media is ADD_CLONE and therefore the below tests don't work
606
		//TODO is this the wanted default behaviour?
607
//		Assert.assertTrue("Rights2 must be contained in the rights", article1.getRights().contains(rights2));
608
//		Assert.assertTrue("Credits2 must be contained in the credits", article1.getCredits().contains(credit2));
609
//		Assert.assertTrue("Media2 must be contained in the media", article1.getMedia().contains(media2));
610

    
611
	}
612

    
613
	/**
614
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
615
	 * @throws MergeException
616
	 */
617
	@Test
618
//	@Ignore
619
	public void testMergeTaxonNameAndTaxon() throws MergeException {
620
	    TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
621
		name1.setTitleCache("BotanicalName1", true);
622

    
623
		TaxonName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
624
		name2.setTitleCache("BotanicalName2", true);
625

    
626
		IBotanicalName name3 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
627
		name3.setTitleCache("BotanicalName3", true);
628

    
629
		Reference database = ReferenceFactory.newDatabase();
630

    
631
		Taxon taxon1 = Taxon.NewInstance(name1, database);
632
		Taxon taxon2 = Taxon.NewInstance(name2, database);
633
		Taxon taxon3 = Taxon.NewInstance(name3, database);
634

    
635
		taxonDao.save(taxon1);
636
		taxonDao.save(taxon2);
637
		taxonDao.save(taxon3);
638

    
639
		cdmGenericDao.merge(name1, name2, null);
640
		Assert.assertEquals("Name1 must have 2 taxa attached now.", 2 ,name1.getTaxonBases().size());
641
		Assert.assertEquals("Taxon2 must have name1 as new name.", name1 ,taxon2.getName());
642

    
643
//TODO
644
//		cdmGenericDao.merge(taxon1, taxon3, null);
645
//		Assert.assertEquals("Name1 must have 3 taxa attached now.", 3 ,name1.getTaxonBases().size());
646

    
647

    
648
	}
649

    
650
	/**
651
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
652
	 * @throws MergeException
653
	 */
654
	@Test
655
	public void testMergeAuthors() throws MergeException {
656

    
657
		IBotanicalName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
658
		name1.setTitleCache("BotanicalName1", true);
659

    
660
		IBotanicalName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
661
		name2.setTitleCache("BotanicalName2", true);
662

    
663
		IBook book1 = ReferenceFactory.newBook();
664
		IBook book2 = ReferenceFactory.newBook();
665

    
666
		Team team1 = Team.NewInstance();
667
		Team team2 = Team.NewInstance();
668
		Team team3 = Team.NewInstance();
669
		team1.setTitleCache("team1", true);
670
		team2.setTitleCache("team2", true);
671
		team3.setTitleCache("team3", true);
672

    
673
		Person person1 = Person.NewTitledInstance("person1");
674
		Person person2 = Person.NewTitledInstance("person2");
675
		Person person3 = Person.NewTitledInstance("person3");
676

    
677
		team1.setNomenclaturalTitle("T.1");
678
		String street1 = "Strasse1";
679
		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)));
680
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
681
		String street3 = "Street3";
682
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
683
		String emailAddress1 = "Email1";
684
		team1.addEmailAddress(emailAddress1);
685

    
686
		team2.addTeamMember(person1);
687
		team2.addTeamMember(person2);
688
		String emailAddress2 = "Email2";
689
		team2.addEmailAddress(emailAddress2);
690

    
691
		team3.addTeamMember(person3);
692
		team3.addEmailAddress("emailAddress3");
693

    
694
		book1.setAuthorship(team2);
695
		book2.setAuthorship(team3);
696

    
697
		Credit credit1 = Credit.NewInstance(team3, "credit1");
698
		book2.addCredit(credit1);
699

    
700
		agentDao.save(team1);
701
		agentDao.save(team2);
702
		agentDao.save(team3);
703
		cdmGenericDao.save((Reference)book1);
704
		cdmGenericDao.save((Reference)book2);
705

    
706
		cdmGenericDao.merge(team2, team3, null);
707

    
708
		Assert.assertSame("Author of book1 must be team2.", team2, book1.getAuthorship());
709
		Assert.assertSame("Author of book2 must be team2.", team2, book2.getAuthorship());
710
		Assert.assertSame("Agent of credit1 must be team2.", team2, credit1.getAgent());
711

    
712
		Assert.assertEquals("Team2 must have 3 persons as members.",3, team2.getTeamMembers().size());
713
		Assert.assertTrue("Team2 must have person3 as new member.", team2.getTeamMembers().contains(person3));
714
		Assert.assertSame("Team2 must have person3 as third member.",person3, team2.getTeamMembers().get(2));
715

    
716

    
717
		//Contact
718
		cdmGenericDao.merge(team2, team1, null);
719
		Contact team2Contact = team2.getContact();
720
		Assert.assertNotNull("team2Contact must not be null", team2Contact);
721
		Assert.assertNotNull("Addresses must not be null", team2Contact.getAddresses());
722
		Assert.assertEquals("Number of addresses must be 3", 3, team2Contact.getAddresses().size());
723
		Assert.assertEquals("Number of email addresses must be 4", 4, team2Contact.getEmailAddresses().size());
724

    
725
		boolean street1Exists = false;
726
		boolean street3Exists = false;
727
		boolean country1Exists = false;
728
		for  (Address address : team2Contact.getAddresses()){
729
			if (street1.equals(address.getStreet())){
730
				street1Exists = true;
731
			}
732
			if (street3.equals(address.getStreet())){
733
				street3Exists = true;
734
			}
735
			if (Country.ARGENTINAARGENTINEREPUBLIC() == address.getCountry()){
736
				country1Exists = true;
737
			}
738
		}
739
		Assert.assertTrue("Street1 must be one of the streets in team2's addresses", street1Exists);
740
		Assert.assertTrue("Street3 must be one of the streets in team2's addressesss", street3Exists);
741
		Assert.assertTrue("Argentina must be one of the countries in team2's addresses", country1Exists);
742

    
743
		//Person
744
		Institution institution1 = Institution.NewInstance();
745
		institution1.setTitleCache("inst1", true);
746
		Institution institution2 = Institution.NewInstance();
747
		institution2.setTitleCache("inst2", true);
748

    
749
		TimePeriod period1 = TimePeriod.NewInstance(2002, 2004);
750
		TimePeriod period2 = TimePeriod.NewInstance(2004, 2006);
751

    
752
		person1.addInstitutionalMembership(institution1, period1, "departement1", "role1");
753
		person2.addInstitutionalMembership(institution2, period2, "departement2", "role2");
754

    
755
		IMergeStrategy personMergeStrategy = DefaultMergeStrategy.NewInstance(Person.class);
756
		personMergeStrategy.invoke(person1, person2);
757

    
758
		Assert.assertEquals("Number of institutional memberships must be 2", 2, person1.getInstitutionalMemberships().size());
759
		for (InstitutionalMembership institutionalMembership : person1.getInstitutionalMemberships()){
760
			Assert.assertSame("Person of institutional memebership must be person1", person1, institutionalMembership.getPerson());
761
		}
762
	}
763

    
764
	/**
765
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
766
     *
767
     * Test for  http://dev.e-taxonomy.eu/trac/ticket/5652
768
     *
769
     * @throws MergeException
770
     */
771
    @Test
772
    public void testMergePersons() throws MergeException {
773
        Team team1 = Team.NewInstance();
774
        Team team2 = Team.NewInstance();
775
        Team team3 = Team.NewInstance();
776
        team1.setTitleCache("team1", true);
777
        team2.setTitleCache("team2", true);
778
        team3.setTitleCache("team3", true);
779

    
780
        Person person1a = Person.NewTitledInstance("person1a");
781
        Person person1b = Person.NewTitledInstance("person1b");
782
        Person person2 = Person.NewTitledInstance("person2");
783
        Person person3 = Person.NewTitledInstance("person3");
784

    
785
        team1.addTeamMember(person1a);
786
        team1.addTeamMember(person2);
787

    
788

    
789
        team2.addTeamMember(person2);
790
        team2.addTeamMember(person1a);
791
        team2.addTeamMember(person3);
792

    
793
        team3.addTeamMember(person3);
794

    
795
        agentDao.save(team1);
796
        agentDao.save(team2);
797
        agentDao.save(team3);
798
        agentDao.save(person1b);
799
        commitAndStartNewTransaction(null);
800

    
801
        IMergeStrategy personMergeStrategy = DefaultMergeStrategy.NewInstance(Person.class);
802
        cdmGenericDao.merge(person1b, person1a, personMergeStrategy);
803

    
804
        team1 = (Team)agentDao.load(team1.getUuid());
805
        team2 = (Team)agentDao.load(team2.getUuid());
806

    
807
        //order should not change and 1a should be replaced by 1b
808
        Assert.assertEquals("person1b", team1.getTeamMembers().get(0).getTitleCache());
809
        Assert.assertEquals("person2", team1.getTeamMembers().get(1).getTitleCache());
810

    
811
        Assert.assertEquals("person2", team2.getTeamMembers().get(0).getTitleCache());
812
        Assert.assertEquals("person1b", team2.getTeamMembers().get(1).getTitleCache());
813
        Assert.assertEquals("person3", team2.getTeamMembers().get(2).getTitleCache());
814

    
815
    }
816

    
817
    @Test
818
    public void testReallocateIntextReferenceForReferenceAndLanguageString() throws MergeException {
819
        UUID uuidRef1 = UUID.fromString("41743cec-b893-4e8b-b06c-91f9b9ba8fee");
820
        UUID uuidRef2 = UUID.fromString("8fd56b43-7cca-4c3b-bb90-7576da81c072");
821

    
822
        // CREATE DATA
823

    
824
        Reference ref1 = ReferenceFactory.newGeneric();
825
        ref1.setTitle("Reference1");
826
        ref1.setUuid(uuidRef1);
827
        Reference ref2 = ReferenceFactory.newGeneric();
828
        ref2.setTitle("Reference2");
829
        ref2.setUuid(uuidRef2);
830
        referenceDao.save(ref2);
831
        Taxon taxon = Taxon.NewInstance(null, null);
832

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

    
843
        //SAVE AND COMMIT
844
        taxonDao.save(taxon);
845
        commitAndStartNewTransaction(null);
846

    
847
        //MERGE
848
        DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(Reference.class);
849
        ref1 = referenceDao.findByUuid(uuidRef1);
850
        ref2 = referenceDao.findByUuid(uuidRef2);
851
        cdmGenericDao.merge(ref2, ref1, strategy);
852

    
853
        taxon = (Taxon)taxonDao.findByUuid(taxon.getUuid());
854
        textData = (TextData)taxon.getDescriptions().iterator().next().getElements().iterator().next();
855
        languageString = textData.getLanguageText(language);
856
        Assert.assertEquals("And <cdm:reference cdmId='"+uuidRef2+"' intextId='"+uuidIntextRefRef+"'>here</cdm:reference> is a citation",
857
                languageString.getText());
858

    
859
    }
860

    
861
    @Test
862
    public void testReallocateIntextReferenceForNameAndAnnotation() throws MergeException {
863
        UUID uuidPinusAlba = UUID.fromString("52743cec-b893-4e8b-b06c-91f9b9ba8fee");
864
        UUID uuidAbiesAlba = UUID.fromString("6ed56b43-7cca-4c3b-bb90-7576da81c072");
865

    
866
        // CREATE DATA
867
        TaxonName pinusAlba = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
868
        pinusAlba.setTitleCache("BotanicalName1", true);
869
        pinusAlba.setUuid(uuidPinusAlba);
870

    
871
        TaxonName abiesAlba = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
872
        abiesAlba.setTitleCache("Abies alba", true);
873
        abiesAlba.setUuid(uuidAbiesAlba);
874

    
875
        Taxon taxon = Taxon.NewInstance(null, null);
876

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

    
884
        //SAVE AND COMMIT
885
        taxonDao.save(taxon);
886
        nameDao.save(abiesAlba);
887
        nameDao.save(pinusAlba);
888
        commitAndStartNewTransaction(null);
889

    
890
        //MERGE
891
        DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(TaxonName.class);
892
        abiesAlba = nameDao.findByUuid(uuidAbiesAlba);
893
        pinusAlba = nameDao.findByUuid(uuidPinusAlba);
894
        cdmGenericDao.merge(pinusAlba, abiesAlba, strategy);
895

    
896
        taxon = (Taxon)taxonDao.findByUuid(taxon.getUuid());
897
        annotation = taxon.getAnnotations().iterator().next();
898

    
899
        Assert.assertEquals("My annotation on <cdm:name cdmId='"+uuidPinusAlba+"' intextId='"+uuidIntextRefName+"'>Abies alba</cdm:name> and its habit.",
900
                annotation.getText());
901
    }
902

    
903
	/**
904
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
905
	 * @throws MergeException
906
	 */
907
	@Test
908
	public void testReallocatePersonTeam() throws MergeException {
909

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

    
913
		IBook book1 = ReferenceFactory.newBook();
914

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

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

    
923
		team1.setNomenclaturalTitle("T.1");
924
		String street1 = "Strasse1";
925
		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)));
926
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
927
		String street3 = "Street3";
928
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
929
		String emailAddress1 = "Email1";
930
		team1.addEmailAddress(emailAddress1);
931

    
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

    
994

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

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

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

    
1040
		cdmGenericDao.saveOrUpdate((Reference)book1);
1041
		cdmGenericDao.saveOrUpdate((Reference)book2);
1042
		cdmGenericDao.saveOrUpdate((Reference)book3);
1043

    
1044
		IMatchStrategyEqual matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1045

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

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

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

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

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

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

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

    
1094

    
1095
			Person person1 = Person.NewTitledInstance("person");
1096
			Person person2 = Person.NewTitledInstance("person");
1097
			Person person3 = Person.NewTitledInstance("person");
1098

    
1099
			person1.setPrefix("pre1");
1100
			person2.setPrefix("pre2");
1101
			person3.setPrefix("pre3");
1102

    
1103
//			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1104
//			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1105

    
1106
			book1.setAuthorship(person1);
1107
			book2.setAuthorship(person1);
1108
			book3.setAuthorship(person1);
1109

    
1110
			boolean m = matchStrategy.invoke(book1, book3).isSuccessful();
1111
			boolean m2 = matchStrategy.invoke(book2, book3).isSuccessful();
1112

    
1113
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1114
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1115

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

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

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

    
1131
	}
1132

    
1133

    
1134
	@Test
1135
	public void findMatchingCache(){
1136
		IBook book1 = ReferenceFactory.newBook();
1137
		Team team1 = Team.NewInstance();
1138
		Team team2 = Team.NewInstance();
1139
		team1.setTitleCache("Team1", true);
1140
		team2.setTitleCache("Team1", true);
1141

    
1142
		book1.setTitle("Title1");
1143
		book1.setEdition("Edition1");
1144
		book1.setAuthorship(team1);
1145

    
1146

    
1147
		IBook book2 = (IBook) ((Reference)book1).clone();
1148
		IBook book3 = (IBook) ((Reference)book1).clone();
1149

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

    
1164
		cdmGenericDao.saveOrUpdate((Reference)book1);
1165
		cdmGenericDao.saveOrUpdate((Reference)book2);
1166
		cdmGenericDao.saveOrUpdate((Reference)book3);
1167
		cdmGenericDao.saveOrUpdate(team1);
1168
		cdmGenericDao.saveOrUpdate(team2);
1169

    
1170

    
1171
		IMatchStrategyEqual matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1172

    
1173
		try {
1174
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1175
			Assert.assertNotNull("Resultlist must not be null", matchResult);
1176
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1177
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1178
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1179

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

    
1185
			book2.setTitleCache("cache2", false);
1186
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1187
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1188
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1189

    
1190
			book2.setEdition(null);
1191
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1192
			Assert.assertEquals("Resultlist must have 0 entries", 0, matchResult.size());
1193

    
1194
			book3.setTitleCache("cache1", true);
1195
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1196
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1197
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1198

    
1199
			IMatchStrategyEqual teamMatcher = DefaultMatchStrategy.NewInstance(Team.class);
1200
			boolean teamsMatch = teamMatcher.invoke(team1, team2).isSuccessful();
1201
			Assert.assertTrue("Team1 and team2 should match" ,teamsMatch);
1202

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

    
1208
			book3.setAuthorship(null);
1209
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1210
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1211
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1212

    
1213
			book2.setTitleCache(book3.getTitleCache(), true);
1214
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1215
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1216
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1217
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1218

    
1219
			team2.setTitleCache("team2", true);
1220
			teamsMatch = teamMatcher.invoke(team1, team2).isSuccessful();
1221
			Assert.assertFalse("Team1 and team2 should not match" ,teamsMatch);
1222

    
1223
			book3.setAuthorship(team1);
1224
			book2.setAuthorship(team2);
1225
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1226
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1227
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1228

    
1229

    
1230
		} catch (MatchException e) {
1231
			Assert.fail("Find match must not throw Exception: " + e.getMessage());
1232
			e.printStackTrace();
1233
		}
1234
	}
1235

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

    
1253
	}
1254

    
1255
	/**
1256
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getHqlResult(java.lang.String)}.
1257
	 */
1258
	@Test
1259
	public void testGetHqlResult() {
1260
		logger.warn("Not yet implemented");
1261
	}
1262

    
1263
    @Override
1264
    public void createTestDataSet() throws FileNotFoundException {}
1265
}
(4-4/11)