Project

General

Profile

Download (46.2 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.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.TaxonNameFactory;
134
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
135
import eu.etaxonomy.cdm.model.name.ViralName;
136
import eu.etaxonomy.cdm.model.name.ZoologicalName;
137
import eu.etaxonomy.cdm.model.occurrence.Collection;
138
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
139
import eu.etaxonomy.cdm.model.occurrence.DerivationEventType;
140
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
141
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
142
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
143
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
144
import eu.etaxonomy.cdm.model.occurrence.PreservationMethod;
145
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
146
import eu.etaxonomy.cdm.model.reference.IBook;
147
import eu.etaxonomy.cdm.model.reference.IBookSection;
148
import eu.etaxonomy.cdm.model.reference.Reference;
149
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
150
import eu.etaxonomy.cdm.model.taxon.Classification;
151
import eu.etaxonomy.cdm.model.taxon.Synonym;
152
import eu.etaxonomy.cdm.model.taxon.SynonymType;
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
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
172

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

    
180
	@SpringBeanByType
181
	private ICdmGenericDao cdmGenericDao;
182

    
183
	@SpringBeanByType
184
	private ITaxonDao taxonDao;
185

    
186
	@SpringBeanByType
187
	private IOccurrenceDao occurrenceDao;
188

    
189
	@SpringBeanByType
190
	private ITaxonNameDao nameDao;
191

    
192
	@SpringBeanByType
193
	private IAgentDao agentDao;
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
				TaxonNameBase.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<Class<?>>();
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 = TaxonNameBase.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
		BotanicalName 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(taxonNameBase, 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
		BotanicalName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
496
		name1.setTitleCache("BotanicalName1", true);
497

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

    
501
		ZoologicalName 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
		BotanicalName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
626
		name1.setTitleCache("BotanicalName1", true);
627

    
628
		BotanicalName name2 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
629
		name2.setTitleCache("BotanicalName2", true);
630

    
631
		BotanicalName 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
		BotanicalName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
663
		name1.setTitleCache("BotanicalName1", true);
664

    
665
		BotanicalName 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

    
823

    
824
	/**
825
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#merge(CdmBase, CdmBase)}.
826
	 * @throws MergeException
827
	 */
828
	@Test
829
	public void testReallocatePersonTeam() throws MergeException {
830

    
831
		BotanicalName name1 = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
832
		name1.setTitleCache("BotanicalName1", true);
833

    
834
		IBook book1 = ReferenceFactory.newBook();
835

    
836
		Team team1 = Team.NewInstance();
837
		Team team2 = Team.NewInstance();
838
		team1.setTitleCache("team1", true);
839
		team2.setTitleCache("team2", true);
840

    
841
		Person person1 = Person.NewTitledInstance("person1");
842
		Person person2 = Person.NewTitledInstance("person2");
843

    
844
		team1.setNomenclaturalTitle("T.1");
845
		String street1 = "Strasse1";
846
		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)));
847
		team2.setContact(Contact.NewInstance("Street2", null, "London", null, null, null, null, "874599873", null, null, null));
848
		String street3 = "Street3";
849
		team2.addAddress(street3, null, null, null, null, null, Point.NewInstance(1.1, 2.2, null, 4));
850
		String emailAddress1 = "Email1";
851
		team1.addEmailAddress(emailAddress1);
852

    
853

    
854
		//FIXME
855
//		team2.addTeamMember(person1);
856
		team2.addTeamMember(person2);
857
		String emailAddress2 = "Email2";
858
		team2.addEmailAddress(emailAddress2);
859

    
860
		Credit credit1 = Credit.NewInstance(team2, "credit1");
861
		book1.addCredit(credit1);
862

    
863
		agentDao.save(team1);
864
		agentDao.save(team2);
865
		agentDao.save(person1);
866
		agentDao.save(person2);
867

    
868
		cdmGenericDao.save((Reference)book1);
869

    
870
		//starting condition
871
		name1.setCombinationAuthorship(person1);
872
		Assert.assertEquals("Name1 should have person1 as combination author", person1, name1.getCombinationAuthorship());
873

    
874
		DefaultMergeStrategy strategy = DefaultMergeStrategy.NewInstance(TeamOrPersonBase.class);
