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.DefinedTerm;
49
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
50
import eu.etaxonomy.cdm.model.common.Extension;
51
import eu.etaxonomy.cdm.model.common.ExtensionType;
52
import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
53
import eu.etaxonomy.cdm.model.common.Group;
54
import eu.etaxonomy.cdm.model.common.ICdmBase;
55
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
56
import eu.etaxonomy.cdm.model.common.Identifier;
57
import eu.etaxonomy.cdm.model.common.IntextReference;
58
import eu.etaxonomy.cdm.model.common.LSIDAuthority;
59
import eu.etaxonomy.cdm.model.common.Language;
60
import eu.etaxonomy.cdm.model.common.LanguageString;
61
import eu.etaxonomy.cdm.model.common.Marker;
62
import eu.etaxonomy.cdm.model.common.MarkerType;
63
import eu.etaxonomy.cdm.model.common.OrderedTermBase;
64
import eu.etaxonomy.cdm.model.common.OrderedTermVocabulary;
65
import eu.etaxonomy.cdm.model.common.OriginalSourceBase;
66
import eu.etaxonomy.cdm.model.common.OriginalSourceType;
67
import eu.etaxonomy.cdm.model.common.RelationshipTermBase;
68
import eu.etaxonomy.cdm.model.common.Representation;
69
import eu.etaxonomy.cdm.model.common.TermVocabulary;
70
import eu.etaxonomy.cdm.model.common.TimePeriod;
71
import eu.etaxonomy.cdm.model.common.User;
72
import eu.etaxonomy.cdm.model.description.CategoricalData;
73
import eu.etaxonomy.cdm.model.description.CommonTaxonName;
74
import eu.etaxonomy.cdm.model.description.DescriptionBase;
75
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
76
import eu.etaxonomy.cdm.model.description.Distribution;
77
import eu.etaxonomy.cdm.model.description.Feature;
78
import eu.etaxonomy.cdm.model.description.FeatureNode;
79
import eu.etaxonomy.cdm.model.description.FeatureTree;
80
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
81
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
82
import eu.etaxonomy.cdm.model.description.MediaKey;
83
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
84
import eu.etaxonomy.cdm.model.description.QuantitativeData;
85
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
86
import eu.etaxonomy.cdm.model.description.State;
87
import eu.etaxonomy.cdm.model.description.StateData;
88
import eu.etaxonomy.cdm.model.description.StatisticalMeasure;
89
import eu.etaxonomy.cdm.model.description.StatisticalMeasurementValue;
90
import eu.etaxonomy.cdm.model.description.TaxonDescription;
91
import eu.etaxonomy.cdm.model.description.TaxonInteraction;
92
import eu.etaxonomy.cdm.model.description.TaxonNameDescription;
93
import eu.etaxonomy.cdm.model.description.TextData;
94
import eu.etaxonomy.cdm.model.description.TextFormat;
95
import eu.etaxonomy.cdm.model.location.Country;
96
import eu.etaxonomy.cdm.model.location.NamedArea;
97
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
98
import eu.etaxonomy.cdm.model.location.NamedAreaType;
99
import eu.etaxonomy.cdm.model.location.Point;
100
import eu.etaxonomy.cdm.model.location.ReferenceSystem;
101
import eu.etaxonomy.cdm.model.media.AudioFile;
102
import eu.etaxonomy.cdm.model.media.ImageFile;
103
import eu.etaxonomy.cdm.model.media.Media;
104
import eu.etaxonomy.cdm.model.media.MediaRepresentation;
105
import eu.etaxonomy.cdm.model.media.MediaRepresentationPart;
106
import eu.etaxonomy.cdm.model.media.MovieFile;
107
import eu.etaxonomy.cdm.model.media.Rights;
108
import eu.etaxonomy.cdm.model.media.RightsType;
109
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
110
import eu.etaxonomy.cdm.model.molecular.Amplification;
111
import eu.etaxonomy.cdm.model.molecular.DnaSample;
112
import eu.etaxonomy.cdm.model.molecular.PhylogeneticTree;
113
import eu.etaxonomy.cdm.model.molecular.Primer;
114
import eu.etaxonomy.cdm.model.molecular.Sequence;
115
import eu.etaxonomy.cdm.model.molecular.SingleRead;
116
import eu.etaxonomy.cdm.model.molecular.SingleReadAlignment;
117
import eu.etaxonomy.cdm.model.name.HomotypicalGroup;
118
import eu.etaxonomy.cdm.model.name.HybridRelationship;
119
import eu.etaxonomy.cdm.model.name.HybridRelationshipType;
120
import eu.etaxonomy.cdm.model.name.IBotanicalName;
121
import eu.etaxonomy.cdm.model.name.NameRelationship;
122
import eu.etaxonomy.cdm.model.name.NameRelationshipType;
123
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
124
import eu.etaxonomy.cdm.model.name.NameTypeDesignationStatus;
125
import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
126
import eu.etaxonomy.cdm.model.name.NomenclaturalStatusType;
127
import eu.etaxonomy.cdm.model.name.Rank;
128
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
129
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
130
import eu.etaxonomy.cdm.model.name.TaxonName;
131
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
132
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
133
import eu.etaxonomy.cdm.model.occurrence.Collection;
134
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
135
import eu.etaxonomy.cdm.model.occurrence.DerivationEventType;
136
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
137
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
138
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
139
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
140
import eu.etaxonomy.cdm.model.occurrence.PreservationMethod;
141
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
142
import eu.etaxonomy.cdm.model.reference.IBook;
143
import eu.etaxonomy.cdm.model.reference.IBookSection;
144
import eu.etaxonomy.cdm.model.reference.Reference;
145
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
146
import eu.etaxonomy.cdm.model.taxon.Classification;
147
import eu.etaxonomy.cdm.model.taxon.Synonym;
148
import eu.etaxonomy.cdm.model.taxon.SynonymType;
149
import eu.etaxonomy.cdm.model.taxon.Taxon;
150
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
151
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
152
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
153
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
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.strategy.match.DefaultMatchStrategy;
162
import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
163
import eu.etaxonomy.cdm.strategy.match.MatchException;
164
import eu.etaxonomy.cdm.strategy.merge.DefaultMergeStrategy;
165
import eu.etaxonomy.cdm.strategy.merge.IMergeStrategy;
166
import eu.etaxonomy.cdm.strategy.merge.MergeException;
167
import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
168
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
169

    
170
/**
171
 * @author a.mueller
172
 * @created 27.07.2009
173
 */
