Project

General

Profile

Download (45 KB) Statistics
| Branch: | Tag: | Revision:
1
// $Id$
2
/**
3
* Copyright (C) 2007 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8
* See LICENSE.TXT at the top of this package for the full license terms.
9
*/
10

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

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

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

    
24
import org.apache.log4j.Logger;
25
import org.hibernate.MappingException;
26
import org.hibernate.internal.SessionFactoryImpl;
27
import org.hibernate.persister.collection.CollectionPersister;
28
import org.hibernate.stat.Statistics;
29
import org.hibernate.type.Type;
30
import org.junit.Assert;
31
import org.junit.Before;
32
import org.junit.Test;
33
import org.unitils.dbunit.annotation.DataSet;
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.IdentifiableSource;
55
import eu.etaxonomy.cdm.model.common.Identifier;
56
import eu.etaxonomy.cdm.model.common.IntextReference;
57
import eu.etaxonomy.cdm.model.common.LSIDAuthority;
58
import eu.etaxonomy.cdm.model.common.Language;
59
import eu.etaxonomy.cdm.model.common.LanguageString;
60
import eu.etaxonomy.cdm.model.common.Marker;
61
import eu.etaxonomy.cdm.model.common.MarkerType;
62
import eu.etaxonomy.cdm.model.common.OrderedTermBase;
63
import eu.etaxonomy.cdm.model.common.OrderedTermVocabulary;
64
import eu.etaxonomy.cdm.model.common.OriginalSourceBase;
65
import eu.etaxonomy.cdm.model.common.OriginalSourceType;
66
import eu.etaxonomy.cdm.model.common.RelationshipTermBase;
67
import eu.etaxonomy.cdm.model.common.Representation;
68
import eu.etaxonomy.cdm.model.common.TermVocabulary;
69
import eu.etaxonomy.cdm.model.common.TimePeriod;
70
import eu.etaxonomy.cdm.model.common.User;
71
import eu.etaxonomy.cdm.model.description.CategoricalData;
72
import eu.etaxonomy.cdm.model.description.CommonTaxonName;
73
import eu.etaxonomy.cdm.model.description.DescriptionBase;
74
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
75
import eu.etaxonomy.cdm.model.description.Distribution;
76
import eu.etaxonomy.cdm.model.description.Feature;
77
import eu.etaxonomy.cdm.model.description.FeatureNode;
78
import eu.etaxonomy.cdm.model.description.FeatureTree;
79
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
80
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
81
import eu.etaxonomy.cdm.model.description.MediaKey;
82
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
83
import eu.etaxonomy.cdm.model.description.QuantitativeData;
84
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
85
import eu.etaxonomy.cdm.model.description.State;
86
import eu.etaxonomy.cdm.model.description.StateData;
87
import eu.etaxonomy.cdm.model.description.StatisticalMeasure;
88
import eu.etaxonomy.cdm.model.description.StatisticalMeasurementValue;
89
import eu.etaxonomy.cdm.model.description.TaxonDescription;
90
import eu.etaxonomy.cdm.model.description.TaxonInteraction;
91
import eu.etaxonomy.cdm.model.description.TaxonNameDescription;
92
import eu.etaxonomy.cdm.model.description.TextData;
93
import eu.etaxonomy.cdm.model.description.TextFormat;
94
import eu.etaxonomy.cdm.model.location.Country;
95
import eu.etaxonomy.cdm.model.location.NamedArea;
96
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
97
import eu.etaxonomy.cdm.model.location.NamedAreaType;
98
import eu.etaxonomy.cdm.model.location.Point;
99
import eu.etaxonomy.cdm.model.location.ReferenceSystem;
100
import eu.etaxonomy.cdm.model.media.AudioFile;
101
import eu.etaxonomy.cdm.model.media.ImageFile;
102
import eu.etaxonomy.cdm.model.media.Media;
103
import eu.etaxonomy.cdm.model.media.MediaRepresentation;
104
import eu.etaxonomy.cdm.model.media.MediaRepresentationPart;
105
import eu.etaxonomy.cdm.model.media.MovieFile;
106
import eu.etaxonomy.cdm.model.media.Rights;
107
import eu.etaxonomy.cdm.model.media.RightsType;
108
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
109
import eu.etaxonomy.cdm.model.molecular.Amplification;
110
import eu.etaxonomy.cdm.model.molecular.DnaSample;
111
import eu.etaxonomy.cdm.model.molecular.PhylogeneticTree;
112
import eu.etaxonomy.cdm.model.molecular.Primer;
113
import eu.etaxonomy.cdm.model.molecular.Sequence;
114
import eu.etaxonomy.cdm.model.molecular.SingleRead;
115
import eu.etaxonomy.cdm.model.molecular.SingleReadAlignment;
116
import eu.etaxonomy.cdm.model.name.BacterialName;
117
import eu.etaxonomy.cdm.model.name.BotanicalName;
118
import eu.etaxonomy.cdm.model.name.CultivarPlantName;
119
import eu.etaxonomy.cdm.model.name.HomotypicalGroup;
120
import eu.etaxonomy.cdm.model.name.HybridRelationship;
121
import eu.etaxonomy.cdm.model.name.HybridRelationshipType;
122
import eu.etaxonomy.cdm.model.name.NameRelationship;
123
import eu.etaxonomy.cdm.model.name.NameRelationshipType;
124
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
125
import eu.etaxonomy.cdm.model.name.NameTypeDesignationStatus;
126
import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
127
import eu.etaxonomy.cdm.model.name.NomenclaturalStatusType;
128
import eu.etaxonomy.cdm.model.name.NonViralName;
129
import eu.etaxonomy.cdm.model.name.Rank;
130
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
131
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
132
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
133
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
134
import eu.etaxonomy.cdm.model.name.ViralName;
135
import eu.etaxonomy.cdm.model.name.ZoologicalName;
136
import eu.etaxonomy.cdm.model.occurrence.Collection;
137
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
138
import eu.etaxonomy.cdm.model.occurrence.DerivationEventType;
139
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
140
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
141
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
142
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
143
import eu.etaxonomy.cdm.model.occurrence.PreservationMethod;
144
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
145
import eu.etaxonomy.cdm.model.reference.IBook;
146
import eu.etaxonomy.cdm.model.reference.IBookSection;
147
import eu.etaxonomy.cdm.model.reference.Reference;
148
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
149
import eu.etaxonomy.cdm.model.taxon.Classification;
150
import eu.etaxonomy.cdm.model.taxon.Synonym;
151
import eu.etaxonomy.cdm.model.taxon.SynonymRelationship;
152
import eu.etaxonomy.cdm.model.taxon.SynonymRelationshipType;
153
import eu.etaxonomy.cdm.model.taxon.Taxon;
154
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
155
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
156
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
157
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
158
import eu.etaxonomy.cdm.model.view.AuditEvent;
159
import eu.etaxonomy.cdm.persistence.dao.agent.IAgentDao;
160
import eu.etaxonomy.cdm.persistence.dao.common.ICdmGenericDao;
161
import eu.etaxonomy.cdm.persistence.dao.name.ITaxonNameDao;
162
import eu.etaxonomy.cdm.persistence.dao.occurrence.IOccurrenceDao;
163
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonDao;
164
import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
165
import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
166
import eu.etaxonomy.cdm.strategy.match.MatchException;
167
import eu.etaxonomy.cdm.strategy.merge.DefaultMergeStrategy;
168
import eu.etaxonomy.cdm.strategy.merge.IMergeStrategy;
169
import eu.etaxonomy.cdm.strategy.merge.MergeException;
170
import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
171

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

    
179
	@SpringBeanByType