875
//		strategy.setOnlyReallocateLinks(true);
876

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

    
893
		//test collections
894
		team1.addTeamMember(person1);
895
		try {
896
			cdmGenericDao.merge(team2, person1, strategy);
897
			Assert.fail("We expect exception because fieldunit.primaryCollector is of type person");
898
		} catch (MergeException e) {
899
			if (! e.getMessage().contains("Object can not be merged into new object as it is referenced in a way that does not allow merging")){
900
				Assert.fail("The exception should be the one thrown by DeduplicationHelper.reallocateByHolder(...)");
901
			}
902
			team1.removeTeamMember(person1); //clean up for next test
903
		} catch (Exception e) {
904
			Assert.fail("Unhandled exception during merge");
905
		}
906
		Assert.assertEquals("Name1 should still have person1 as combination author", person1, name1.getCombinationAuthorship());
907

    
908
		//test successful merge
909
		cdmGenericDao.save(name1);
910
		cdmGenericDao.merge(team2, person1, strategy);
911
		Assert.assertEquals("Name1 should have team2 as combination author now", team2, name1.getCombinationAuthorship());
912

    
913
	}
914

    
915

    
916
	private void testMergeExceptions(CdmBase name1, CdmBase name2, CdmBase taxon,CdmBase zooName1) throws MergeException{
917
		//
918
		try {
919
			cdmGenericDao.merge(name1, null, null);
920
			Assert.fail("Merging of 2 objects one or both of them null must throw an exception");
921
		} catch (NullPointerException e) {
922
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
923
		}
924
		//
925
		try {
926
			cdmGenericDao.merge(null, name1, null);
927
			Assert.fail("Merging of 2 objects one or both of them null must throw an exception");
928
		} catch (NullPointerException e) {
929
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
930
		}
931
		//exceptions to be thrown
932
		try {
933
			cdmGenericDao.merge(name1, taxon, null);
934
			//this is not fully true anymore !! In certain cases merging of objects of different classes is allowed
935
			Assert.fail("Merging of 2 objects of different types must throw an exception");
936
		} catch (MergeException e) {
937
			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
938
		}
939
		//next exception
940
		//for names this is not the case anymore
941
//		try {
942
//			cdmGenericDao.merge(name1, zooName1, null);
943
//			Assert.fail("Merging of 2 objects of different types must throw an exception");
944
//		} catch (MergeException e) {
945
//			Assert.assertTrue("Merging of 2 objects of different types must throw an exception", true);
946
//		}
947
	}
948

    
949
	@Test
