-
Notifications
You must be signed in to change notification settings - Fork 14
/
CloneBuilderImpl.java
327 lines (294 loc) · 13.1 KB
/
CloneBuilderImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/**
* Copyright (C) 2019 Czech Technical University in Prague
* <p>
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.jopa.sessions;
import cz.cvut.kbss.jopa.adapters.IndirectCollection;
import cz.cvut.kbss.jopa.exceptions.OWLPersistenceException;
import cz.cvut.kbss.jopa.model.descriptors.Descriptor;
import cz.cvut.kbss.jopa.model.metamodel.EntityType;
import cz.cvut.kbss.jopa.model.metamodel.FieldSpecification;
import cz.cvut.kbss.jopa.model.metamodel.Identifier;
import cz.cvut.kbss.jopa.model.metamodel.Metamodel;
import cz.cvut.kbss.jopa.utils.EntityPropertiesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.*;
public class CloneBuilderImpl implements CloneBuilder {
private static final Logger LOG = LoggerFactory.getLogger(CloneBuilderImpl.class);
private static final Set<Class<?>> IMMUTABLE_TYPES = getImmutableTypes();
// Contains entities that are already cloned, so that we don't clone them again
private final RepositoryMap visitedEntities;
private final Builders builders;
private final UnitOfWorkImpl uow;
public CloneBuilderImpl(UnitOfWorkImpl uow) {
this.uow = uow;
this.visitedEntities = new RepositoryMap();
this.builders = new Builders();
}
@Override
public Object buildClone(Object original, CloneConfiguration cloneConfiguration) {
Objects.requireNonNull(original);
Objects.requireNonNull(cloneConfiguration);
// TODO Replace with a lambda after migration to new SLF4J
LOG.trace("Cloning object {}.", stringify(original));
return buildCloneImpl(null, null, original, cloneConfiguration);
}
@Override
public Object buildClone(Object cloneOwner, Field clonedField, Object original, Descriptor descriptor) {
if (cloneOwner == null || original == null || descriptor == null) {
throw new NullPointerException();
}
// TODO Replace with a lambda after migration to new SLF4J
LOG.trace("Cloning object {} with owner {}", stringify(original), stringify(cloneOwner));
return buildCloneImpl(cloneOwner, clonedField, original, new CloneConfiguration(descriptor));
}
private Object buildCloneImpl(Object cloneOwner, Field clonedField, Object original,
CloneConfiguration cloneConfiguration) {
assert original != null;
if (isOriginalInUoW(original)) {
return uow.getCloneForOriginal(original);
}
final Class<?> cls = original.getClass();
final boolean managed = isTypeManaged(cls);
final Descriptor descriptor = cloneConfiguration.getDescriptor();
if (managed) {
final Object visitedClone = getVisitedEntity(descriptor, original);
if (visitedClone != null) {
return visitedClone;
}
}
final AbstractInstanceBuilder builder = getInstanceBuilder(original);
Object clone = builder.buildClone(cloneOwner, clonedField, original, cloneConfiguration);
if (managed) {
// Register visited object before populating attributes to prevent endless cloning cycles
putVisitedEntity(descriptor, original, clone);
}
if (!builder.populatesAttributes() && !isImmutable(cls)) {
populateAttributes(original, clone, cloneConfiguration);
}
return clone;
}
/**
* Clone all the attributes of the original and set the clone values. This also means cloning any relationships and
* their targets.
*/
private void populateAttributes(Object original, Object clone, CloneConfiguration configuration) {
final Class<?> originalClass = original.getClass();
final EntityType<?> et = getMetamodel().entity(originalClass);
// Ensure the identifier is cloned before any other attributes
// This prevents problems where circular references between entities lead to clones being registered with null identifier
cloneIdentifier(original, clone, et);
for (FieldSpecification<?, ?> fs : et.getFieldSpecifications()) {
if (fs == et.getIdentifier()) {
continue; // Already cloned
}
final Field f = fs.getJavaField();
final Object origVal = EntityPropertiesUtils.getFieldValue(f, original);
if (origVal == null) {
continue;
}
final Class<?> origValueClass = origVal.getClass();
Object clonedValue;
if (isImmutable(origValueClass)) {
// The field is an immutable type
clonedValue = origVal;
} else if (origVal instanceof Collection || origVal instanceof Map) {
final Descriptor fieldDescriptor = getFieldDescriptor(f, originalClass, configuration.getDescriptor());
// Collection or Map
clonedValue = getInstanceBuilder(origVal).buildClone(clone, f, origVal,
new CloneConfiguration(fieldDescriptor, configuration.getPostRegister()));
} else {
// Otherwise we have a relationship and we need to clone its target as well
if (isOriginalInUoW(origVal)) {
// If the reference is already managed
clonedValue = uow.getCloneForOriginal(origVal);
} else {
if (isTypeManaged(origValueClass)) {
final Descriptor fieldDescriptor =
getFieldDescriptor(f, originalClass, configuration.getDescriptor());
clonedValue = getVisitedEntity(configuration.getDescriptor(), origVal);
if (clonedValue == null) {
clonedValue = uow.registerExistingObject(origVal, fieldDescriptor,
configuration.getPostRegister());
}
} else {
clonedValue = buildClone(origVal, configuration);
}
}
}
EntityPropertiesUtils.setFieldValue(f, clone, clonedValue);
}
}
private static void cloneIdentifier(Object original, Object clone, EntityType<?> et) {
final Identifier identifier = et.getIdentifier();
final Object idValue = EntityPropertiesUtils.getFieldValue(identifier.getJavaField(), original);
EntityPropertiesUtils.setFieldValue(identifier.getJavaField(), clone, idValue);
}
private Descriptor getFieldDescriptor(Field field, Class<?> entityClass, Descriptor entityDescriptor) {
final EntityType<?> et = getMetamodel().entity(entityClass);
final FieldSpecification<?, ?> fieldSpec = et.getFieldSpecification(field.getName());
return entityDescriptor.getAttributeDescriptor(fieldSpec);
}
/**
* Check if the given class is an immutable type.
* <p>
* Objects of immutable types do not have to be cloned, because they cannot be modified.
* <p>
* Note that this method does not do any sophisticated verification, it just checks if the specified class
* corresponds to a small set of predefined conditions, e.g. primitive class, enum, String.
*
* @param cls the class to check
* @return Whether the class represents immutable objects
*/
static boolean isImmutable(Class<?> cls) {
return cls.isPrimitive() || cls.isEnum() || IMMUTABLE_TYPES.contains(cls);
}
/**
* Checks if the specified object is immutable.
* <p>
* {@code null} is considered immutable, otherwise, this method just calls {@link #isImmutable(Class)}.
*
* @param object The instance to check
* @return immutability status
*/
static boolean isImmutable(Object object) {
return object == null || isImmutable(object.getClass());
}
@Override
public void mergeChanges(ObjectChangeSet changeSet) {
final Object original = changeSet.getChangedObject();
try {
for (ChangeRecord change : changeSet.getChanges()) {
Field f = change.getAttribute().getJavaField();
if (isImmutable(f.getType())) {
EntityPropertiesUtils.setFieldValue(f, original, change.getNewValue());
continue;
}
Object origVal = EntityPropertiesUtils.getFieldValue(f, original);
Object newVal = change.getNewValue();
if (newVal == null) {
EntityPropertiesUtils.setFieldValue(f, original, null);
continue;
}
getInstanceBuilder(newVal).mergeChanges(f, original, origVal, newVal);
}
} catch (SecurityException e) {
throw new OWLPersistenceException(e);
}
}
private Object getVisitedEntity(Descriptor descriptor, Object original) {
assert descriptor != null;
assert original != null;
return visitedEntities.get(descriptor, original);
}
private void putVisitedEntity(Descriptor descriptor, Object original, Object clone) {
assert descriptor != null;
visitedEntities.add(descriptor, original, clone);
}
AbstractInstanceBuilder getInstanceBuilder(Object toClone) {
return builders.getBuilder(toClone);
}
boolean isTypeManaged(Class<?> cls) {
return uow.isEntityType(cls);
}
boolean isOriginalInUoW(Object original) {
return uow.containsOriginal(original);
}
Object getOriginal(Object clone) {
return uow.getOriginal(clone);
}
Metamodel getMetamodel() {
return uow.getMetamodel();
}
@Override
public void reset() {
visitedEntities.clear();
}
@Override
public void removeVisited(Object instance, Descriptor descriptor) {
visitedEntities.remove(descriptor, instance);
}
IndirectCollection<?> createIndirectCollection(Object c, Object owner, Field f) {
return uow.createIndirectCollection(c, owner, f);
}
/**
* Gets basic object info for logging.
* <p>
* This works around using {@link Object#toString()} for entities, which could inadvertently trigger lazy field
* fetching.
*
* @param object Object to stringify
* @return String info about the specified object
*/
private String stringify(Object object) {
assert object != null;
return isTypeManaged(object.getClass()) ?
object.getClass().getSimpleName() + "<" + EntityPropertiesUtils.getIdentifier(object, getMetamodel()) +
">" : object.toString();
}
private static Set<Class<?>> getImmutableTypes() {
HashSet<Class<?>> ret = new HashSet<>();
ret.add(Boolean.class);
ret.add(Character.class);
ret.add(Byte.class);
ret.add(Short.class);
ret.add(Integer.class);
ret.add(Long.class);
ret.add(Float.class);
ret.add(Double.class);
ret.add(Void.class);
ret.add(String.class);
ret.add(URI.class);
ret.add(URL.class);
ret.add(LocalDate.class);
ret.add(LocalDateTime.class);
ret.add(ZonedDateTime.class);
ret.add(Instant.class);
return ret;
}
private final class Builders {
private AbstractInstanceBuilder defaultBuilder;
private AbstractInstanceBuilder dateBuilder;
// Lists and Sets
private AbstractInstanceBuilder collectionBuilder;
private AbstractInstanceBuilder mapBuilder;
private Builders() {
this.defaultBuilder = new DefaultInstanceBuilder(CloneBuilderImpl.this, uow);
this.dateBuilder = new DateInstanceBuilder(CloneBuilderImpl.this, uow);
}
private AbstractInstanceBuilder getBuilder(Object toClone) {
if (toClone instanceof Date) {
return dateBuilder;
}
if (toClone instanceof Map) {
if (mapBuilder == null) {
this.mapBuilder = new MapInstanceBuilder(CloneBuilderImpl.this, uow);
}
return mapBuilder;
} else if (toClone instanceof Collection) {
if (collectionBuilder == null) {
this.collectionBuilder = new CollectionInstanceBuilder(CloneBuilderImpl.this, uow);
}
return collectionBuilder;
} else {
return defaultBuilder;
}
}
}
}