180
	private ICdmGenericDao cdmGenericDao;
181

    
182
	@SpringBeanByType
183
	private ITaxonDao taxonDao;
184

    
185
	@SpringBeanByType
186
	private IOccurrenceDao occurrenceDao;
187

    
188
	@SpringBeanByType
189
	private ITaxonNameDao nameDao;
190

    
191
	@SpringBeanByType
192
	private IAgentDao agentDao;
193

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

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

    
202
	@Test
203
	public void testDelete(){
204
		Reference ref1 = ReferenceFactory.newBook();
205
		Reference ref2 = ReferenceFactory.newBook();
206
		Annotation annotation = Annotation.NewInstance("Anno1", null);
207
		ref1.addAnnotation(annotation);
208
		cdmGenericDao.saveOrUpdate(ref1);
209
		cdmGenericDao.saveOrUpdate(ref2);
210
		taxonDao.flush();
211
		try {
212
			cdmGenericDao.merge(ref2, ref1, null);
213
			taxonDao.flush();
214
		} catch (MergeException e) {
215
			Assert.fail();
216
		}
217
		cdmGenericDao.delete(ref1);
218
		taxonDao.flush();
219
	}
220

    
221

    
222
	/**
223
	 * 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)}.
224
	 */
225
	@Test
226
	public void testGetCdmBasesByFieldAndClass() {
227
		logger.warn("Not yet implemented");
228
	}
229

    
230
	/**
231
	 * 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)}.
232
	 */
233
	@Test
234
	public void testGetCdmBasesWithItemInCollection() {
235
		logger.warn("Not yet implemented");
236
	}
237

    
238
	/**
239
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getAllPersistedClasses(boolean)}.
240
	 */
241
	@Test
242
	public void testGetAllPersistedClasses() {
243
		Class<?>[] existingClassesArray = {
244
				Address.class,
245
				AgentBase.class,
246
				Institution.class,
247
				InstitutionalMembership.class,
248
				Person.class,
249
				Team.class,
250
				TeamOrPersonBase.class,
251
				Annotation.class,
252
				AnnotationType.class,
253
				Credit.class,
254
				DefinedTermBase.class,
255
				Extension.class,
256
				ExtensionType.class,
257
				GrantedAuthorityImpl.class,
258
				Group.class,
259
				IdentifiableSource.class,
260
				Identifier.class,
261
				IntextReference.class,
262
				Language.class,
263
				LanguageString.class,
264
				LSIDAuthority.class,
265
				Marker.class,
266
				MarkerType.class,
267
				OrderedTermBase.class,
268
				OrderedTermVocabulary.class,
269
				OriginalSourceBase.class,
270
				RelationshipTermBase.class,
271
				Representation.class,
272
				TermVocabulary.class,
273
				User.class,
274
				DefinedTerm.class,
275

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

    
369
		//for debugging only
370
		//		for (Class existingClass : existingClassesList){
371
		//			if (! foundClasses.contains(existingClass)){
372
		//				logger.warn("Class not found: " + existingClass.getCanonicalName());
373
		//			}
374
		//		}
375

    
376
		//All classes must be found
377
		Assert.assertTrue("all classes must be found by getAllCdmClasses() method", foundClasses.containsAll(existingClassesList));
378

    
379

    
380
		//No extra classes must be found
381
		for (Class<?> clazz : foundClasses){
382
			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)
383
				Assert.fail("Class " + clazz.getName() + " is not assignable from CdmBase");
384
			}
385
		}