174
public class CdmGenericDaoImplTest extends CdmTransactionalIntegrationTest {
175
	private static final Logger logger = Logger.getLogger(CdmGenericDaoImplTest.class);
176

    
177
	@SpringBeanByType
178
	private ICdmGenericDao cdmGenericDao;
179

    
180
	@SpringBeanByType
181
	private ITaxonDao taxonDao;
182

    
183
	@SpringBeanByType
184
	private IOccurrenceDao occurrenceDao;
185

    
186
	@SpringBeanByType
187
	private ITaxonNameDao nameDao;
188

    
189
	@SpringBeanByType
190
	private IAgentDao agentDao;
191

    
192
    @SpringBeanByType
193
    private IReferenceDao referenceDao;
194

    
195
	/**
196
	 * @throws java.lang.Exception
197
	 */
198
	@Before
199
	public void setUp() throws Exception {}
200

    
201
// ***************** TESTS **************************************************
202

    
203
	@Test
204
	@DataSets({
205
     @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
206
     @DataSet("/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml")})
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
		UUID ref1Uuid = cdmGenericDao.saveOrUpdate(ref1);
213
		UUID ref2Uuid = cdmGenericDao.saveOrUpdate(ref2);
214
		List<Reference> list = cdmGenericDao.list(Reference.class, 10, 0, null, null);
215
        System.out.println("ref1: " + ref1Uuid + " ref2: " + ref2Uuid);
216
        for (Reference ref: list){
217
            System.out.println("reference: " + ref.getUuid());
218
        }
219
		try {
220
			cdmGenericDao.merge(ref2, ref1, null);
221

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

    
233
	}
234

    
235

    
236
	/**
237
	 * 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)}.
238
	 */
239
	@Test
240
	public void testGetCdmBasesByFieldAndClass() {
241
		logger.warn("Not yet implemented");
242
	}
243

    
244
	/**
245
	 * 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)}.
246
	 */
247
	@Test
248
	public void testGetCdmBasesWithItemInCollection() {
249
		logger.warn("Not yet implemented");
250
	}
251

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

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

    
382
		//for debugging only
383
		//		for (Class existingClass : existingClassesList){
384
		//			if (! foundClasses.contains(existingClass)){
385
		//				logger.warn("Class not found: " + existingClass.getCanonicalName());
386
		//			}
387
		//		}
388

    
389
		//All classes must be found
390
		Assert.assertTrue("all classes must be found by getAllCdmClasses() method", foundClasses.containsAll(existingClassesList));
391

    
392

    
393
		//No extra classes must be found
394
		for (Class<?> clazz : foundClasses){
395
			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)
396
				Assert.fail("Class " + clazz.getName() + " is not assignable from CdmBase");
397
			}
