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
		testMergeExceptions(name1, name2, taxon1, zooName1);
607

    
608

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

    
616
	}
617

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

    
628
		TaxonName<?,?> name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
629
		name2.setTitleCache("BotanicalName2", true);
630

    
631
		IBotanicalName name3 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
632
		name3.setTitleCache("BotanicalName3", true);
633

    
634
		Reference database = ReferenceFactory.newDatabase();
635

    
636
		Taxon taxon1 = Taxon.NewInstance(name1, database);
637
		Taxon taxon2 = Taxon.NewInstance(name2, database);
638
		Taxon taxon3 = Taxon.NewInstance(name3, database);
639

    
640
		taxonDao.save(taxon1);
641
		taxonDao.save(taxon2);
642
		taxonDao.save(taxon3);
643

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

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

    
652

    
653
	}
654

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

    
662
		IBotanicalName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
663
		name1.setTitleCache("BotanicalName1", true);
664

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

    
668
		IBook book1 = ReferenceFactory.newBook();
669
		IBook book2 = ReferenceFactory.newBook();
670

    
671
		Team team1 = Team.NewInstance();
672
		Team team2 = Team.NewInstance();
673
		Team team3 = Team.NewInstance();
674
		team1.setTitleCache("team1", true);
675
		team2.setTitleCache("team2", true);
676
		team3.setTitleCache("team3", true);
677

    
678
		Person person1 = Person.NewTitledInstance("person1");
679
		Person person2 = Person.NewTitledInstance("person2");
680
		Person person3 = Person.NewTitledInstance("person3");
681

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

    
691
		team2.addTeamMember(person1);
692
		team2.addTeamMember(person2);
693
		String emailAddress2 = "Email2";
694
		team2.addEmailAddress(emailAddress2);
695

    
696
		team3.addTeamMember(person3);
697
		team3.addEmailAddress("emailAddress3");
698

    
699
		book1.setAuthorship(team2);
700
		book2.setAuthorship(team3);
701

    
702
		Credit credit1 = Credit.NewInstance(team3, "credit1");
703
		book2.addCredit(credit1);
704

    
705
		agentDao.save(team1);
706
		agentDao.save(team2);
707
		agentDao.save(team3);
708
		cdmGenericDao.save((Reference)book1);
709
		cdmGenericDao.save((Reference)book2);
710

    
711
		cdmGenericDao.merge(team2, team3, null);
712

    
713
		Assert.assertSame("Author of book1 must be team2.", team2, book1.getAuthorship());
714
		Assert.assertSame("Author of book2 must be team2.", team2, book2.getAuthorship());
715
		Assert.assertSame("Agent of credit1 must be team2.", team2, credit1.getAgent());
716

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

    
721

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

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

    
748
		//Person
749
		Institution institution1 = Institution.NewInstance();
750
		institution1.setTitleCache("inst1", true);
751
		Institution institution2 = Institution.NewInstance();
752
		institution2.setTitleCache("inst2", true);
753

    
754
		TimePeriod period1 = TimePeriod.NewInstance(2002, 2004);
755
		TimePeriod period2 = TimePeriod.NewInstance(2004, 2006);
756

    
757
		person1.addInstitutionalMembership(institution1, period1, "departement1", "role1");
758
		person2.addInstitutionalMembership(institution2, period2, "departement2", "role2");
759

    
760
		IMergeStrategy personMergeStrategy = DefaultMergeStrategy.NewInstance(Person.class);
761
		personMergeStrategy.invoke(person1, person2);
762

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

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

    
785
        Person person1a = Person.NewTitledInstance("person1a");
786
        Person person1b = Person.NewTitledInstance("person1b");
787
        Person person2 = Person.NewTitledInstance("person2");
788
        Person person3 = Person.NewTitledInstance("person3");
789

    
790
        team1.addTeamMember(person1a);
791
        team1.addTeamMember(person2);
792

    
793

    
794
        team2.addTeamMember(person2);
795
        team2.addTeamMember(person1a);
796
        team2.addTeamMember(person3);
797

    
798
        team3.addTeamMember(person3);
799

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

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

    
809
        team1 = (Team)agentDao.load(team1.getUuid());
810
        team2 = (Team)agentDao.load(team2.getUuid());
811

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

    
816
        Assert.assertEquals("person2", team2.getTeamMembers().get(0).getTitleCache());
817
        Assert.assertEquals("person1b", team2.getTeamMembers().get(1).getTitleCache());
818
        Assert.assertEquals("person3", team2.getTeamMembers().get(2).getTitleCache());
819

    
820
    }
821

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

    
827
        // CREATE DATA
828

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

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

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

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

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

    
864
    }
865

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

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

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

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

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

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

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

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

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

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

    
915
	    TaxonName<?,?> name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
