-
Notifications
You must be signed in to change notification settings - Fork 14
/
CollectionInstanceBuilder.java
260 lines (247 loc) · 10.9 KB
/
CollectionInstanceBuilder.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
/**
* Copyright (C) 2016 Czech Technical University in Prague
*
* 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.
*
* 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.annotations.Types;
import cz.cvut.kbss.jopa.model.descriptors.Descriptor;
import cz.cvut.kbss.jopa.utils.EntityPropertiesUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.*;
/**
* Special class for cloning collections. Introduced because some Java collection have no no-argument constructor and
* thus they must be cloned specially. NOTE: This class may be removed in case a better cloning mechanisms (namely
* database mappings and copy policies) is introduced.
*
* @author kidney
*/
class CollectionInstanceBuilder extends AbstractInstanceBuilder {
private static final Class<?> singletonListClass = Collections.singletonList(null).getClass();
private static final Class<?> singletonSetClass = Collections.singleton(null).getClass();
private static final Class<?> arrayAsListClass = Arrays.asList(new Object()).getClass();
CollectionInstanceBuilder(CloneBuilderImpl builder, UnitOfWork uow) {
super(builder, uow);
this.populates = true;
}
/**
* This method is the entry point for cloning the Java collections. It clones standard collections as well as
* immutable collections and singleton collections. </p>
* <p>
* Currently supported are List and Set.
*
* @param collection The collection to clone
* @return A deep clone of the specified collection
*/
@Override
Object buildClone(Object cloneOwner, Field field, Object collection, Descriptor repository)
throws OWLPersistenceException {
assert (collection instanceof Collection);
Collection<?> container = (Collection<?>) collection;
if (container instanceof IndirectCollection<?>) {
container = (Collection<?>) ((IndirectCollection<?>) container)
.getReferencedCollection();
}
Collection<?> clone = cloneUsingDefaultConstructor(cloneOwner, field, container, repository);
if (clone == null) {
if (Collections.EMPTY_LIST == container) {
return Collections.EMPTY_LIST;
}
if (Collections.EMPTY_SET == container) {
return Collections.EMPTY_SET;
}
Constructor<?> c;
Object element = container.iterator().next();
Object[] params = new Object[1];
if (!CloneBuilderImpl.isImmutable(element.getClass())) {
element = builder.buildClone(element, repository);
if (element instanceof Collection || element instanceof Map) {
element = builder.createIndirectCollection(element, cloneOwner, field);
}
}
params[0] = element;
if (singletonListClass.isInstance(container)) {
c = getFirstDeclaredConstructorFor(singletonListClass);
} else if (singletonSetClass.isInstance(container)) {
c = getFirstDeclaredConstructorFor(singletonSetClass);
} else if (arrayAsListClass.isInstance(container)) {
final List arrayList = new ArrayList<>(container.size());
cloneCollectionContent(cloneOwner, field, container, arrayList, repository);
c = getFirstDeclaredConstructorFor(ArrayList.class);
params[0] = arrayList;
} else {
throw new OWLPersistenceException("Encountered unsupported type of collection: "
+ container.getClass());
}
try {
if (!c.isAccessible()) {
c.setAccessible(true);
}
clone = (Collection<?>) c.newInstance(params);
} catch (InstantiationException | IllegalArgumentException | InvocationTargetException e) {
throw new OWLPersistenceException(e);
} catch (IllegalAccessException e) {
logConstructorAccessException(c, e);
try {
clone = (Collection<?>) AccessController
.doPrivileged(new PrivilegedInstanceCreator(c));
} catch (PrivilegedActionException ex) {
throw new OWLPersistenceException(ex);
}
}
}
clone = (Collection<?>) builder.createIndirectCollection(clone, cloneOwner, field);
return clone;
}
/**
* Clones the specified collection using its default zero argument constructor. If the specified collection has none
* (e. g. like SingletonList), this method returns null.
*
* @param container The collection to clone.
* @return cloned collection
*/
private Collection<?> cloneUsingDefaultConstructor(Object cloneOwner, Field field,
Collection<?> container, Descriptor repository) {
Class<?> javaClass = container.getClass();
Collection<?> result = createNewInstance(javaClass, container.size());
if (result != null) {
// Makes shallow copy
cloneCollectionContent(cloneOwner, field, container, result, repository);
}
return result;
}
private Collection<?> createNewInstance(Class<?> type, int size) {
Object[] params = null;
Class<?>[] types = {int.class};
// Look for constructor taking initial size as parameter
Constructor<?> ctor = getDeclaredConstructorFor(type, types);
if (ctor != null) {
params = new Object[1];
params[0] = size;
} else {
ctor = DefaultInstanceBuilder.getDeclaredConstructorFor(type, null);
}
if (ctor == null) {
return null;
}
Collection<?> result = null;
try {
result = (Collection<?>) ctor.newInstance(params);
} catch (InstantiationException | InvocationTargetException | IllegalArgumentException e) {
throw new OWLPersistenceException(e);
} catch (IllegalAccessException e) {
logConstructorAccessException(ctor, e);
try {
result = (Collection<?>) AccessController
.doPrivileged(new PrivilegedInstanceCreator(ctor));
} catch (PrivilegedActionException ex) {
logPrivilegedConstructorAccessException(ctor, ex);
// Do nothing
}
}
return result;
}
/**
* Clone all the elements in the collection. This will make sure that the cloning process creates a deep copy.
*
* @param source The collection to clone.
*/
private void cloneCollectionContent(Object cloneOwner, Field field, Collection<?> source,
Collection<?> target, Descriptor descriptor) {
if (source.isEmpty()) {
return;
}
Collection<Object> tg = (Collection<Object>) target;
for (Object obj : source) {
if (obj == null) {
tg.add(null);
continue;
}
if (CloneBuilderImpl.isImmutable(obj.getClass())) {
tg.addAll(source);
break;
}
Object clone;
if (builder.isTypeManaged(obj.getClass())) {
clone = uow.registerExistingObject(obj, descriptor);
} else {
clone = builder.buildClone(cloneOwner, field, obj, descriptor);
}
tg.add(clone);
}
}
@Override
void mergeChanges(Field field, Object target, Object originalValue, Object cloneValue) {
assert (originalValue == null || originalValue instanceof Collection);
assert cloneValue instanceof Collection;
Collection<Object> orig = (Collection<Object>) originalValue;
Collection<Object> clone = (Collection<Object>) cloneValue;
if (clone instanceof IndirectCollection) {
clone = ((IndirectCollection<Collection<Object>>) clone).getReferencedCollection();
}
if (originalValue == null) {
orig = (Collection<Object>) createNewInstance(clone.getClass(), clone.size());
if (orig == null) {
orig = createDefaultCollection(clone.getClass());
}
EntityPropertiesUtils.setFieldValue(field, target, orig);
}
orig.clear();
if (clone.isEmpty()) {
return;
}
for (Object cl : clone) {
orig.add(uow.contains(cl) ? builder.getOriginal(cl) : cl);
}
final Types types = field.getAnnotation(Types.class);
if (types != null) {
checkForNewTypes(orig);
}
}
private Collection<Object> createDefaultCollection(Class<?> cls) {
if (Set.class.isAssignableFrom(cls)) {
return new HashSet<>();
} else if (List.class.isAssignableFrom(cls)) {
return new ArrayList<>();
} else {
throw new IllegalArgumentException("Unsupported type of collection: " + cls);
}
}
/**
* Checks if new types were added to the specified collection. </p>
* <p>
* If so, they are added to the module extraction signature managed by Metamodel.
*
* @param collection The collection to check
* @see Types
*/
private void checkForNewTypes(Collection<?> collection) {
assert collection != null;
if (collection.isEmpty()) {
return;
}
final Set<URI> signature = builder.getMetamodel().getModuleExtractionExtraSignature();
for (Object elem : collection) {
final URI u = EntityPropertiesUtils.getValueAsURI(elem);
if (!signature.contains(u)) {
builder.getMetamodel().addUriToModuleExtractionSignature(u);
}
}
}
}