398
		}
399

    
400
		includeAbstractClasses = false;
401
		Set<Class<? extends CdmBase>> noAbstractClasses = cdmGenericDao.getAllPersistedClasses(includeAbstractClasses);
402
		Class<?> abstractClassToTest = TaxonBase.class;
403
		Assert.assertFalse("Abstract class " + abstractClassToTest.getName() + " may not be in set ", noAbstractClasses.contains(abstractClassToTest));
404
	}
405

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

    
424
		name.setNomenclaturalReference(ref1);
425

    
426
		taxonDao.save(taxon);
427
//		UUID uuid = UUID.fromString("613980ac-9bd5-43b9-a374-d71e1794688f");
428
//		Reference ref1 = referenceService.findByUuid(uuid);
429
		commitAndStartNewTransaction(null);
430

    
431
		Set<CdmBase> referencedObjects = cdmGenericDao.getReferencingObjects(ref1);
432
		String debug = "############## RESULT ###################";
433
		for (CdmBase obj: referencedObjects){
434
			debug += "Object1: " + obj.getClass().getSimpleName() + " - " + obj;
435
		}
436
		//was 3 before bidirectionality was removed for supplemental data
437
		assertEquals(2, referencedObjects.size());
438
		debug += "############## ENDE ###################";
439

    
440
//		UUID uuidAuthor = UUID.fromString("4ce66544-a5a3-4601-ab0b-1f0a1338327b");
441
//		AgentBase author = agentService.findByUuid(uuidAuthor);
442

    
443
		referencedObjects = cdmGenericDao.getReferencingObjects(author);
444
		debug += "############## RESULT ###################";
445
		for (CdmBase obj: referencedObjects){
446
			debug += "Object2: " + obj.getClass().getSimpleName() + " - " + obj;
447
		}
448
		assertEquals(2, referencedObjects.size());
449
		debug += "############## ENDE ###################";
450
		logger.info(debug);
451
	}
452

    
453
	/**
454
	 * 2nd test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getReferencingObjects(CdmBase)}.
455
	 *
456
	 */
457
	@Test
458
	@DataSet
459
	public final void testGetReferencingObjects2() {
460
//		SpecimenDescription desc1 = SpecimenDescription.NewInstance();
461
//		desc1.setTitleCache("desc1");
462
//		SpecimenDescription desc2 = SpecimenDescription.NewInstance();
463
//		desc2.setTitleCache("desc2");
464
//
465
//		SpecimenOrObservationBase spec1 = Specimen.NewInstance();
466
//
467
//		desc1.addDescribedSpecimenOrObservation(spec1);
468
//		//Taxon taxon = Taxon.NewInstance(taxonName, sec)
469
//		spec1.addDescription(desc2);
470
//
471
//		occurrenceService.save(spec1);
472

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

    
476

    
477
		Set<CdmBase> referencingObjects = cdmGenericDao.getReferencingObjects(spec1);
478
//		System.out.println("############## RESULT ###################");
479
//		for (CdmBase obj: referencingObjects){
480
//			System.out.println("Object: " + obj.getClass().getSimpleName() + " - " + obj);
481
//		}
482
//		System.out.println("############## ENDE ###################");
483
		assertEquals("Number of referencing objects must be 2.", 2, referencingObjects.size());
484

    
485
	}