386

    
387
		includeAbstractClasses = false;
388
		Set<Class<? extends CdmBase>> noAbstractClasses = cdmGenericDao.getAllPersistedClasses(includeAbstractClasses);
389
		Class<?> abstractClassToTest = TaxonNameBase.class;
390
		Assert.assertFalse("Abstract class " + abstractClassToTest.getName() + " may not be in set ", noAbstractClasses.contains(abstractClassToTest));
391
	}
392

    
393
	/**
394
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getReferencingObjects(CdmBase)}.
395
	 */
396
	@Test
397
	public void testGetReferencingObjectsCdmBase() {
398
		BotanicalName name = BotanicalName.NewInstance(Rank.SPECIES());
399
		name.setTitleCache("A name", true);
400
		Reference ref1 = ReferenceFactory.newArticle();
401
		Taxon taxon = Taxon.NewInstance(name, ref1);
402
		Person author = Person.NewInstance();
403
		author.setTitleCache("Author", true);
404
		ref1.addAnnotation(Annotation.NewInstance("A1", Language.DEFAULT()));
405
		ref1.setAuthorship(author);
406
		name.setBasionymAuthorship(author);
407

    
408
		name.setNomenclaturalReference(ref1);
409

    
410
		taxonDao.save(taxon);
411
//		UUID uuid = UUID.fromString("613980ac-9bd5-43b9-a374-d71e1794688f");
412
//		Reference ref1 = referenceService.findByUuid(uuid);
413

    
414

    
415
		Set<CdmBase> referencedObjects = cdmGenericDao.getReferencingObjects(ref1);
416
		System.out.println("############## RESULT ###################");
417
		for (CdmBase obj: referencedObjects){
418
			System.out.println("Object1: " + obj.getClass().getSimpleName() + " - " + obj);
419
		}
420
		//was 3 before bidirectionality was removed for supplemental data
421
		assertEquals(2, referencedObjects.size());
422
		System.out.println("############## ENDE ###################");
423

    
424
//		UUID uuidAuthor = UUID.fromString("4ce66544-a5a3-4601-ab0b-1f0a1338327b");
425
//		AgentBase author = agentService.findByUuid(uuidAuthor);
426

    
427
		referencedObjects = cdmGenericDao.getReferencingObjects(author);
428
		System.out.println("############## RESULT ###################");
429
		for (CdmBase obj: referencedObjects){
430
			System.out.println("Object2: " + obj.getClass().getSimpleName() + " - " + obj);
431
		}
432
		assertEquals(2, referencedObjects.size());
433
		System.out.println("############## ENDE ###################");
434
	}
435

    
436
	/**
437
	 * 2nd test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getReferencingObjects(CdmBase)}.
438
	 *
439
	 */
440
	@Test
441
	@DataSet
442
	public final void testGetReferencingObjects2() {
443
//		SpecimenDescription desc1 = SpecimenDescription.NewInstance();
444
//		desc1.setTitleCache("desc1");
445
//		SpecimenDescription desc2 = SpecimenDescription.NewInstance();
446
//		desc2.setTitleCache("desc2");
447
//
448
//		SpecimenOrObservationBase spec1 = Specimen.NewInstance();
449
//
450
//		desc1.addDescribedSpecimenOrObservation(spec1);
451
//		//Taxon taxon = Taxon.NewInstance(taxonNameBase, sec)
452
//		spec1.addDescription(desc2);
453
//
454
//		occurrenceService.save(spec1);
455

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

    
459

    
460
		Set<CdmBase> referencingObjects = cdmGenericDao.getReferencingObjects(spec1);
461
//		System.out.println("############## RESULT ###################");
462
//		for (CdmBase obj: referencingObjects){
463
//			System.out.println("Object: " + obj.getClass().getSimpleName() + " - " + obj);
464
//		}
465
//		System.out.println("############## ENDE ###################");
466
		assertEquals("Number of referencing objects must be 2.", 2, referencingObjects.size());
467

    
468
	}
469

    
470
	/**
471
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
472
	 * @throws MergeException
473
	 */
474
	@Test