950
	public void findMatching(){
951
		IBook book1 = ReferenceFactory.newBook();
952
		IBook book2 = ReferenceFactory.newBook();
953
		IBook book3 = ReferenceFactory.newBook();
954

    
955
		String title1 = "title1";
956
		String title2 = "title2";
957
		book1.setTitle(title1);
958
		book2.setTitle(title2);
959
		book3.setTitle(title1);
960

    
961
		cdmGenericDao.saveOrUpdate((Reference)book1);
962
		cdmGenericDao.saveOrUpdate((Reference)book2);
963
		cdmGenericDao.saveOrUpdate((Reference)book3);
964

    
965
		IMatchStrategy matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
966

    
967
		try {
968
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
969
			Assert.assertNotNull("Resultlist must not be null", matchResult);
970
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
971
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
972

    
973
			book1.setDatePublished(TimePeriod.NewInstance(1999, 2002));
974
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
975
			Assert.assertTrue("Resultlist must have no entries", matchResult.isEmpty());
976

    
977
			book3.setDatePublished(TimePeriod.NewInstance(1999));
978
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
979
			Assert.assertTrue("Resultlist must have no entries", matchResult.isEmpty());
980

    
981
			book3.setDatePublished(TimePeriod.NewInstance(1999,2002));
982
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
983
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
984
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
985

    
986
			//BookSection
987
			IBookSection section1 = ReferenceFactory.newBookSection();
988
			section1.setInBook(book1);
989
			section1.setTitle("SecTitle");
990
			section1.setPages("22-33");
991
			IBookSection section2 = ReferenceFactory.newBookSection();
992
			section2.setInBook(book2);
993
			section2.setTitle("SecTitle");
994
			section2.setPages("22-33");
995
			IBookSection section3 = ReferenceFactory.newBookSection();
996
			section3.setInBook(book1);
997
			section3.setTitle("SecTitle");
998
			section3.setPages("22-33");
999
			cdmGenericDao.saveOrUpdate((Reference)section1);
1000
			cdmGenericDao.saveOrUpdate((Reference)section2);
1001
			cdmGenericDao.saveOrUpdate((Reference)section3);
1002

    
1003
			List<IBookSection> sectionResult = cdmGenericDao.findMatching(section3, null);
1004
			Assert.assertEquals("Resultlist must have 1 entries", 1, sectionResult.size());
1005
			Assert.assertSame("Resultlist entry must be section1", section1, sectionResult.get(0));
1006

    
1007
			section2.setInBook(book2 = (IBook)book1.clone());
1008
			cdmGenericDao.saveOrUpdate((Reference)book2);
1009
			cdmGenericDao.saveOrUpdate((Reference)book1);
1010
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1011
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1012
			sectionResult = cdmGenericDao.findMatching(section3, null);
1013
			Assert.assertEquals("Resultlist must have 1 entries", 2, sectionResult.size());
1014

    
1015

    
1016
			Person person1 = Person.NewTitledInstance("person");
1017
			Person person2 = Person.NewTitledInstance("person");
1018
			Person person3 = Person.NewTitledInstance("person");
1019

    
1020
			person1.setPrefix("pre1");
1021
			person2.setPrefix("pre2");
1022
			person3.setPrefix("pre3");
1023

    
1024
//			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1025
//			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1026

    
1027
			book1.setAuthorship(person1);
1028
			book2.setAuthorship(person1);
1029
			book3.setAuthorship(person1);
1030

    
1031
			boolean m = matchStrategy.invoke(book1, book3);
1032
			boolean m2 = matchStrategy.invoke(book2, book3);
1033

    
1034
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1035
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1036

    
1037
			book2.setAuthorship(person2);
1038
			book3.setAuthorship(person3);
1039
			matchResult = cdmGenericDao.findMatching(book3, null);
1040
			Assert.assertEquals("Resultlist must have no entries", 0, matchResult.size());
1041

    
1042
			person3.setPrefix("pre1");
1043
			matchResult = cdmGenericDao.findMatching(book3, null);
1044
			Assert.assertEquals("Resultlist must have 1 entry", 1, matchResult.size());
1045
			Assert.assertSame("Resultlist entry must be book 1", book1, matchResult.get(0));
1046

    
1047
		} catch (MatchException e) {
1048
			Assert.fail("Find match must not throw Exception: " + e.getMessage());
1049
			e.printStackTrace();
1050
		}
1051

    
1052
	}
1053

    
1054

    
1055
	@Test