486

    
487
	/**
488
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
489
	 * @throws MergeException
490
	 */
491
	@Test
492
//	@Ignore
493
	public void testMergeCdmBaseReferenceAndIdentifiable() throws MergeException {
494

    
495
		TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
496
		name1.setTitleCache("BotanicalName1", true);
497

    
498
		TaxonName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
499
		name2.setTitleCache("BotanicalName2", true);
500

    
501
		TaxonName zooName1 = TaxonNameFactory.NewZoologicalInstance(Rank.SPECIES());
502
		name1.setTitleCache("ZoologicalName1", true);
503

    
504
		Reference article1 = ReferenceFactory.newArticle();
505
		Reference article2 = ReferenceFactory.newArticle();
506

    
507

    
508
		name1.setNomenclaturalReference(article1);
509
		name2.setNomenclaturalReference(article2);
510

    
511

    
512
		Taxon taxon1 = Taxon.NewInstance(name1, article1);
513
		Taxon taxon2 = Taxon.NewInstance(name2, article2);
514

    
515

    
516
//		Person author = Person.NewInstance();
517
//		author.setTitleCache("Author");
518
		Annotation annotation1 = Annotation.NewInstance("A1", Language.DEFAULT());
519
		Annotation annotation2 = Annotation.NewInstance("A2", Language.DEFAULT());
520

    
521
		article1.addAnnotation(annotation1);
522
		article2.addAnnotation(annotation2);
523

    
524
		Marker marker1 = Marker.NewInstance(MarkerType.COMPLETE(), false);
525
		Marker marker2 = Marker.NewInstance(MarkerType.IMPORTED(), false);
526

    
527
		article1.addMarker(marker1);
528
		article2.addMarker(marker2);
529

    
530
		Rights rights1 = Rights.NewInstance();
531
		Rights rights2 = Rights.NewInstance();
532

    
533
		article1.addRights(rights1);
534
		article2.addRights(rights2);
535

    
536
		Credit credit1 = Credit.NewInstance(Team.NewInstance(), "credit1");
537
		Credit credit2 = Credit.NewInstance(Team.NewInstance(), "credit2");
538

    
539
		article1.addCredit(credit1);
540
		article2.addCredit(credit2);
541

    
542
		Extension extension1 = Extension.NewInstance();
543
		Extension extension2 = Extension.NewInstance();
544

    
545
		article1.addExtension(extension1);
546
		article2.addExtension(extension2);
547

    
548
		IdentifiableSource source1 = IdentifiableSource.NewInstance(OriginalSourceType.Unknown);
549
		IdentifiableSource source2 = IdentifiableSource.NewInstance(OriginalSourceType.Unknown);
550

    
551
		article1.addSource(source1);
552
		article2.addSource(source2);
553

    
554
		Media media1 = Media.NewInstance();
555
		Media media2 = Media.NewInstance();
556

    
557
		article1.addMedia(media1);
558
		article2.addMedia(media2);
559

    
560
//		ref1.setAuthorship(author);
561
//		name1.setBasionymAuthorship(author);
562

    
563
		name1.setNomenclaturalReference(article1);
564

    
565
		nameDao.save(name1);
566
		nameDao.save(name2);
567
		nameDao.save(zooName1);
568

    
569
		TaxonDescription taxDesc = TaxonDescription.NewInstance(taxon1);
570
		taxDesc.setTitleCache("taxDesc", true);
571
		taxDesc.addSource(OriginalSourceType.Unknown, null, null, article2, null);
572

    
573
		taxonDao.save(taxon1);
574

    
575
		//unidircetional reference to the merged object should be redirected
576
		cdmGenericDao.merge(article1, article2, null);
577
		Assert.assertEquals("Name2 must have article 1 as new nomRef", article1 ,name2.getNomenclaturalReference());
578
		//TODO microCitations!! -> warning
579

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

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

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

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

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

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

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

    
601
		//Description sources
602
		Assert.assertEquals("Number of sources for taxon description must be 1", 1, taxDesc.getSources().size());
603
		Assert.assertEquals("Taxon description must have article1 as source", taxDesc.getSources().iterator().next().getCitation(),article1);
604

    
605
		//test exceptions
606

    
607
		testMergeExceptions(name1, name2, taxon1, zooName1);
608

    
609

    
610

    
611

    
612
		//FIXME TO BE IMPLEMENTED
613
		//current defalt implementation for rights, credits and media is ADD_CLONE and therefore the below tests don't work
614
		//TODO is this the wanted default behaviour?
615
//		Assert.assertTrue("Rights2 must be contained in the rights", article1.getRights().contains(rights2));
616
//		Assert.assertTrue("Credits2 must be contained in the credits", article1.getCredits().contains(credit2));
617
//		Assert.assertTrue("Media2 must be contained in the media", article1.getMedia().contains(media2));
618

    
619
	}