475
//	@Ignore
476
	public void testMergeCdmBaseReferenceAndIdentifiable() throws MergeException {
477

    
478
		BotanicalName name1 = BotanicalName.NewInstance(Rank.SPECIES());
479
		name1.setTitleCache("BotanicalName1", true);
480

    
481
		BotanicalName name2 = BotanicalName.NewInstance(Rank.SPECIES());
482
		name2.setTitleCache("BotanicalName2", true);
483

    
484
		ZoologicalName zooName1 = ZoologicalName.NewInstance(Rank.SPECIES());
485
		name1.setTitleCache("ZoologicalName1", true);
486

    
487
		Reference article1 = ReferenceFactory.newArticle();
488
		Reference article2 = ReferenceFactory.newArticle();
489

    
490

    
491
		name1.setNomenclaturalReference(article1);
492
		name2.setNomenclaturalReference(article2);
493

    
494

    
495
		Taxon taxon1 = Taxon.NewInstance(name1, article1);
496
		Taxon taxon2 = Taxon.NewInstance(name2, article2);
497

    
498

    
499
//		Person author = Person.NewInstance();
500
//		author.setTitleCache("Author");
501
		Annotation annotation1 = Annotation.NewInstance("A1", Language.DEFAULT());
502
		Annotation annotation2 = Annotation.NewInstance("A2", Language.DEFAULT());
503

    
504
		article1.addAnnotation(annotation1);
505
		article2.addAnnotation(annotation2);
506

    
507
		Marker marker1 = Marker.NewInstance(MarkerType.COMPLETE(), false);
508
		Marker marker2 = Marker.NewInstance(MarkerType.IMPORTED(), false);
509

    
510
		article1.addMarker(marker1);
511
		article2.addMarker(marker2);
512

    
513
		Rights rights1 = Rights.NewInstance();
514
		Rights rights2 = Rights.NewInstance();
515

    
516
		article1.addRights(rights1);
517
		article2.addRights(rights2);
518

    
519
		Credit credit1 = Credit.NewInstance(Team.NewInstance(), "credit1");
520
		Credit credit2 = Credit.NewInstance(Team.NewInstance(), "credit2");
521

    
522
		article1.addCredit(credit1);
523
		article2.addCredit(credit2);
524

    
525
		Extension extension1 = Extension.NewInstance();
526
		Extension extension2 = Extension.NewInstance();
527

    
528
		article1.addExtension(extension1);
529
		article2.addExtension(extension2);
530

    
531
		IdentifiableSource source1 = IdentifiableSource.NewInstance(OriginalSourceType.Unknown);
532
		IdentifiableSource source2 = IdentifiableSource.NewInstance(OriginalSourceType.Unknown);
533

    
534
		article1.addSource(source1);
535
		article2.addSource(source2);
536

    
537
		Media media1 = Media.NewInstance();
538
		Media media2 = Media.NewInstance();
539

    
540
		article1.addMedia(media1);
541
		article2.addMedia(media2);
542

    
543
//		ref1.setAuthorship(author);
544
//		name1.setBasionymAuthorship(author);
545

    
546
		name1.setNomenclaturalReference(article1);
547

    
548
		nameDao.save(name1);
549
		nameDao.save(name2);
550
		nameDao.save(zooName1);
551

    
552
		TaxonDescription taxDesc = TaxonDescription.NewInstance(taxon1);
553
		taxDesc.setTitleCache("taxDesc", true);
554
		taxDesc.addSource(OriginalSourceType.Unknown, null, null, article2, null);
555

    
556
		taxonDao.save(taxon1);
557

    
558
		//unidircetional reference to the merged object should be redirected
559
		cdmGenericDao.merge(article1, article2, null);
560
		Assert.assertEquals("Name2 must have article 1 as new nomRef", article1 ,name2.getNomenclaturalReference());
561
		//TODO microCitations!! -> warning
562

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

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

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

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

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

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

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

    
584
		//Description sources
585
		Assert.assertEquals("Number of sources for taxon description must be 1", 1, taxDesc.getSources().size());
586
		Assert.assertEquals("Taxon description must have article1 as source", taxDesc.getSources().iterator().next().getCitation(),article1);
587

    
588
		//test exceptions
589
		testMergeExceptions(name1, name2, taxon1, zooName1);
590

    
591

    
592
		//FIXME TO BE IMPLEMENTED
593
		//current defalt implementation for rights, credits and media is ADD_CLONE and therefore the below tests don't work
594
		//TODO is this the wanted default behaviour?
595
//		Assert.assertTrue("Rights2 must be contained in the rights", article1.getRights().contains(rights2));
596
//		Assert.assertTrue("Credits2 must be contained in the credits", article1.getCredits().contains(credit2));
597
//		Assert.assertTrue("Media2 must be contained in the media", article1.getMedia().contains(media2));
598

    
599
	}
600

    
601
	/**
602
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
603
	 * @throws MergeException
604
	 */
605
	@Test
606
//	@Ignore
607
	public void testMergeTaxonNameAndTaxon() throws MergeException {
608
		BotanicalName name1 = BotanicalName.NewInstance(Rank.SPECIES());
609
		name1.setTitleCache("BotanicalName1", true);
610

    
611
		BotanicalName name2 = BotanicalName.NewInstance(Rank.SPECIES());
612
		name2.setTitleCache("BotanicalName2", true);
613

    
614
		BotanicalName name3 = BotanicalName.NewInstance(Rank.SPECIES());
615
		name3.setTitleCache("BotanicalName3", true);
616

    
617
		Reference database = ReferenceFactory.newDatabase();
618

    
619
		Taxon taxon1 = Taxon.NewInstance(name1, database);
620
		Taxon taxon2 = Taxon.NewInstance(name2, database);
621
		Taxon taxon3 = Taxon.NewInstance(name3, database);
622

    
623
		taxonDao.save(taxon1);
624
		taxonDao.save(taxon2);
625
		taxonDao.save(taxon3);
626

    
627
		cdmGenericDao.merge(name1, name2, null);
628
		Assert.assertEquals("Name1 must have 2 taxa attached now.", 2 ,name1.getTaxonBases().size());
629
		Assert.assertEquals("Taxon2 must have name1 as new name.", name1 ,taxon2.getName());
630

    
631
//TODO
632
//		cdmGenericDao.merge(taxon1, taxon3, null);
633
//		Assert.assertEquals("Name1 must have 3 taxa attached now.", 3 ,name1.getTaxonBases().size());
634

    
635

    
636
	}
637

    
638
	/**
639
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
640
	 * @throws MergeException
641
	 */
642
	@Test