916
		name1.setTitleCache("BotanicalName1", true);
917

    
918
		IBook book1 = ReferenceFactory.newBook();
919

    
920
		Team team1 = Team.NewInstance();
921
		Team team2 = Team.NewInstance();
922
		team1.setTitleCache("team1", true);
923
		team2.setTitleCache("team2", true);
924

    
925
		Person person1 = Person.NewTitledInstance("person1");
926
		Person person2 = Person.NewTitledInstance("person2");
927

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

    
937

    
938
		//FIXME
939
//		team2.addTeamMember(person1);
940
		team2.addTeamMember(person2);
941
		String emailAddress2 = "Email2";
942
		team2.addEmailAddress(emailAddress2);
943

    
944
		Credit credit1 = Credit.NewInstance(team2, "credit1");
945
		book1.addCredit(credit1);
946

    
947
		agentDao.save(team1);
948
		agentDao.save(team2);
949
		agentDao.save(person1);
950
		agentDao.save(person2);
951

    
952
		cdmGenericDao.save((Reference)book1);
953

    
954
		//starting condition
955
		name1.setCombinationAuthorship(person1);
956
		Assert.assertEquals("Name1 should have person1 as combination author", person1, name1.getCombinationAuthorship());
957

    
958
		DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(TeamOrPersonBase.class);
959
//		strategy.setOnlyReallocateLinks(true);
960

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

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

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

    
997
	}
998

    
999

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

    
1033
	@Test
1034
	public void findMatching(){
1035
		IBook book1 = ReferenceFactory.newBook();
1036
		IBook book2 = ReferenceFactory.newBook();
1037
		IBook book3 = ReferenceFactory.newBook();
1038

    
1039
		String title1 = "title1";
1040
		String title2 = "title2";
1041
		book1.setTitle(title1);
1042
		book2.setTitle(title2);
1043
		book3.setTitle(title1);
1044

    
1045
		cdmGenericDao.saveOrUpdate((Reference)book1);
1046
		cdmGenericDao.saveOrUpdate((Reference)book2);
1047
		cdmGenericDao.saveOrUpdate((Reference)book3);
1048

    
1049
		IMatchStrategy matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1050

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

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

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

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

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

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

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

    
1099

    
1100
			Person person1 = Person.NewTitledInstance("person");
1101
			Person person2 = Person.NewTitledInstance("person");
1102
			Person person3 = Person.NewTitledInstance("person");
1103

    
1104
			person1.setPrefix("pre1");
1105
			person2.setPrefix("pre2");
1106
			person3.setPrefix("pre3");
1107

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

    
1111
			book1.setAuthorship(person1);
1112
			book2.setAuthorship(person1);
1113
			book3.setAuthorship(person1);
1114

    
1115
			boolean m = matchStrategy.invoke(book1, book3);
1116
			boolean m2 = matchStrategy.invoke(book2, book3);
1117

    
1118
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1119
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1120

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

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

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

    
1136
	}
1137

    
1138

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

    
1147
		book1.setTitle("Title1");
1148
		book1.setEdition("Edition1");
1149
		book1.setAuthorship(team1);
1150

    
1151

    
1152
		IBook book2 = (IBook) ((Reference)book1).clone();
1153
		IBook book3 = (IBook) ((Reference)book1).clone();
1154

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

    
1169
		cdmGenericDao.saveOrUpdate((Reference)book1);
1170
		cdmGenericDao.saveOrUpdate((Reference)book2);
1171
		cdmGenericDao.saveOrUpdate((Reference)book3);
1172
		cdmGenericDao.saveOrUpdate(team1);
1173
		cdmGenericDao.saveOrUpdate(team2);
1174

    
1175

    
1176
		IMatchStrategy matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1177

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

    
1185
			book1.setTitleCache("cache1", true);
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.setTitleCache("cache2", false);
1191
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1192
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1193
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1194

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

    
1199
			book3.setTitleCache("cache1", true);
1200
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1201
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1202
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1203

    
1204
			IMatchStrategy teamMatcher = DefaultMatchStrategy.NewInstance(Team.class);
1205
			boolean teamsMatch = teamMatcher.invoke(team1, team2);
1206
			Assert.assertTrue("Team1 and team2 should match" ,teamsMatch);
1207

    
1208
			book3.setAuthorship(team2);
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
			book3.setAuthorship(null);
1214
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1215
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1216
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1217

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

    
1224
			team2.setTitleCache("team2", true);
1225
			teamsMatch = teamMatcher.invoke(team1, team2);
1226
			Assert.assertFalse("Team1 and team2 should not match" ,teamsMatch);
1227

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

    
1234

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

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

    
1258
	}
1259

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

    
1268
    @Override
1269
    public void createTestDataSet() throws FileNotFoundException {}
1270
}
(4-4/11)