620

    
621
	/**
622
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
623
	 * @throws MergeException
624
	 */
625
	@Test
626
//	@Ignore
627
	public void testMergeTaxonNameAndTaxon() throws MergeException {
628
	    TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
629
		name1.setTitleCache("BotanicalName1", true);
630

    
631
		TaxonName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
632
		name2.setTitleCache("BotanicalName2", true);
633

    
634
		IBotanicalName name3 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
635
		name3.setTitleCache("BotanicalName3", true);
636

    
637
		Reference database = ReferenceFactory.newDatabase();
638

    
639
		Taxon taxon1 = Taxon.NewInstance(name1, database);
640
		Taxon taxon2 = Taxon.NewInstance(name2, database);
641
		Taxon taxon3 = Taxon.NewInstance(name3, database);
642

    
643
		taxonDao.save(taxon1);
644
		taxonDao.save(taxon2);
645
		taxonDao.save(taxon3);
646

    
647
		cdmGenericDao.merge(name1, name2, null);
648
		Assert.assertEquals("Name1 must have 2 taxa attached now.", 2 ,name1.getTaxonBases().size());
649
		Assert.assertEquals("Taxon2 must have name1 as new name.", name1 ,taxon2.getName());
650

    
651
//TODO
652
//		cdmGenericDao.merge(taxon1, taxon3, null);
653
//		Assert.assertEquals("Name1 must have 3 taxa attached now.", 3 ,name1.getTaxonBases().size());
654

    
655

    
656
	}
657

    
658
	/**
659
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
660
	 * @throws MergeException
661
	 */
662
	@Test
663
	public void testMergeAuthors() throws MergeException {
664

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

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

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

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

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

    
685
		team1.setNomenclaturalTitle("T.1");
686
		String street1 = "Strasse1";
687
		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)));
688
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
689
		String street3 = "Street3";
690
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
691
		String emailAddress1 = "Email1";
692
		team1.addEmailAddress(emailAddress1);
693

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

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

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

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

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

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

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

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

    
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  http://dev.e-taxonomy.eu/trac/ticket/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

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

    
801
        team3.addTeamMember(person3);
802

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

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

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

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

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

    
823
    }
824

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

    
830
        // CREATE DATA
831

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

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

    
851
        //SAVE AND COMMIT
852
        taxonDao.save(taxon);
853
        commitAndStartNewTransaction(null);
854

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

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

    
867
    }
868

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

    
874
        // CREATE DATA
875
        TaxonName pinusAlba = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
876
        pinusAlba.setTitleCache("BotanicalName1", true);
877
        pinusAlba.setUuid(uuidPinusAlba);
878

    
879
        TaxonName abiesAlba = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
880
        abiesAlba.setTitleCache("Abies alba", true);
881
        abiesAlba.setUuid(uuidAbiesAlba);
882

    
883
        Taxon taxon = Taxon.NewInstance(null, null);