643
	public void testMergeAuthors() throws MergeException {
644

    
645
		BotanicalName name1 = BotanicalName.NewInstance(Rank.SPECIES());
646
		name1.setTitleCache("BotanicalName1", true);
647

    
648
		BotanicalName name2 = BotanicalName.NewInstance(Rank.SPECIES());
649
		name2.setTitleCache("BotanicalName2", true);
650

    
651
		IBook book1 = ReferenceFactory.newBook();
652
		IBook book2 = ReferenceFactory.newBook();
653

    
654
		Team team1 = Team.NewInstance();
655
		Team team2 = Team.NewInstance();
656
		Team team3 = Team.NewInstance();
657
		team1.setTitleCache("team1", true);
658
		team2.setTitleCache("team2", true);
659
		team3.setTitleCache("team3", true);
660

    
661
		Person person1 = Person.NewTitledInstance("person1");
662
		Person person2 = Person.NewTitledInstance("person2");
663
		Person person3 = Person.NewTitledInstance("person3");
664

    
665
		team1.setNomenclaturalTitle("T.1");
666
		String street1 = "Strasse1";
667
		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)));
668
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
669
		String street3 = "Street3";
670
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
671
		String emailAddress1 = "Email1";
672
		team1.addEmailAddress(emailAddress1);
673

    
674
		team2.addTeamMember(person1);
675
		team2.addTeamMember(person2);
676
		String emailAddress2 = "Email2";
677
		team2.addEmailAddress(emailAddress2);
678

    
679
		team3.addTeamMember(person3);
680
		team3.addEmailAddress("emailAddress3");
681

    
682
		book1.setAuthorship(team2);
683
		book2.setAuthorship(team3);
684

    
685
		Credit credit1 = Credit.NewInstance(team3, "credit1");
686
		book2.addCredit(credit1);
687

    
688
		agentDao.save(team1);
689
		agentDao.save(team2);
690
		agentDao.save(team3);
691
		cdmGenericDao.save((Reference)book1);
692
		cdmGenericDao.save((Reference)book2);
693

    
694
		cdmGenericDao.merge(team2, team3, null);
695

    
696
		Assert.assertSame("Author of book1 must be team2.", team2, book1.getAuthorship());
697
		Assert.assertSame("Author of book2 must be team2.", team2, book2.getAuthorship());
698
		Assert.assertSame("Agent of credit1 must be team2.", team2, credit1.getAgent());
699

    
700
		Assert.assertEquals("Team2 must have 3 persons as members.",3, team2.getTeamMembers().size());
701
		Assert.assertTrue("Team2 must have person3 as new member.", team2.getTeamMembers().contains(person3));
702
		Assert.assertSame("Team2 must have person3 as third member.",person3, team2.getTeamMembers().get(2));
703

    
704

    
705
		//Contact
706
		cdmGenericDao.merge(team2, team1, null);
707
		Contact team2Contact = team2.getContact();
708
		Assert.assertNotNull("team2Contact must not be null", team2Contact);
709
		Assert.assertNotNull("Addresses must not be null", team2Contact.getAddresses());
710
		Assert.assertEquals("Number of addresses must be 3", 3, team2Contact.getAddresses().size());
711
		Assert.assertEquals("Number of email addresses must be 4", 4, team2Contact.getEmailAddresses().size());
712

    
713
		boolean street1Exists = false;
714
		boolean street3Exists = false;
715
		boolean country1Exists = false;
716
		for  (Address address : team2Contact.getAddresses()){
717
			if (street1.equals(address.getStreet())){
718
				street1Exists = true;
719
			}
720
			if (street3.equals(address.getStreet())){
721
				street3Exists = true;
722
			}
723
			if (Country.ARGENTINAARGENTINEREPUBLIC() == address.getCountry()){
724
				country1Exists = true;
725
			}
726
		}
727
		Assert.assertTrue("Street1 must be one of the streets in team2's addresses", street1Exists);
728
		Assert.assertTrue("Street3 must be one of the streets in team2's addressesss", street3Exists);
729
		Assert.assertTrue("Argentina must be one of the countries in team2's addresses", country1Exists);
730

    
731
		//Person
732
		Institution institution1 = Institution.NewInstance();
733
		institution1.setTitleCache("inst1", true);
734
		Institution institution2 = Institution.NewInstance();
735
		institution2.setTitleCache("inst2", true);
736

    
737
		TimePeriod period1 = TimePeriod.NewInstance(2002, 2004);
738
		TimePeriod period2 = TimePeriod.NewInstance(2004, 2006);
739

    
740
		person1.addInstitutionalMembership(institution1, period1, "departement1", "role1");
741
		person2.addInstitutionalMembership(institution2, period2, "departement2", "role2");
742

    
743
		IMergeStrategy personMergeStrategy = DefaultMergeStrategy.NewInstance(Person.class);
744
		personMergeStrategy.invoke(person1, person2);
745

    
746
		Assert.assertEquals("Number of institutional memberships must be 2", 2, person1.getInstitutionalMemberships().size());
747
		for (InstitutionalMembership institutionalMembership : person1.getInstitutionalMemberships()){
748
			Assert.assertSame("Person of institutional memebership must be person1", person1, institutionalMembership.getPerson());
749
		}
750
	}
751

    
752
	/**
753
     * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
754
     *
755
     * Test for  http://dev.e-taxonomy.eu/trac/ticket/5652
756
     *
757
     * @throws MergeException
758
     */
759
    @Test
