-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInstanceFactory.java
226 lines (192 loc) · 8.8 KB
/
InstanceFactory.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
package com.github.nylle.javafixture;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;
import org.objenesis.instantiator.ObjectInstantiator;
import javassist.util.proxy.ProxyFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
import static java.lang.String.format;
import static java.util.Arrays.stream;
public class InstanceFactory {
private final SpecimenFactory specimenFactory;
private final PseudoRandom random;
private static final Map<Class<?>, Object> primitiveDefaults = Map.of(
Boolean.TYPE, false,
Character.TYPE, '\0',
Byte.TYPE, (byte) 0,
Short.TYPE, 0,
Integer.TYPE, 0,
Long.TYPE, 0L,
Float.TYPE, 0.0f,
Double.TYPE, 0.0d
);
public InstanceFactory(SpecimenFactory specimenFactory) {
this.specimenFactory = specimenFactory;
this.random = new PseudoRandom();
}
public <T> T construct(SpecimenType<T> type, CustomizationContext customizationContext) {
return random.shuffled(type.getDeclaredConstructors())
.stream()
.filter(x -> Modifier.isPublic(x.getModifiers()))
.findFirst()
.map(x -> construct(type, x, customizationContext))
.orElseGet(() -> manufacture(type, customizationContext, new SpecimenException("No public constructor found")));
}
public <T> T manufacture(SpecimenType<T> type, CustomizationContext customizationContext, Throwable throwable) {
return random.shuffled(type.getFactoryMethods())
.stream()
.filter(method -> Modifier.isPublic(method.getModifiers()))
.filter(method -> !hasSpecimenTypeAsParameter(method, type))
.map(x -> manufactureOrNull(x, type, customizationContext))
.filter(x -> x != null)
.findFirst()
.orElseThrow(() -> new SpecimenException(format("Cannot create instance of %s: no factory-method found", type.asClass()), throwable));
}
public <T> T instantiate(SpecimenType<T> type) {
try {
return type.asClass().getDeclaredConstructor().newInstance();
} catch (Exception e) {
return (T) ((ObjectInstantiator) ((Objenesis) new ObjenesisStd()).getInstantiatorOf(type.asClass())).newInstance();
}
}
public <T> Object proxy(final SpecimenType<T> type) {
return proxy(type, new HashMap<>());
}
public <T> Object proxy(final SpecimenType<T> type, final Map<String, ISpecimen<?>> specimens) {
return type.isInterface()
? createProxyForInterface(type, specimens)
: createProxyForAbstract(type, specimens);
}
public <G, T extends Collection<G>> T createCollection(final SpecimenType<T> type) {
return type.isInterface()
? createCollectionFromInterfaceType(type.asClass())
: createCollectionFromConcreteType(type);
}
private <T> boolean hasSpecimenTypeAsParameter(Method m, SpecimenType<T> type) {
return stream(m.getGenericParameterTypes()).anyMatch(t -> t.getTypeName().equals(type.asClass().getName()));
}
private <T> T construct(final SpecimenType<T> type, final Constructor<?> constructor, CustomizationContext customizationContext) {
try {
constructor.setAccessible(true);
return (T) constructor.newInstance(stream(constructor.getParameters())
.map(p -> createParameter(p, customizationContext))
.toArray());
} catch (Exception ex) {
return manufacture(type, customizationContext, ex);
}
}
private static Object defaultValue(Class<?> type) {
return type.isPrimitive()
? primitiveDefaults.get(type)
: null;
}
private Object createParameter(Parameter parameter, CustomizationContext customizationContext) {
if (customizationContext.getIgnoredFields().contains(parameter.getName())) {
return defaultValue(parameter.getType());
}
if (customizationContext.getCustomFields().containsKey(parameter.getName())) {
return customizationContext.getCustomFields().get(parameter.getName());
}
return specimenFactory
.build(SpecimenType.fromClass(parameter.getParameterizedType()))
.create(new CustomizationContext(List.of(), Map.of(), customizationContext.useRandomConstructor()), new Annotation[0]);
}
private <T> Object createProxyForInterface(SpecimenType<T> type, Map<String, ISpecimen<?>> specimens) {
try {
var proxyFactory = new ProxyFactory();
proxyFactory.setInterfaces(new Class<?>[]{type.asClass()});
return proxyFactory.create(new Class[0], new Object[0], new ProxyInvocationHandler(specimenFactory, specimens));
} catch (Exception e) {
throw new SpecimenException(format("Unable to proxy interface %s: %s", type.asClass(), e.getMessage()), e);
}
}
private <T> T createProxyForAbstract(final SpecimenType<T> type, final Map<String, ISpecimen<?>> specimens) {
try {
var factory = new ProxyFactory();
factory.setSuperclass(type.asClass());
return (T) factory.create(new Class<?>[0], new Object[0], new ProxyInvocationHandler(specimenFactory, specimens));
} catch (Exception ex) {
throw new SpecimenException(format("Unable to create instance of abstract %s: %s", type.asClass(), ex.getMessage()), ex);
}
}
private <T> T manufactureOrNull(final Method method, SpecimenType<T> type, CustomizationContext customizationContext) {
try {
List<Object> arguments = new ArrayList<>();
for (int i = 0; i < method.getParameterCount(); i++) {
var genericParameterType = method.getGenericParameterTypes()[i];
var specimen = specimenFactory.build(type.isParameterized()
? type.getGenericTypeArgument(i)
: SpecimenType.fromClass(genericParameterType));
var o = specimen.create(customizationContext, new Annotation[0]);
arguments.add(o);
}
return (T) method.invoke(null, arguments.toArray());
} catch (Exception ex) {
return null;
}
}
private <G, T extends Collection<G>> T createCollectionFromInterfaceType(final Class<T> type) {
if (List.class.isAssignableFrom(type)) {
return (T) new ArrayList<G>();
}
if (NavigableSet.class.isAssignableFrom(type)) {
return (T) new TreeSet<G>();
}
if (SortedSet.class.isAssignableFrom(type)) {
return (T) new TreeSet<G>();
}
if (Set.class.isAssignableFrom(type)) {
return (T) new HashSet<G>();
}
if (BlockingDeque.class.isAssignableFrom(type)) {
return (T) new LinkedBlockingDeque<G>();
}
if (Deque.class.isAssignableFrom(type)) {
return (T) new ArrayDeque<G>();
}
if (TransferQueue.class.isAssignableFrom(type)) {
return (T) new LinkedTransferQueue<G>();
}
if (BlockingQueue.class.isAssignableFrom(type)) {
return (T) new LinkedBlockingQueue<G>();
}
if (Queue.class.isAssignableFrom(type)) {
return (T) new LinkedList<G>();
}
if (Collection.class.isAssignableFrom(type)) {
return (T) new ArrayList<G>();
}
throw new SpecimenException("Unsupported type: " + type);
}
private <G, T extends Collection<G>> T createCollectionFromConcreteType(final SpecimenType<T> type) {
try {
return type.asClass().getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new SpecimenException("Unable to create collection of type " + type.getName(), e);
}
}
}