884

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

    
892
        //SAVE AND COMMIT
893
        taxonDao.save(taxon);
894
        nameDao.save(abiesAlba);
895
        nameDao.save(pinusAlba);
896
        commitAndStartNewTransaction(null);
897

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

    
904
        taxon = (Taxon)taxonDao.findByUuid(taxon.getUuid());
905
        annotation = taxon.getAnnotations().iterator().next();
906

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

    
911
	/**
912
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
913
	 * @throws MergeException
914
	 */
915
	@Test
916
	public void testReallocatePersonTeam() throws MergeException {
917

    
918
	    TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
919
		name1.setTitleCache("BotanicalName1", true);
920

    
921
		IBook book1 = ReferenceFactory.newBook();
922

    
923
		Team team1 = Team.NewInstance();
924
		Team team2 = Team.NewInstance();
925
		team1.setTitleCache("team1", true);
926
		team2.setTitleCache("team2", true);
927

    
928
		Person person1 = Person.NewTitledInstance("person1");
929
		Person person2 = Person.NewTitledInstance("person2");
930

    
931
		team1.setNomenclaturalTitle("T.1");
932
		String street1 = "Strasse1";
933
		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)));
934
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
935
		String street3 = "Street3";
936
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
937
		String emailAddress1 = "Email1";
938
		team1.addEmailAddress(emailAddress1);
939

    
940

    
941
		//FIXME
942
//		team2.addTeamMember(person1);
943
		team2.addTeamMember(person2);
944
		String emailAddress2 = "Email2";
945
		team2.addEmailAddress(emailAddress2);
946

    
947
		Credit credit1 = Credit.NewInstance(team2, "credit1");
948
		book1.addCredit(credit1);
949

    
950
		agentDao.save(team1);
951
		agentDao.save(team2);
952
		agentDao.save(person1);
953
		agentDao.save(person2);
954

    
955
		cdmGenericDao.save((Reference)book1);
956

    
957
		//starting condition
958
		name1.setCombinationAuthorship(person1);
959
		Assert.assertEquals("Name1 should have person1 as combination author", person1, name1.getCombinationAuthorship());
960

    
961
		DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(TeamOrPersonBase.class);
962
//		strategy.setOnlyReallocateLinks(true);
963

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

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

    
995
		//test successful merge
996
		cdmGenericDao.save(name1);
997
		cdmGenericDao.merge(team2, person1, strategy);
998
		Assert.assertEquals("Name1 should have team2 as combination author now", team2, name1.getCombinationAuthorship());
999

    
1000
	}