760
    public void testMergePersons() throws MergeException {
761
        Team team1 = Team.NewInstance();
762
        Team team2 = Team.NewInstance();
763
        Team team3 = Team.NewInstance();
764
        team1.setTitleCache("team1", true);
765
        team2.setTitleCache("team2", true);
766
        team3.setTitleCache("team3", true);
767

    
768
        Person person1a = Person.NewTitledInstance("person1a");
769
        Person person1b = Person.NewTitledInstance("person1b");
770
        Person person2 = Person.NewTitledInstance("person2");
771
        Person person3 = Person.NewTitledInstance("person3");
772

    
773
        team1.addTeamMember(person1a);
774
        team1.addTeamMember(person2);
775

    
776

    
777
        team2.addTeamMember(person2);
778
        team2.addTeamMember(person1a);
779
        team2.addTeamMember(person3);
780

    
781
        team3.addTeamMember(person3);
782

    
783
        agentDao.save(team1);
784
        agentDao.save(team2);
785
        agentDao.save(team3);
786
        agentDao.save(person1b);
787
        commitAndStartNewTransaction(null);
788

    
789
        IMergeStrategy personMergeStrategy = DefaultMergeStrategy.NewInstance(Person.class);
790
        cdmGenericDao.merge(person1b, person1a, personMergeStrategy);
791

    
792
        team1 = (Team)agentDao.load(team1.getUuid());
793
        team2 = (Team)agentDao.load(team2.getUuid());
794

    
795
        //order should not change and 1a should be replaced by 1b
796
        Assert.assertEquals("person1b", team1.getTeamMembers().get(0).getTitleCache());
797
        Assert.assertEquals("person2", team1.getTeamMembers().get(1).getTitleCache());
798

    
799
        Assert.assertEquals("person2", team2.getTeamMembers().get(0).getTitleCache());
800
        Assert.assertEquals("person1b", team2.getTeamMembers().get(1).getTitleCache());
801
        Assert.assertEquals("person3", team2.getTeamMembers().get(2).getTitleCache());
802

    
803
    }
804

    
805

    
806

    
807
	/**
808
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
809
	 * @throws MergeException
810
	 */
811
	@Test
812
	public void testReallocatePersonTeam() throws MergeException {
813

    
814
		BotanicalName name1 = BotanicalName.NewInstance(Rank.SPECIES());
815
		name1.setTitleCache("BotanicalName1", true);
816

    
817
		IBook book1 = ReferenceFactory.newBook();
818

    
819
		Team team1 = Team.NewInstance();
820
		Team team2 = Team.NewInstance();
821
		team1.setTitleCache("team1", true);
822
		team2.setTitleCache("team2", true);
823

    
824
		Person person1 = Person.NewTitledInstance("person1");
825
		Person person2 = Person.NewTitledInstance("person2");
826

    
827
		team1.setNomenclaturalTitle("T.1");
828
		String street1 = "Strasse1";
829
		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)));
830
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
831
		String street3 = "Street3";
832
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
833
		String emailAddress1 = "Email1";
834
		team1.addEmailAddress(emailAddress1);
835

    
836

    
837
		//FIXME
838
//		team2.addTeamMember(person1);
839
		team2.addTeamMember(person2);
840
		String emailAddress2 = "Email2";
841
		team2.addEmailAddress(emailAddress2);
842

    
843
		Credit credit1 = Credit.NewInstance(team2, "credit1");
844
		book1.addCredit(credit1);
845

    
846
		agentDao.save(team1);
847
		agentDao.save(team2);
848
		agentDao.save(person1);
849
		agentDao.save(person2);
850

    
851
		cdmGenericDao.save((Reference)book1);
852

    
853
		//starting condition
854
		name1.setCombinationAuthorship(person1);
855
		Assert.assertEquals("Name1 should have person1 as combination author", person1, name1.getCombinationAuthorship());
856

    
857
		DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(TeamOrPersonBase.class);
858
//		strategy.setOnlyReallocateLinks(true);
859

    
860
		FieldUnit fieldUnit1 = FieldUnit.NewInstance();
861
		fieldUnit1.setPrimaryCollector(person1);
862
		cdmGenericDao.save(fieldUnit1);
863
		try {
864
			cdmGenericDao.merge(team2, person1, strategy);
865
			Assert.fail("We expect exception because fieldunit.primaryCollector is of type person");
866
		} catch (MergeException e) {
867
			if (! e.getMessage().contains("Object can not be merged into new object as it is referenced in a way that does not allow merging")){
868
				Assert.fail("The exception should be the one thrown by DeduplicationHelper.reallocateByHolder(...)");
869
			}
870
			fieldUnit1.setPrimaryCollector(null);  //clean up for next test
871
		} catch (Exception e) {
872
			Assert.fail("Unhandled exception during merge");
873
		}
874
		Assert.assertEquals("Name1 should still have person1 as combination author", person1, name1.getCombinationAuthorship());
875

    
876
		//test collections
877
		team1.addTeamMember(person1);
878
		try {
879
			cdmGenericDao.merge(team2, person1, strategy);
880
			Assert.fail("We expect exception because fieldunit.primaryCollector is of type person");
881
		} catch (MergeException e) {
882
			if (! e.getMessage().contains("Object can not be merged into new object as it is referenced in a way that does not allow merging")){
883
				Assert.fail("The exception should be the one thrown by DeduplicationHelper.reallocateByHolder(...)");
884
			}
885
			team1.removeTeamMember(person1); //clean up for next test
886
		} catch (Exception e) {
887
			Assert.fail("Unhandled exception during merge");
888
		}