1056
	public void findMatchingCache(){
1057
		IBook book1 = ReferenceFactory.newBook();
1058
		Team team1 = Team.NewInstance();
1059
		Team team2 = Team.NewInstance();
1060
		team1.setTitleCache("Team1", true);
1061
		team2.setTitleCache("Team1", true);
1062

    
1063
		book1.setTitle("Title1");
1064
		book1.setEdition("Edition1");
1065
		book1.setAuthorship(team1);
1066

    
1067

    
1068
		IBook book2 = (IBook) ((Reference)book1).clone();
1069
		IBook book3 = (IBook) ((Reference)book1).clone();
1070

    
1071
//		Assert.assertTrue("Cloned book should match", matchStrategy.invoke(book1, bookClone));
1072
//		book1.setTitleCache("cache1");
1073
//		Assert.assertFalse("Cached book should not match", matchStrategy.invoke(book1, bookClone));
1074
//
1075
//		bookClone.setTitleCache("cache1");
1076
//		Assert.assertTrue("Cached book with same cache should match", matchStrategy.invoke(book1, bookClone));
1077
//
1078
//		bookClone.setTitleCache("cache2");
1079
//		Assert.assertFalse("Cached book with differings caches should not match", matchStrategy.invoke(book1, bookClone));
1080
//		bookClone.setTitleCache("cache1"); //restore
1081
//
1082
//		bookClone.setEdition(null);
1083
//		Assert.assertTrue("Cached book with a defined and a null edition should match", matchStrategy.invoke(book1, bookClone));
1084

    
1085
		cdmGenericDao.saveOrUpdate((Reference)book1);
1086
		cdmGenericDao.saveOrUpdate((Reference)book2);
1087
		cdmGenericDao.saveOrUpdate((Reference)book3);
1088
		cdmGenericDao.saveOrUpdate(team1);
1089
		cdmGenericDao.saveOrUpdate(team2);
1090

    
1091

    
1092
		IMatchStrategy matchStrategy = DefaultMatchStrategy.NewInstance(Reference.class);
1093

    
1094
		try {
1095
			List<IBook> matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1096
			Assert.assertNotNull("Resultlist must not be null", matchResult);
1097
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1098
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1099
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1100

    
1101
			book1.setTitleCache("cache1", true);
1102
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1103
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1104
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1105

    
1106
			book2.setTitleCache("cache2", false);
1107
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1108
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1109
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1110

    
1111
			book2.setEdition(null);
1112
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1113
			Assert.assertEquals("Resultlist must have 0 entries", 0, matchResult.size());
1114

    
1115
			book3.setTitleCache("cache1", true);
1116
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1117
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1118
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1119

    
1120
			IMatchStrategy teamMatcher = DefaultMatchStrategy.NewInstance(Team.class);
1121
			boolean teamsMatch = teamMatcher.invoke(team1, team2);
1122
			Assert.assertTrue("Team1 and team2 should match" ,teamsMatch);
1123

    
1124
			book3.setAuthorship(team2);
1125
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1126
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1127
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1128

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

    
1134
			book2.setTitleCache(book3.getTitleCache(), true);
1135
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1136
			Assert.assertEquals("Resultlist must have 2 entries", 2, matchResult.size());
1137
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1138
			Assert.assertTrue("Resultlist must contain book 2", matchResult.contains(book2));
1139

    
1140
			team2.setTitleCache("team2", true);
1141
			teamsMatch = teamMatcher.invoke(team1, team2);
1142
			Assert.assertFalse("Team1 and team2 should not match" ,teamsMatch);
1143

    
1144
			book3.setAuthorship(team1);
1145
			book2.setAuthorship(team2);
1146
			matchResult = cdmGenericDao.findMatching(book3, matchStrategy);
1147
			Assert.assertEquals("Resultlist must have 1 entries", 1, matchResult.size());
1148
			Assert.assertTrue("Resultlist must contain book 1", matchResult.contains(book1));
1149

    
1150

    
1151
		} catch (MatchException e) {
1152
			Assert.fail("Find match must not throw Exception: " + e.getMessage());
1153
			e.printStackTrace();
1154
		}
1155
	}
1156

    
1157
	//from original testing within class, can be removed if not needed anymore
1158
	private void test() {
1159
		SessionFactoryImpl factory = (SessionFactoryImpl)((CdmGenericDaoImpl)cdmGenericDao).getSession().getSessionFactory();
1160
		Type propType = factory.getReferencedPropertyType(BotanicalName.class.getCanonicalName(), "titleCache");
1161
		Map<?,?> collMetadata = factory.getAllCollectionMetadata();
1162
		Object roles = factory.getCollectionRolesByEntityParticipant("eu.etaxonomy.cdm.model.name.BotanicalName");
1163
		CollectionPersister collPersister;
1164
		try {
1165
			collPersister = factory.getCollectionPersister(TaxonNameBase.class.getCanonicalName()+".annotations");
1166
		} catch (MappingException e) {
1167
			// TODO Auto-generated catch block
1168
			e.printStackTrace();
1169
		}
1170
		Statistics statistics = factory.getStatistics();
1171
		Map<?,?> allClassMetadata = factory.getAllClassMetadata();
1172
		logger.debug("");
1173

    
1174
	}
1175

    
1176
	/**
1177
	 * Test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getHqlResult(java.lang.String)}.
1178
	 */
1179
	@Test
1180
	public void testGetHqlResult() {
1181
		logger.warn("Not yet implemented");
1182
	}
1183

    
1184
    @Override
1185
    public void createTestDataSet() throws FileNotFoundException {}
1186
}
(4-4/11)