1001

    
1002

    
1003
	private void testMergeExceptions(CdmBase name1, CdmBase name2, CdmBase taxon, ICdmBase zooName1) throws MergeException{
1004
		//
1005
		try {
1006
			cdmGenericDao.merge(name1, null, null);
1007
			Assert.fail("Merging of 2 objects one or both of them null must throw an exception");
1008
		} catch (NullPointerException e) {
1009
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
1010
		}
1011
		//
1012
		try {
1013
			cdmGenericDao.merge(null, name1, null);
1014
			Assert.fail("Merging of 2 objects one or both of them null must throw an exception");
1015
		} catch (NullPointerException e) {
1016
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
1017
		}
1018
		//exceptions to be thrown
1019
		try {
1020
			cdmGenericDao.merge(name1, taxon, null);
1021
			//this is not fully true anymore !! In certain cases merging of objects of different classes is allowed
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
		//next exception
1027
		//for names this is not the case anymore
1028
//		try {
1029
//			cdmGenericDao.merge(name1, zooName1, null);
1030
//			Assert.fail("Merging of 2 objects of different types must throw an exception");
1031
//		} catch (MergeException e) {
1032
//			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
1033
//		}
1034
	}
1035

    
1036
	@Test
1037
	public void findMatching(){
1038
		IBook book1 = ReferenceFactory.newBook();
1039
		IBook book2 = ReferenceFactory.newBook();
1040
		IBook book3 = ReferenceFactory.newBook();
1041

    
1042
		String title1 = "title1";
1043
		String title2 = "title2";
1044
		book1.setTitle(title1);
1045
		book2.setTitle(title2);
1046
		book3.setTitle(title1);
1047

    
1048
		cdmGenericDao.saveOrUpdate((Reference)book1);
1049
		cdmGenericDao.saveOrUpdate((Reference)book2);
1050
		cdmGenericDao.saveOrUpdate((Reference)book3);
1051

    
1052
		IMatchStrategy matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1053

    
1054
		try {
1055
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1056
			Assert.assertNotNull("Resultlist must not be null", matchResult);
1057
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1058
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
1059

    
1060
			book1.setDatePublished(TimePeriod.NewInstance(1999, 2002));
1061
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1062
			Assert.assertTrue("Resultlist must have no entries", matchResult.isEmpty());
1063

    
1064
			book3.setDatePublished(TimePeriod.NewInstance(1999));
1065
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1066
			Assert.assertTrue("Resultlist must have no entries", matchResult.isEmpty());
1067

    
1068
			book3.setDatePublished(TimePeriod.NewInstance(1999,2002));
1069
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1070
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1071
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
1072

    
1073
			//BookSection
1074
			IBookSection section1 = ReferenceFactory.newBookSection();
1075
			section1.setInBook(book1);
1076
			section1.setTitle("SecTitle");
1077
			section1.setPages("22-33");
1078
			IBookSection section2 = ReferenceFactory.newBookSection();
1079
			section2.setInBook(book2);
1080
			section2.setTitle("SecTitle");
1081
			section2.setPages("22-33");
1082
			IBookSection section3 = ReferenceFactory.newBookSection();
1083
			section3.setInBook(book1);
1084
			section3.setTitle("SecTitle");
1085
			section3.setPages("22-33");
1086
			cdmGenericDao.saveOrUpdate((Reference)section1);
1087
			cdmGenericDao.saveOrUpdate((Reference)section2);
1088
			cdmGenericDao.saveOrUpdate((Reference)section3);
1089

    
1090
			List<IBookSection> sectionResult = cdmGenericDao.findMatching(section3, null);
1091
			Assert.assertEquals("Resultlist must have 1 entries", 1, sectionResult.size());
1092
			Assert.assertSame("Resultlist entry must be section1", section1, sectionResult.get(0));
1093

    
1094
			section2.setInBook(book2 = (IBook)book1.clone());
1095
			cdmGenericDao.saveOrUpdate((Reference)book2);
1096
			cdmGenericDao.saveOrUpdate((Reference)book1);
1097
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1098
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1099
			sectionResult = cdmGenericDao.findMatching(section3, null);
1100
			Assert.assertEquals("Resultlist must have 1 entries", 2, sectionResult.size());
1101

    
1102

    
1103
			Person person1 = Person.NewTitledInstance("person");
1104
			Person person2 = Person.NewTitledInstance("person");
1105
			Person person3 = Person.NewTitledInstance("person");
1106

    
1107
			person1.setPrefix("pre1");
1108
			person2.setPrefix("pre2");
1109
			person3.setPrefix("pre3");
1110

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

    
1114
			book1.setAuthorship(person1);
1115
			book2.setAuthorship(person1);
1116
			book3.setAuthorship(person1);
1117

    
1118
			boolean m = matchStrategy.invoke(book1, book3);
1119
			boolean m2 = matchStrategy.invoke(book2, book3);
1120

    
1121
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1122
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1123

    
1124
			book2.setAuthorship(person2);
1125
			book3.setAuthorship(person3);
1126
			matchResult = cdmGenericDao.findMatching(book3, null);
1127
			Assert.assertEquals("Resultlist must have no entries", 0, matchResult.size());
1128

    
1129
			person3.setPrefix("pre1");
1130
			matchResult = cdmGenericDao.findMatching(book3, null);
1131
			Assert.assertEquals("Resultlist must have 1 entry", 1, matchResult.size());
1132
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
1133

    
1134
		} catch (MatchException e) {
1135
			Assert.fail("Find match must not throw Exception: " + e.getMessage());
1136
			e.printStackTrace();
1137
		}
1138

    
1139
	}
1140

    
1141

    
1142
	@Test
1143
	public void findMatchingCache(){
1144
		IBook book1 = ReferenceFactory.newBook();
1145
		Team team1 = Team.NewInstance();
1146
		Team team2 = Team.NewInstance();
1147
		team1.setTitleCache("Team1", true);
1148
		team2.setTitleCache("Team1", true);
1149

    
1150
		book1.setTitle("Title1");
1151
		book1.setEdition("Edition1");
1152
		book1.setAuthorship(team1);
1153

    
1154

    
1155
		IBook book2 = (IBook) ((Reference)book1).clone();
1156
		IBook book3 = (IBook) ((Reference)book1).clone();
1157

    
1158
//		Assert.assertTrue("Cloned book should match", matchStrategy.invoke(book1, bookClone));
1159
//		book1.setTitleCache("cache1");
1160
//		Assert.assertFalse("Cached book should not match", matchStrategy.invoke(book1, bookClone));
1161
//
1162
//		bookClone.setTitleCache("cache1");
1163
//		Assert.assertTrue("Cached book with same cache should match", matchStrategy.invoke(book1, bookClone));
1164
//
1165
//		bookClone.setTitleCache("cache2");
1166
//		Assert.assertFalse("Cached book with differings caches should not match", matchStrategy.invoke(book1, bookClone));
1167
//		bookClone.setTitleCache("cache1"); //restore
1168
//
1169
//		bookClone.setEdition(null);
1170
//		Assert.assertTrue("Cached book with a defined and a null edition should match", matchStrategy.invoke(book1, bookClone));
1171

    
1172
		cdmGenericDao.saveOrUpdate((Reference)book1);
1173
		cdmGenericDao.saveOrUpdate((Reference)book2);
1174
		cdmGenericDao.saveOrUpdate((Reference)book3);
1175
		cdmGenericDao.saveOrUpdate(team1);
1176
		cdmGenericDao.saveOrUpdate(team2);
1177

    
1178

    
1179
		IMatchStrategy matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1180

    
1181
		try {
1182
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1183
			Assert.assertNotNull("Resultlist must not be null", matchResult);
1184
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1185
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1186
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1187

    
1188
			book1.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 2", matchResult.contains(book2));
1192

    
1193
			book2.setTitleCache("cache2", false);
1194
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1195
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1196
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1197

    
1198
			book2.setEdition(null);
1199
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1200
			Assert.assertEquals("Resultlist must have 0 entries", 0, matchResult.size());
1201

    
1202
			book3.setTitleCache("cache1", true);
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
			IMatchStrategy teamMatcher = DefaultMatchStrategy.NewInstance(Team.class);
1208
			boolean teamsMatch = teamMatcher.invoke(team1, team2);
1209
			Assert.assertTrue("Team1 and team2 should match" ,teamsMatch);
1210

    
1211
			book3.setAuthorship(team2);
1212
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1213
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1214
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1215

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

    
1221
			book2.setTitleCache(book3.getTitleCache(), true);
1222
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1223
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1224
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1225
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1226

    
1227
			team2.setTitleCache("team2", true);
1228
			teamsMatch = teamMatcher.invoke(team1, team2);
1229
			Assert.assertFalse("Team1 and team2 should not match" ,teamsMatch);
1230

    
1231
			book3.setAuthorship(team1);
1232
			book2.setAuthorship(team2);
1233
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1234
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1235
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1236

    
1237

    
1238
		} catch (MatchException e) {
1239
			Assert.fail("Find match must not throw Exception: " + e.getMessage());
1240
			e.printStackTrace();
1241
		}
1242
	}
1243

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

    
1261
	}
1262

    
1263
	/**
1264
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getHqlResult(java.lang.String)}.
1265
	 */
1266
	@Test
1267
	public void testGetHqlResult() {
1268
		logger.warn("Not yet implemented");
1269
	}
1270

    
1271
    @Override
1272
    public void createTestDataSet() throws FileNotFoundException {}
1273
}
(4-4/11)