889
		Assert.assertEquals("Name1 should still have person1 as combination author", person1, name1.getCombinationAuthorship());
890

    
891
		//test successful merge
892
		cdmGenericDao.save(name1);
893
		cdmGenericDao.merge(team2, person1, strategy);
894
		Assert.assertEquals("Name1 should have team2 as combination author now", team2, name1.getCombinationAuthorship());
895

    
896
	}
897

    
898

    
899
	private void testMergeExceptions(CdmBase name1, CdmBase name2, CdmBase taxon,CdmBase zooName1) throws MergeException{
900
		//
901
		try {
902
			cdmGenericDao.merge(name1, null, null);
903
			Assert.fail("Merging of 2 objects one or both of them null must throw an exception");
904
		} catch (NullPointerException e) {
905
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
906
		}
907
		//
908
		try {
909
			cdmGenericDao.merge(null, name1, null);
910
			Assert.fail("Merging of 2 objects one or both of them null must throw an exception");
911
		} catch (NullPointerException e) {
912
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
913
		}
914
		//exceptions to be thrown
915
		try {
916
			cdmGenericDao.merge(name1, taxon, null);
917
			//this is not fully true anymore !! In certain cases merging of objects of different classes is allowed
918
			Assert.fail("Merging of 2 objects of different types must throw an exception");
919
		} catch (MergeException e) {
920
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
921
		}
922
		//next exception
923
		//for names this is not the case anymore
924
//		try {
925
//			cdmGenericDao.merge(name1, zooName1, null);
926
//			Assert.fail("Merging of 2 objects of different types must throw an exception");
927
//		} catch (MergeException e) {
928
//			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
929
//		}
930
	}
931

    
932
	@Test
933
	public void findMatching(){
934
		IBook book1 = ReferenceFactory.newBook();
935
		IBook book2 = ReferenceFactory.newBook();
936
		IBook book3 = ReferenceFactory.newBook();
937

    
938
		String title1 = "title1";
939
		String title2 = "title2";
940
		book1.setTitle(title1);
941
		book2.setTitle(title2);
942
		book3.setTitle(title1);
943

    
944
		cdmGenericDao.saveOrUpdate((Reference)book1);
945
		cdmGenericDao.saveOrUpdate((Reference)book2);
946
		cdmGenericDao.saveOrUpdate((Reference)book3);
947

    
948
		IMatchStrategy matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
949

    
950
		try {
951
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
952
			Assert.assertNotNull("Resultlist must not be null", matchResult);
953
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
954
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
955

    
956
			book1.setDatePublished(TimePeriod.NewInstance(1999, 2002));
957
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
958
			Assert.assertTrue("Resultlist must have no entries", matchResult.isEmpty());
959

    
960
			book3.setDatePublished(TimePeriod.NewInstance(1999));
961
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
962
			Assert.assertTrue("Resultlist must have no entries", matchResult.isEmpty());
963

    
964
			book3.setDatePublished(TimePeriod.NewInstance(1999,2002));
965
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
966
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
967
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
968

    
969
			//BookSection
970
			IBookSection section1 = ReferenceFactory.newBookSection();
971
			section1.setInBook(book1);
972
			section1.setTitle("SecTitle");
973
			section1.setPages("22-33");
974
			IBookSection section2 = ReferenceFactory.newBookSection();
975
			section2.setInBook(book2);
976
			section2.setTitle("SecTitle");
977
			section2.setPages("22-33");
978
			IBookSection section3 = ReferenceFactory.newBookSection();
979
			section3.setInBook(book1);
980
			section3.setTitle("SecTitle");
981
			section3.setPages("22-33");
982
			cdmGenericDao.saveOrUpdate((Reference)section1);
983
			cdmGenericDao.saveOrUpdate((Reference)section2);
984
			cdmGenericDao.saveOrUpdate((Reference)section3);
985

    
986
			List<IBookSection> sectionResult = cdmGenericDao.findMatching(section3, null);
987
			Assert.assertEquals("Resultlist must have 1 entries", 1, sectionResult.size());
988
			Assert.assertSame("Resultlist entry must be section1", section1, sectionResult.get(0));
989

    
990
			section2.setInBook(book2 = (IBook)book1.clone());
991
			cdmGenericDao.saveOrUpdate((Reference)book2);
992
			cdmGenericDao.saveOrUpdate((Reference)book1);
993
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
994
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
995
			sectionResult = cdmGenericDao.findMatching(section3, null);
996
			Assert.assertEquals("Resultlist must have 1 entries", 2, sectionResult.size());
997

    
998

    
999
			Person person1 = Person.NewTitledInstance("person");
1000
			Person person2 = Person.NewTitledInstance("person");
1001
			Person person3 = Person.NewTitledInstance("person");
1002

    
1003
			person1.setPrefix("pre1");
1004
			person2.setPrefix("pre2");
1005
			person3.setPrefix("pre3");
1006

    
1007
//			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1008
//			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1009

    
1010
			book1.setAuthorship(person1);
1011
			book2.setAuthorship(person1);
1012
			book3.setAuthorship(person1);
1013

    
1014
			boolean m = matchStrategy.invoke(book1, book3);
1015
			boolean m2 = matchStrategy.invoke(book2, book3);
1016

    
1017
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1018
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1019

    
1020
			book2.setAuthorship(person2);
1021
			book3.setAuthorship(person3);
1022
			matchResult = cdmGenericDao.findMatching(book3, null);
1023
			Assert.assertEquals("Resultlist must have no entries", 0, matchResult.size());
1024

    
1025
			person3.setPrefix("pre1");
1026
			matchResult = cdmGenericDao.findMatching(book3, null);
1027
			Assert.assertEquals("Resultlist must have 1 entry", 1, matchResult.size());
1028
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
1029

    
1030
		} catch (MatchException e) {
1031
			Assert.fail("Find match must not throw Exception: " + e.getMessage());
1032
			e.printStackTrace();
1033
		}
1034

    
1035
	}
