1
|
/**
|
2
|
*
|
3
|
*/
|
4
|
package eu.etaxonomy.cdm.persistence.dao.hibernate.common;
|
5
|
|
6
|
import java.lang.reflect.Field;
|
7
|
import java.lang.reflect.InvocationTargetException;
|
8
|
import java.lang.reflect.Method;
|
9
|
import java.util.ArrayList;
|
10
|
import java.util.Collection;
|
11
|
import java.util.HashSet;
|
12
|
import java.util.List;
|
13
|
import java.util.Set;
|
14
|
|
15
|
import javax.naming.Reference;
|
16
|
|
17
|
import org.apache.commons.lang.UnhandledException;
|
18
|
import org.apache.log4j.Logger;
|
19
|
import org.hibernate.MappingException;
|
20
|
import org.hibernate.Query;
|
21
|
import org.hibernate.Session;
|
22
|
import org.hibernate.internal.SessionFactoryImpl;
|
23
|
import org.hibernate.internal.SessionImpl;
|
24
|
import org.hibernate.metadata.ClassMetadata;
|
25
|
import org.hibernate.metadata.CollectionMetadata;
|
26
|
import org.hibernate.persister.collection.CollectionPersister;
|
27
|
import org.hibernate.persister.collection.OneToManyPersister;
|
28
|
import org.hibernate.persister.entity.AbstractEntityPersister;
|
29
|
import org.hibernate.type.AnyType;
|
30
|
import org.hibernate.type.CollectionType;
|
31
|
import org.hibernate.type.ComponentType;
|
32
|
import org.hibernate.type.EntityType;
|
33
|
import org.hibernate.type.SetType;
|
34
|
import org.hibernate.type.Type;
|
35
|
|
36
|
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
|
37
|
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
|
38
|
import eu.etaxonomy.cdm.model.common.AnnotatableEntity;
|
39
|
import eu.etaxonomy.cdm.model.common.Annotation;
|
40
|
import eu.etaxonomy.cdm.model.common.CdmBase;
|
41
|
import eu.etaxonomy.cdm.model.common.Extension;
|
42
|
import eu.etaxonomy.cdm.model.common.ICdmBase;
|
43
|
import eu.etaxonomy.cdm.model.common.IIntextReferencable;
|
44
|
import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
|
45
|
import eu.etaxonomy.cdm.model.common.Identifier;
|
46
|
import eu.etaxonomy.cdm.model.common.IntextReference;
|
47
|
import eu.etaxonomy.cdm.model.common.Marker;
|
48
|
import eu.etaxonomy.cdm.model.name.TaxonName;
|
49
|
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
|
50
|
import eu.etaxonomy.cdm.model.taxon.Taxon;
|
51
|
import eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl.ReferenceHolder;
|
52
|
import eu.etaxonomy.cdm.strategy.merge.ConvertMergeStrategy;
|
53
|
import eu.etaxonomy.cdm.strategy.merge.DefaultMergeStrategy;
|
54
|
import eu.etaxonomy.cdm.strategy.merge.IMergable;
|
55
|
import eu.etaxonomy.cdm.strategy.merge.IMergeStrategy;
|
56
|
import eu.etaxonomy.cdm.strategy.merge.MergeException;
|
57
|
|
58
|
/**
|
59
|
* @author a.mueller
|
60
|
*/
|
61
|
public class DeduplicationHelper {
|
62
|
private static final Logger logger = Logger.getLogger(DeduplicationHelper.class);
|
63
|
|
64
|
private final SessionImpl session;
|
65
|
private final CdmGenericDaoImpl genericDao;
|
66
|
|
67
|
protected DeduplicationHelper(SessionImpl session, CdmGenericDaoImpl genericDao){
|
68
|
this.session = session;
|
69
|
this.genericDao = genericDao;
|
70
|
}
|
71
|
|
72
|
public <T extends CdmBase> boolean isMergeable(T cdmBase1, T cdmBase2, IMergeStrategy mergeStrategy) {
|
73
|
|
74
|
if (mergeStrategy == null){
|
75
|
mergeStrategy = DefaultMergeStrategy.NewInstance(cdmBase1.getClass());
|
76
|
}
|
77
|
try {
|
78
|
checkMergeValid(cdmBase1, cdmBase2, mergeStrategy);
|
79
|
return true;
|
80
|
} catch (IllegalArgumentException e) {
|
81
|
return false;
|
82
|
} catch (NullPointerException e) {
|
83
|
return false;
|
84
|
}
|
85
|
}
|
86
|
|
87
|
|
88
|
public <T extends CdmBase> void merge(T cdmBase1, T cdmBase2, IMergeStrategy mergeStrategy) throws MergeException {
|
89
|
@SuppressWarnings("unchecked")
|
90
|
Class<T> clazz = (Class<T>)cdmBase1.getClass();
|
91
|
@SuppressWarnings("unchecked")
|
92
|
Class<T> clazz2 = (Class<T>)cdmBase2.getClass();
|
93
|
|
94
|
// SessionFactory sessionFactory = session.getSessionFactory();
|
95
|
if (mergeStrategy == null){
|
96
|
mergeStrategy = DefaultMergeStrategy.NewInstance(cdmBase1.getClass());
|
97
|
}
|
98
|
try {
|
99
|
//check null and types
|
100
|
checkMergeValid(cdmBase1, cdmBase2, mergeStrategy);
|
101
|
|
102
|
//merge objects
|
103
|
//externel impl
|
104
|
//internal impl
|
105
|
|
106
|
Set<ICdmBase> deleteSet = new HashSet<>();
|
107
|
Set<ICdmBase> cloneSet = new HashSet<>();
|
108
|
if (cdmBase1 instanceof IMergable){
|
109
|
IMergable mergable1 = (IMergable)cdmBase1;
|
110
|
IMergable mergable2 = (IMergable)cdmBase2;
|
111
|
deleteSet = mergeStrategy.invoke(mergable1, mergable2, cloneSet);
|
112
|
//session.saveOrUpdate(mergable1);
|
113
|
|
114
|
//session.flush();
|
115
|
//((IMergable)cdmBase1).mergeInto(cdmBase2, DefaultMergeStrategy.NewInstance(cdmBase1.getClass()));
|
116
|
}else{
|
117
|
//TODO should we better use clazz2 here?
|
118
|
mergeExternal(cdmBase1, cdmBase2, clazz, session);
|
119
|
}
|
120
|
|
121
|
|
122
|
if (cdmBase2.getId() > 0){
|
123
|
session.saveOrUpdate(cdmBase2);
|
124
|
session.flush();
|
125
|
//rearrange references pointing to cdmBase2 to cdmBase1 in future
|
126
|
reallocateReferences(cdmBase1, cdmBase2, clazz2, cloneSet);
|
127
|
}
|
128
|
|
129
|
//remove deleted objects
|
130
|
|
131
|
//session.delete(null, mergable2, true, null);
|
132
|
boolean deleteSecond = true;
|
133
|
if (mergeStrategy instanceof ConvertMergeStrategy) {
|
134
|
deleteSecond = ((ConvertMergeStrategy)mergeStrategy).isDeleteSecondObject();
|
135
|
}
|
136
|
if(deleteSecond){
|
137
|
session.delete(cdmBase2);
|
138
|
|
139
|
for (ICdmBase toBeDeleted : deleteSet){
|
140
|
logger.debug("Delete " + toBeDeleted);
|
141
|
if (toBeDeleted != cdmBase2){
|
142
|
session.delete(toBeDeleted);
|
143
|
|
144
|
}
|
145
|
}
|
146
|
}
|
147
|
|
148
|
//flush
|
149
|
session.flush();
|
150
|
|
151
|
} catch (Exception e) {
|
152
|
e.printStackTrace();
|
153
|
throw new MergeException(e);
|
154
|
}
|
155
|
}
|
156
|
|
157
|
/**
|
158
|
* Throws an exception if merge is not possible.
|
159
|
* @param cdmBase1
|
160
|
* @param cdmBase2
|
161
|
* @param strategy
|
162
|
* @throws IllegalArgumentException
|
163
|
* @throws NullPointerException
|
164
|
*/
|
165
|
|
166
|
private <T extends CdmBase> void checkMergeValid(T cdmBase1, T cdmBase2, IMergeStrategy strategy)throws IllegalArgumentException, NullPointerException{
|
167
|
if (cdmBase1 == null || cdmBase2 == null){
|
168
|
throw new NullPointerException("Merge arguments must not be (null)");
|
169
|
}
|
170
|
cdmBase1 = HibernateProxyHelper.deproxy(cdmBase1);
|
171
|
cdmBase2 = HibernateProxyHelper.deproxy(cdmBase2);
|
172
|
|
173
|
|
174
|
if (cdmBase1.getClass() != cdmBase2.getClass()){
|
175
|
boolean reallocationPossible = checkOnlyReallocationAllowed(cdmBase1.getClass(), cdmBase2.getClass());
|
176
|
if (! reallocationPossible){
|
177
|
String msg = "Merge not possible for objects of type %s and type %s";
|
178
|
msg = String.format(msg, cdmBase1.getClass().getSimpleName(), cdmBase2.getClass().getSimpleName());
|
179
|
throw new IllegalArgumentException(msg);
|
180
|
}else{
|
181
|
if (! checkInstancesMergeable(cdmBase1, cdmBase2, strategy)){
|
182
|
throw new IllegalArgumentException("Object can not be merged into new object as it is referenced in a way that does not allow merging");
|
183
|
}
|
184
|
}
|
185
|
}
|
186
|
}
|
187
|
|
188
|
@SuppressWarnings("unchecked")
|
189
|
private <T extends CdmBase> boolean checkInstancesMergeable(T cdmBase1, T cdmBase2, IMergeStrategy strategy){
|
190
|
Class<T> clazz2 = (Class<T>)cdmBase2.getClass();
|
191
|
//FIXME do we need to compute the cloneSet? See #reallocateReferences for comparison
|
192
|
//this is only a copy from there. Maybe we do not need the cloneSet at all here
|
193
|
Set<ICdmBase> cloneSet = new HashSet<ICdmBase>();
|
194
|
Set<ReferenceHolder> holderSet;
|
195
|
try {
|
196
|
boolean result = true;
|
197
|
holderSet = genericDao.getOrMakeHolderSet(clazz2);
|
198
|
for (ReferenceHolder refHolder: holderSet){
|
199
|
if (! reallocateByHolderPossible(cdmBase1, cdmBase2, refHolder, cloneSet)){
|
200
|
return false;
|
201
|
}
|
202
|
}
|
203
|
return result;
|
204
|
} catch (ClassNotFoundException e) {
|
205
|
return false;
|
206
|
} catch (NoSuchFieldException e) {
|
207
|
return false;
|
208
|
} catch (MergeException e) {
|
209
|
return false;
|
210
|
}
|
211
|
}
|
212
|
|
213
|
/**
|
214
|
* Checks if 2 can be merged and reallocation of referencing objects is allowed.
|
215
|
* This is <code>true</code> if
|
216
|
* classes are same or for some explicit cases like both
|
217
|
* inherit form {@link TeamOrPersonBase} or from {@link TaxonName}.
|
218
|
* Necessary condition is that both classes are mapped to the same table.
|
219
|
*
|
220
|
* @param class1
|
221
|
* @param class2
|
222
|
* @return true if mer
|
223
|
*/
|
224
|
private boolean checkOnlyReallocationAllowed(Class<? extends CdmBase> class1,
|
225
|
Class<? extends CdmBase> class2) {
|
226
|
if (class1 == class2){
|
227
|
return true;
|
228
|
}else{
|
229
|
if (classesAssignableFrom(TeamOrPersonBase.class, class1, class2)){
|
230
|
return true;
|
231
|
}else if (classesAssignableFrom(TaxonName.class, class1, class2)){
|
232
|
return true;
|
233
|
}else{
|
234
|
return false;
|
235
|
}
|
236
|
}
|
237
|
}
|
238
|
|
239
|
private boolean classesAssignableFrom(Class<? extends CdmBase> superClass,
|
240
|
Class<? extends CdmBase> class1, Class<? extends CdmBase> class2) {
|
241
|
return superClass.isAssignableFrom(class1) && superClass.isAssignableFrom(class2);
|
242
|
}
|
243
|
|
244
|
/**
|
245
|
* @param <T>
|
246
|
* @param cdmBase1
|
247
|
* @param cdmBase2
|
248
|
* @param clazz
|
249
|
* @param sessionFactory
|
250
|
* @throws MergeException
|
251
|
* @throws ClassNotFoundException
|
252
|
* @throws NoSuchFieldException
|
253
|
*/
|
254
|
private <T extends CdmBase> void mergeExternal(T cdmBase1, T cdmBase2, Class<T> clazz,
|
255
|
Session session) throws MergeException {
|
256
|
// handleAnnotations
|
257
|
logger.warn("Merge external");
|
258
|
handleAnnotationsEtc(cdmBase1, cdmBase2, session);
|
259
|
|
260
|
SessionFactoryImpl sessionFactory = (SessionFactoryImpl) session.getSessionFactory();
|
261
|
|
262
|
// Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata();
|
263
|
|
264
|
//TODO cast
|
265
|
getCollectionRoles(clazz, sessionFactory);
|
266
|
|
267
|
TaxonName name1 = TaxonNameFactory.NewBotanicalInstance(null);
|
268
|
name1.getTaxonBases();
|
269
|
|
270
|
Type propType = sessionFactory.getReferencedPropertyType(TaxonName.class.getCanonicalName(), "taxonBases");
|
271
|
// Map<?,?> collMetadata = sessionFactory.getAllCollectionMetadata();
|
272
|
//roles = sessionFactory.getCollectionRolesByEntityParticipant("eu.etaxonomy.cdm.model.name.BotanicalName");
|
273
|
CollectionPersister collPersister;
|
274
|
try {
|
275
|
collPersister = sessionFactory.getCollectionPersister(TaxonName.class.getCanonicalName()+".annotations");
|
276
|
} catch (MappingException e) {
|
277
|
// TODO Auto-generated catch block
|
278
|
e.printStackTrace();
|
279
|
}
|
280
|
// Statistics statistics = sessionFactory.getStatistics();
|
281
|
logger.debug("");
|
282
|
ClassMetadata taxonMetaData = sessionFactory.getClassMetadata(Taxon.class);
|
283
|
String ename = taxonMetaData.getEntityName();
|
284
|
try {
|
285
|
Reference ref = sessionFactory.getReference();
|
286
|
logger.debug("");
|
287
|
} catch (Exception e) {
|
288
|
// TODO Auto-generated catch block
|
289
|
e.printStackTrace();
|
290
|
}
|
291
|
|
292
|
//sessionFactory.get
|
293
|
ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(clazz);
|
294
|
Type[] propertyTypes = classMetadata.getPropertyTypes();
|
295
|
int propertyNr = 0;
|
296
|
for (Type propertyType: propertyTypes){
|
297
|
String propertyName = classMetadata.getPropertyNames()[propertyNr];
|
298
|
logger.debug(propertyName);
|
299
|
makeMergeProperty(cdmBase1, cdmBase2, propertyType, propertyName, sessionFactory, false);
|
300
|
propertyNr++;
|
301
|
}
|
302
|
Set<String> collectionRoles;
|
303
|
if (classMetadata instanceof AbstractEntityPersister){
|
304
|
AbstractEntityPersister persister = (AbstractEntityPersister)classMetadata;
|
305
|
String rootName = persister.getRootEntityName();
|
306
|
collectionRoles = sessionFactory.getCollectionRolesByEntityParticipant(rootName);
|
307
|
for (String collectionRole : collectionRoles){
|
308
|
CollectionMetadata collMetadata2 = sessionFactory.getCollectionMetadata(collectionRole);
|
309
|
String role = collMetadata2.getRole();
|
310
|
Type elType = collMetadata2.getElementType();
|
311
|
logger.debug(role);
|
312
|
}
|
313
|
}
|
314
|
}
|
315
|
|
316
|
|
317
|
/**
|
318
|
* @param <T>
|
319
|
* @param cdmBase1
|
320
|
* @param cdmBase2
|
321
|
* @param session
|
322
|
*/
|
323
|
private <T> void handleAnnotationsEtc(T cdmBase1, T cdmBase2, Session session) {
|
324
|
//when handling annotations and other elements linked via @Any an JDBC errors occurs
|
325
|
//due to the unique column constraint in the association table on the column referencing
|
326
|
//the annotation.
|
327
|
//For some reason not delete command is executed for the old collection
|
328
|
// Hibernate bug ??
|
329
|
session.flush(); //for debugging
|
330
|
if (cdmBase1 instanceof AnnotatableEntity){
|
331
|
copyAnnotatableExtensions(cdmBase1, cdmBase2, session);
|
332
|
}
|
333
|
if (cdmBase1 instanceof IdentifiableEntity){
|
334
|
copyIdentifiableExtensions(cdmBase1, cdmBase2, session);
|
335
|
}
|
336
|
|
337
|
session.saveOrUpdate(cdmBase1);
|
338
|
session.saveOrUpdate(cdmBase2);
|
339
|
session.flush();
|
340
|
}
|
341
|
|
342
|
|
343
|
/**
|
344
|
* Clones all annotations and markers of cdmBase2 and
|
345
|
* attaches the clones to cdmBase1.
|
346
|
* Finally removes all annotations and markers from cdmBase2.
|
347
|
* @param cdmBase1
|
348
|
* @param cdmBase2
|
349
|
* @param session
|
350
|
*/
|
351
|
private <T> void copyAnnotatableExtensions(T cdmBase1, T cdmBase2,
|
352
|
Session session) {
|
353
|
AnnotatableEntity annotatableEntity1 = (AnnotatableEntity)cdmBase1;
|
354
|
AnnotatableEntity annotatableEntity2 = (AnnotatableEntity)cdmBase2;
|
355
|
//annotations
|
356
|
List<Annotation> removeListAnnotation = new ArrayList<>();
|
357
|
for (Annotation annotation : annotatableEntity2.getAnnotations()){
|
358
|
Annotation clone = null;
|
359
|
try {
|
360
|
clone = (Annotation)annotation.clone();
|
361
|
} catch (CloneNotSupportedException e) {
|
362
|
e.printStackTrace();
|
363
|
}
|
364
|
annotatableEntity1.addAnnotation(clone);
|
365
|
removeListAnnotation.add(annotation);
|
366
|
}
|
367
|
for (Annotation annotation : removeListAnnotation){
|
368
|
annotatableEntity2.removeAnnotation(annotation);
|
369
|
session.delete(annotation);
|
370
|
}
|
371
|
|
372
|
//marker
|
373
|
List<Marker> removeListMarker = new ArrayList<>();
|
374
|
for (Marker marker : annotatableEntity2.getMarkers()){
|
375
|
Marker clone = null;
|
376
|
try {
|
377
|
clone = (Marker)marker.clone();
|
378
|
} catch (CloneNotSupportedException e) {
|
379
|
e.printStackTrace();
|
380
|
}
|
381
|
annotatableEntity1.addMarker(clone);
|
382
|
removeListMarker.add(marker);
|
383
|
}
|
384
|
for (Marker marker : removeListMarker){
|
385
|
annotatableEntity2.removeMarker(marker);
|
386
|
session.delete(marker);
|
387
|
}
|
388
|
}
|
389
|
|
390
|
/**
|
391
|
* Clones all extensions of cdmBase2 and
|
392
|
* attaches the clones to cdmBase1.
|
393
|
* Finally removes all annotations and markers from cdmBase2.
|
394
|
* @param cdmBase1
|
395
|
* @param cdmBase2
|
396
|
* @param session
|
397
|
*/
|
398
|
//TODO Why do we not handle credits, rights and sources here
|
399
|
private <T> void copyIdentifiableExtensions(T cdmBase1, T cdmBase2,
|
400
|
Session session) {
|
401
|
IdentifiableEntity<?> identifiableEntity1 = (IdentifiableEntity<?>)cdmBase1;
|
402
|
IdentifiableEntity<?> identifiableEntity2 = (IdentifiableEntity<?>)cdmBase2;
|
403
|
|
404
|
//extensions
|
405
|
List<Extension> removeListExtension = new ArrayList<>();
|
406
|
for (Extension changeObject : identifiableEntity2.getExtensions()){
|
407
|
try {
|
408
|
Extension clone = (Extension)changeObject.clone();
|
409
|
identifiableEntity1.addExtension(clone);
|
410
|
removeListExtension.add(changeObject);
|
411
|
} catch (CloneNotSupportedException e) {
|
412
|
throw new RuntimeException("Clone is not yet supported for class " + changeObject.getClass().getName() + " but should.");
|
413
|
}
|
414
|
}
|
415
|
for (Extension removeObject : removeListExtension){
|
416
|
identifiableEntity2.removeExtension(removeObject);
|
417
|
session.delete(removeObject);
|
418
|
}
|
419
|
|
420
|
//identifiers
|
421
|
List<Identifier<?>> removeListIdentifier = new ArrayList<>();
|
422
|
for (Identifier<?> changeObject : identifiableEntity2.getIdentifiers()){
|
423
|
try {
|
424
|
Identifier<?> clone = (Identifier<?>)changeObject.clone();
|
425
|
identifiableEntity1.addIdentifier(clone);
|
426
|
removeListIdentifier.add(changeObject);
|
427
|
} catch (CloneNotSupportedException e) {
|
428
|
throw new RuntimeException(e);
|
429
|
}
|
430
|
}
|
431
|
for (Identifier<?> removeObject : removeListIdentifier){
|
432
|
identifiableEntity2.removeIdentifier(removeObject);
|
433
|
session.delete(removeObject);
|
434
|
}
|
435
|
|
436
|
}
|
437
|
|
438
|
private void reallocateReferences(CdmBase cdmBase1, CdmBase cdmBase2, Class<? extends CdmBase> clazz, Set<ICdmBase> cloneSet){
|
439
|
try {
|
440
|
Set<ReferenceHolder> holderSet = genericDao.getOrMakeHolderSet(clazz);
|
441
|
for (ReferenceHolder refHolder: holderSet){
|
442
|
reallocateByHolder(cdmBase1, cdmBase2, refHolder, cloneSet);
|
443
|
}
|
444
|
return;
|
445
|
} catch (Exception e) {
|
446
|
throw new RuntimeException(e);
|
447
|
}
|
448
|
}
|
449
|
|
450
|
/**
|
451
|
* @param cdmBase1
|
452
|
* @param cdmBase2
|
453
|
* @param refHolder
|
454
|
* @throws MergeException
|
455
|
*/
|
456
|
private boolean reallocateByHolderPossible(CdmBase cdmBase1, CdmBase cdmBase2, ReferenceHolder refHolder, Set<ICdmBase> cloneSet) throws MergeException {
|
457
|
try {
|
458
|
if (refHolder.isCollection()){
|
459
|
return reallocateCollectionPossible(cdmBase1, cdmBase2, refHolder, cloneSet);
|
460
|
}else{
|
461
|
return reallocateSingleItemPossible(cdmBase1, cdmBase2, refHolder, cloneSet);
|
462
|
}
|
463
|
} catch (Exception e) {
|
464
|
throw new MergeException("Error during reallocation of references to merge object: " + cdmBase2, e);
|
465
|
}
|
466
|
}
|
467
|
|
468
|
/**
|
469
|
* @param cdmBase1
|
470
|
* @param cdmBase2
|
471
|
* @param refHolder
|
472
|
* @throws MergeException
|
473
|
*/
|
474
|
private void reallocateByHolder(CdmBase cdmBase1, CdmBase cdmBase2, ReferenceHolder refHolder, Set<ICdmBase> cloneSet) throws MergeException {
|
475
|
try {
|
476
|
if (refHolder.isCollection()){
|
477
|
reallocateCollection(cdmBase1, cdmBase2, refHolder, cloneSet);
|
478
|
}else{
|
479
|
reallocateSingleItem(cdmBase1, cdmBase2, refHolder, cloneSet);
|
480
|
}
|
481
|
} catch (Exception e) {
|
482
|
throw new MergeException("Error during reallocation of references to merge object: " + cdmBase2, e);
|
483
|
}
|
484
|
}
|
485
|
|
486
|
private boolean reallocateCollectionPossible(CdmBase cdmBase1, CdmBase cdmBase2,
|
487
|
ReferenceHolder refHolder, Set<ICdmBase> cloneSet) throws SecurityException, IllegalArgumentException {
|
488
|
Class<?> targetClass = refHolder.targetClass;
|
489
|
Class<?> clazz1 = cdmBase1.getClass();
|
490
|
if (! targetClass.isAssignableFrom(clazz1)){
|
491
|
//FIXME only do count or hasXXX, we do not need to instantiate objects here
|
492
|
List<CdmBase> referencingObjects = genericDao.getCdmBasesWithItemInCollection(refHolder.itemClass, refHolder.otherClass, refHolder.propertyName, cdmBase2, null);
|
493
|
if (! referencingObjects.isEmpty()){
|
494
|
return false;
|
495
|
}
|
496
|
}
|
497
|
return true;
|
498
|
}
|
499
|
|
500
|
/**
|
501
|
* @param cdmBase1
|
502
|
* @param cdmBase2
|
503
|
* @param refHolder
|
504
|
* @param cloneSet
|
505
|
* @throws MergeException
|
506
|
* @throws NoSuchFieldException
|
507
|
* @throws SecurityException
|
508
|
* @throws IllegalAccessException
|
509
|
* @throws IllegalArgumentException
|
510
|
* @throws InvocationTargetException
|
511
|
*/
|
512
|
private void reallocateCollection(CdmBase cdmBase1, CdmBase cdmBase2,
|
513
|
ReferenceHolder refHolder, Set<ICdmBase> cloneSet) throws MergeException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
|
514
|
List<CdmBase> list = genericDao.getCdmBasesWithItemInCollection(refHolder.itemClass, refHolder.otherClass, refHolder.propertyName, cdmBase2, null);
|
515
|
for (CdmBase referencingObject : list){
|
516
|
Field referencingField = getFieldRecursive(refHolder.otherClass, refHolder.propertyName);
|
517
|
referencingField.setAccessible(true);
|
518
|
Object collection = referencingField.get(referencingObject);
|
519
|
if (! (collection instanceof Collection)){
|
520
|
throw new MergeException ("Reallocation of collections for collection other than set and list not yet implemented");
|
521
|
}else if (collection instanceof List){
|
522
|
Method replaceMethod = DefaultMergeStrategy.getReplaceMethod(referencingField);
|
523
|
replaceMethod.invoke(referencingObject, cdmBase1, cdmBase2);
|
524
|
}else{
|
525
|
Method addMethod = DefaultMergeStrategy.getAddMethod(referencingField, false);
|
526
|
Method removeMethod = DefaultMergeStrategy.getAddMethod(referencingField, true);
|
527
|
addMethod.invoke(referencingObject, cdmBase1);
|
528
|
removeMethod.invoke(referencingObject, cdmBase2);
|
529
|
}
|
530
|
}
|
531
|
}
|
532
|
|
533
|
private boolean reallocateSingleItemPossible(CdmBase cdmBase1, CdmBase cdmBase2, ReferenceHolder refHolder, Set<ICdmBase> cloneSet) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
|
534
|
Class<?> targetClass = refHolder.targetClass;
|
535
|
Class<?> clazz1 = cdmBase1.getClass();
|
536
|
if (! targetClass.isAssignableFrom(clazz1)){
|
537
|
//FIXME only do count or hasXXX, we do not need to instantiate objects here
|
538
|
List<CdmBase> referencingObjects = genericDao.getCdmBasesByFieldAndClass(refHolder.otherClass, refHolder.propertyName, cdmBase2, null);
|
539
|
if (! referencingObjects.isEmpty()){
|
540
|
return false;
|
541
|
}
|
542
|
}
|
543
|
return true;
|
544
|
}
|
545
|
|
546
|
private void reallocateSingleItem(CdmBase cdmBase1, CdmBase cdmBase2, ReferenceHolder refHolder, Set<ICdmBase> cloneSet) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
|
547
|
List<CdmBase> referencingObjects = genericDao.getCdmBasesByFieldAndClass(refHolder.otherClass, refHolder.propertyName, cdmBase2, null);
|
548
|
for (CdmBase referencingObject : referencingObjects){
|
549
|
if (!cloneSet.contains(referencingObject)){
|
550
|
String className = refHolder.otherClass.getSimpleName();
|
551
|
String propertyName = refHolder.propertyName;
|
552
|
String hql = " UPDATE " + className + " c "
|
553
|
+ " SET c."+propertyName+" = :newValue "
|
554
|
+ " WHERE c.id = :id ";
|
555
|
Query query = session.createQuery(hql);
|
556
|
query.setEntity("newValue", cdmBase1);
|
557
|
query.setInteger("id",referencingObject.getId());
|
558
|
int rowCount = query.executeUpdate();
|
559
|
if (logger.isDebugEnabled()){logger.debug("Rows affected: " + rowCount);}
|
560
|
session.refresh(referencingObject);
|
561
|
if (refHolder.otherClass == IntextReference.class){
|
562
|
IntextReference intextRef = CdmBase.deproxy(referencingObject, IntextReference.class);
|
563
|
IIntextReferencable refEnt = intextRef.getReferencedEntity();
|
564
|
if (refEnt != null) {
|
565
|
String newText = refEnt.getText() == null? null: refEnt.getText().replace(cdmBase2.getUuid().toString(), cdmBase1.getUuid().toString());
|
566
|
refEnt.setText(newText);
|
567
|
session.saveOrUpdate(refEnt);
|
568
|
}
|
569
|
|
570
|
//TODO
|
571
|
/*
|
572
|
* UPDATE LanguageString
|
573
|
* SET text = Replace(text, cdmBase2.getUuuid(), cdmBase1.getUuid)
|
574
|
* WHERE id IN (SELECT * FROM IntextReference
|
575
|
*
|
576
|
*/
|
577
|
System.out.println("IntextReference found");
|
578
|
}
|
579
|
}
|
580
|
}
|
581
|
session.flush();
|
582
|
}
|
583
|
|
584
|
private Field getFieldRecursive(Class<?> clazz, String propertyName) throws NoSuchFieldException{
|
585
|
try {
|
586
|
return clazz.getDeclaredField(propertyName);
|
587
|
} catch (NoSuchFieldException e) {
|
588
|
Class<?> superClass = clazz.getSuperclass();
|
589
|
if (CdmBase.class.isAssignableFrom(superClass)){
|
590
|
return getFieldRecursive(superClass, propertyName);
|
591
|
}else{
|
592
|
throw e;
|
593
|
}
|
594
|
}
|
595
|
}
|
596
|
|
597
|
/**
|
598
|
* @throws NoSuchFieldException
|
599
|
* @throws SecurityException
|
600
|
* @throws IllegalAccessException
|
601
|
* @throws IllegalArgumentException
|
602
|
*
|
603
|
*/
|
604
|
private void reallocateSingleItem_Old(CdmBase cdmBase1, CdmBase cdmBase2, ReferenceHolder refHolder) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
|
605
|
List<CdmBase> referencingObjects = genericDao.getCdmBasesByFieldAndClass(refHolder.otherClass, refHolder.propertyName, cdmBase2, null);
|
606
|
for (CdmBase referencingObject : referencingObjects){
|
607
|
Field referencingField = refHolder.otherClass.getDeclaredField(refHolder.propertyName);
|
608
|
referencingField.setAccessible(true);
|
609
|
Object test = referencingField.get(referencingObject);
|
610
|
assert(test.equals(cdmBase2));
|
611
|
referencingField.set(referencingObject, cdmBase1);
|
612
|
}
|
613
|
}
|
614
|
|
615
|
|
616
|
|
617
|
|
618
|
/**
|
619
|
* @param <T>
|
620
|
* @param clazz
|
621
|
* @param sessionFactory
|
622
|
*/
|
623
|
private <T> Set<String> getCollectionRoles(Class<T> clazz,
|
624
|
SessionFactoryImpl sessionFactory) {
|
625
|
Set<String> collectionRoles = null;
|
626
|
ClassMetadata classMetaData = sessionFactory.getClassMetadata(clazz);
|
627
|
if (classMetaData instanceof AbstractEntityPersister){
|
628
|
AbstractEntityPersister persister = (AbstractEntityPersister)classMetaData;
|
629
|
String rootName = persister.getRootEntityName();
|
630
|
collectionRoles = sessionFactory.getCollectionRolesByEntityParticipant(rootName);
|
631
|
for (String collectionRole : collectionRoles){
|
632
|
CollectionMetadata collMetadata = sessionFactory.getCollectionMetadata(collectionRole);
|
633
|
CollectionPersister collPersister = sessionFactory.getCollectionPersister(collectionRole);
|
634
|
logger.debug("");
|
635
|
}
|
636
|
}else{
|
637
|
logger.warn("Class metadata is not of type AbstractEntityPersister");
|
638
|
throw new UnhandledException("Class metadata is not of type AbstractEntityPersister", null);
|
639
|
}
|
640
|
return collectionRoles;
|
641
|
}
|
642
|
|
643
|
|
644
|
private <T extends CdmBase> void makeMergeProperty(T cdmBase1, T cdmBase2, Type propertyType, String propertyName, SessionFactoryImpl sessionFactory, boolean isCollection) throws MergeException{
|
645
|
|
646
|
try {
|
647
|
Class<T> clazz = (Class<T>)cdmBase1.getClass();
|
648
|
if (CdmGenericDaoImpl.isNoDoType(propertyType)){
|
649
|
//do nothing
|
650
|
}else if (propertyType.isEntityType()){
|
651
|
//Field field = clazz.getField(propertyName);
|
652
|
EntityType entityType = (EntityType)propertyType;
|
653
|
String associatedEntityName = entityType.getAssociatedEntityName();
|
654
|
Class<?> entityClass = Class.forName(associatedEntityName);
|
655
|
// Type refPropType = sessionFactory.getReferencedPropertyType(entityClass.getCanonicalName(), propertyName);
|
656
|
Set<String> collectionRoles = getCollectionRoles(clazz, sessionFactory);
|
657
|
for (String collectionRole : collectionRoles){
|
658
|
CollectionMetadata collMetadata = sessionFactory.getCollectionMetadata(collectionRole);
|
659
|
String role = collMetadata.getRole();
|
660
|
logger.debug(role);
|
661
|
|
662
|
}
|
663
|
|
664
|
// if (entityClass.isInterface()){
|
665
|
// logger.debug("So ein interface");
|
666
|
// }
|
667
|
// if (entityClass.isAssignableFrom(clazz)){
|
668
|
// makeSingleProperty(referencedClass, entityClass, propertyName, cdmClass, result, isCollection);
|
669
|
// }
|
670
|
}else if (propertyType.isCollectionType()){
|
671
|
CollectionType collectionType = (CollectionType)propertyType;
|
672
|
String role = collectionType.getRole();
|
673
|
Type elType = collectionType.getElementType(sessionFactory);
|
674
|
String n = collectionType.getAssociatedEntityName(sessionFactory);
|
675
|
CollectionMetadata collMetadata = sessionFactory.getCollectionMetadata(role);
|
676
|
if (collMetadata instanceof OneToManyPersister){
|
677
|
OneToManyPersister oneManyPersister = (OneToManyPersister)collMetadata;
|
678
|
String className = oneManyPersister.getOwnerEntityName();
|
679
|
Class<?> myClass = Class.forName(className);
|
680
|
Field field = myClass.getDeclaredField(propertyName);
|
681
|
field.setAccessible(true);
|
682
|
try {
|
683
|
if (collectionType instanceof SetType){
|
684
|
Set<?> set2 = (Set<?>)field.get(cdmBase2);
|
685
|
Set<Object> set1 = (Set<Object>)field.get(cdmBase1);
|
686
|
for (Object obj2: set2){
|
687
|
set1.add(obj2);
|
688
|
}
|
689
|
}
|
690
|
} catch (IllegalArgumentException e) {
|
691
|
// TODO Auto-generated catch block
|
692
|
e.printStackTrace();
|
693
|
} catch (IllegalAccessException e) {
|
694
|
// TODO Auto-generated catch block
|
695
|
e.printStackTrace();
|
696
|
}
|
697
|
|
698
|
}
|
699
|
logger.debug("");
|
700
|
|
701
|
// makePropertyType(result, referencedClass, sessionFactory, cdmClass, elType, propertyName, true);
|
702
|
}else if (propertyType.isAnyType()){
|
703
|
AnyType anyType = (AnyType)propertyType;
|
704
|
Field field = clazz.getDeclaredField(propertyName);
|
705
|
Class returnType = field.getType();
|
706
|
// if (returnType.isInterface()){
|
707
|
// logger.debug("So ein interface");
|
708
|
// }
|
709
|
// if (returnType.isAssignableFrom(referencedClass)){
|
710
|
// makeSingleProperty(referencedClass, returnType, propertyName, cdmClass, result, isCollection);
|
711
|
// }
|
712
|
}else if (propertyType.isComponentType()){
|
713
|
ComponentType componentType = (ComponentType)propertyType;
|
714
|
Type[] subTypes = componentType.getSubtypes();
|
715
|
// Field field = cdmClass.getDeclaredField(propertyName);
|
716
|
// Class returnType = field.getType();
|
717
|
int propertyNr = 0;
|
718
|
for (Type subType: subTypes){
|
719
|
String subPropertyName = componentType.getPropertyNames()[propertyNr];
|
720
|
if (! CdmGenericDaoImpl.isNoDoType(subType)){
|
721
|
logger.warn("SubType not yet handled: " + subType);
|
722
|
}
|
723
|
// handlePropertyType(referencedCdmBase, result, referencedClass,
|
724
|
// sessionFactory, cdmClass, subType, subPropertyName, isCollection);
|
725
|
propertyNr++;
|
726
|
}
|
727
|
}else{
|
728
|
logger.warn("propertyType not yet handled: " + propertyType.getName());
|
729
|
}
|
730
|
//OLD:
|
731
|
// if (! type.isInterface()){
|
732
|
// if (referencedClass.isAssignableFrom(type)||
|
733
|
// type.isAssignableFrom(referencedClass) && CdmBase.class.isAssignableFrom(type)){
|
734
|
// handleSingleClass(referencedClass, type, field, cdmClass, result, referencedCdmBase, false);
|
735
|
// }
|
736
|
// //interface
|
737
|
// }else if (type.isAssignableFrom(referencedClass)){
|
738
|
// handleSingleClass(referencedClass, type, field, cdmClass, result, referencedCdmBase, false);
|
739
|
} catch (Exception e) {
|
740
|
throw new MergeException(e);
|
741
|
}
|
742
|
}
|
743
|
|
744
|
|
745
|
|
746
|
}
|