1036

    
1037

    
1038
	@Test
1039
	public void findMatchingCache(){
1040
		IBook book1 = ReferenceFactory.newBook();
1041
		Team team1 = Team.NewInstance();
1042
		Team team2 = Team.NewInstance();
1043
		team1.setTitleCache("Team1", true);
1044
		team2.setTitleCache("Team1", true);
1045

    
1046
		book1.setTitle("Title1");
1047
		book1.setEdition("Edition1");
1048
		book1.setAuthorship(team1);
1049

    
1050

    
1051
		IBook book2 = (IBook) ((Reference)book1).clone();
1052
		IBook book3 = (IBook) ((Reference)book1).clone();
1053

    
1054
//		Assert.assertTrue("Cloned book should match", matchStrategy.invoke(book1, bookClone));
1055
//		book1.setTitleCache("cache1");
1056
//		Assert.assertFalse("Cached book should not match", matchStrategy.invoke(book1, bookClone));
1057
//
1058
//		bookClone.setTitleCache("cache1");
1059
//		Assert.assertTrue("Cached book with same cache should match", matchStrategy.invoke(book1, bookClone));
1060
//
1061
//		bookClone.setTitleCache("cache2");
1062
//		Assert.assertFalse("Cached book with differings caches should not match", matchStrategy.invoke(book1, bookClone));
1063
//		bookClone.setTitleCache("cache1"); //restore
1064
//
1065
//		bookClone.setEdition(null);
1066
//		Assert.assertTrue("Cached book with a defined and a null edition should match", matchStrategy.invoke(book1, bookClone));
1067

    
1068
		cdmGenericDao.saveOrUpdate((Reference)book1);
1069
		cdmGenericDao.saveOrUpdate((Reference)book2);
1070
		cdmGenericDao.saveOrUpdate((Reference)book3);
1071
		cdmGenericDao.saveOrUpdate(team1);
1072
		cdmGenericDao.saveOrUpdate(team2);
1073

    
1074

    
1075
		IMatchStrategy matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1076

    
1077
		try {
1078
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1079
			Assert.assertNotNull("Resultlist must not be null", matchResult);
1080
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1081
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1082
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1083

    
1084
			book1.setTitleCache("cache1", true);
1085
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1086
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1087
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1088

    
1089
			book2.setTitleCache("cache2", false);
1090
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1091
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1092
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1093

    
1094
			book2.setEdition(null);
1095
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1096
			Assert.assertEquals("Resultlist must have 0 entries", 0, matchResult.size());
1097

    
1098
			book3.setTitleCache("cache1", true);
1099
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1100
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1101
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1102

    
1103
			IMatchStrategy teamMatcher = DefaultMatchStrategy.NewInstance(Team.class);
1104
			boolean teamsMatch = teamMatcher.invoke(team1, team2);
1105
			Assert.assertTrue("Team1 and team2 should match" ,teamsMatch);
1106

    
1107
			book3.setAuthorship(team2);
1108
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1109
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1110
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1111

    
1112
			book3.setAuthorship(null);
1113
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1114
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1115
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1116

    
1117
			book2.setTitleCache(book3.getTitleCache(), true);
1118
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1119
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1120
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1121
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1122

    
1123
			team2.setTitleCache("team2", true);
1124
			teamsMatch = teamMatcher.invoke(team1, team2);
1125
			Assert.assertFalse("Team1 and team2 should not match" ,teamsMatch);
1126

    
1127
			book3.setAuthorship(team1);
1128
			book2.setAuthorship(team2);
1129
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1130
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1131
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1132

    
1133

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

    
1140
	//from original testing within class, can be removed if not needed anymore
1141
	private void test() {
1142
		SessionFactoryImpl factory = (SessionFactoryImpl)((CdmGenericDaoImpl)cdmGenericDao).getSession().getSessionFactory();
1143
		Type propType = factory.getReferencedPropertyType(BotanicalName.class.getCanonicalName(), "titleCache");
1144
		Map<?,?> collMetadata = factory.getAllCollectionMetadata();
1145
		Object roles = factory.getCollectionRolesByEntityParticipant("eu.etaxonomy.cdm.model.name.BotanicalName");
1146
		CollectionPersister collPersister;
1147
		try {
1148
			collPersister = factory.getCollectionPersister(TaxonNameBase.class.getCanonicalName()+".annotations");
1149
		} catch (MappingException e) {
1150
			// TODO Auto-generated catch block
1151
			e.printStackTrace();
1152
		}
1153
		Statistics statistics = factory.getStatistics();
1154
		Map<?,?> allClassMetadata = factory.getAllClassMetadata();
1155
		logger.debug("");
1156

    
1157
	}
1158

    
1159
	/**
1160
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getHqlResult(java.lang.String)}.
1161
	 */
1162
	@Test
1163
	public void testGetHqlResult() {
1164
		logger.warn("Not yet implemented");
1165
	}
1166

    
1167
    @Override
1168
    public void createTestDataSet() throws FileNotFoundException {}
1169
}
(4-4/11)