/
AbstractProducerBean.java
386 lines (357 loc) · 12.2 KB
/
AbstractProducerBean.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.webbeans.bean;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;
import javax.context.CreationalContext;
import javax.context.Dependent;
import javax.context.ScopeType;
import javax.inject.DefinitionException;
import javax.inject.DeploymentType;
import javax.inject.IllegalProductException;
import javax.inject.Initializer;
import javax.inject.Produces;
import javax.inject.manager.InjectionPoint;
import org.jboss.webbeans.ManagerImpl;
import org.jboss.webbeans.context.CreationalContextImpl;
import org.jboss.webbeans.context.DependentContext;
import org.jboss.webbeans.context.DependentStorageRequest;
import org.jboss.webbeans.log.LogProvider;
import org.jboss.webbeans.log.Logging;
import org.jboss.webbeans.metadata.MetaDataCache;
import org.jboss.webbeans.util.Beans;
import org.jboss.webbeans.util.Names;
import org.jboss.webbeans.util.Reflections;
/**
* The implicit producer bean
*
* @author Gavin King
*
* @param <T>
* @param <S>
*/
public abstract class AbstractProducerBean<T, S> extends AbstractBean<T, S>
{
// The declaring bean
protected AbstractClassBean<?> declaringBean;
private static final LogProvider log = Logging.getLogProvider(AbstractProducerBean.class);
/**
* Constructor
*
* @param declaringBean The declaring bean
* @param manager The Web Beans manager
*/
public AbstractProducerBean(AbstractClassBean<?> declaringBean, ManagerImpl manager)
{
super(manager);
this.declaringBean = declaringBean;
}
/**
* Gets the deployment types
*
* @return The deployment types of the declaring bean
*/
@Override
protected Class<? extends Annotation> getDefaultDeploymentType()
{
return deploymentType = declaringBean.getDeploymentType();
}
/**
* Initializes the API types
*/
@Override
protected void initTypes()
{
if (getType().isArray() || getType().isPrimitive())
{
Set<Type> types = new HashSet<Type>();
types = new HashSet<Type>();
types.add(getType());
types.add(Object.class);
super.types = types;
}
else if (getType().isInterface())
{
Set<Type> types = new HashSet<Type>();
types.add(Object.class);
types.addAll(getAnnotatedItem().getFlattenedTypeHierarchy());
super.types = types;
}
else
{
super.initTypes();
}
}
/**
* Initializes the type
*/
@Override
protected void initType()
{
try
{
this.type = getAnnotatedItem().getType();
}
catch (ClassCastException e)
{
throw new RuntimeException(" Cannot cast producer type " + getAnnotatedItem().getType() + " to bean type " + (getDeclaredBeanType() == null ? " unknown " : getDeclaredBeanType()), e);
}
}
/**
* Gets the declared bean type
*
* @return The bean type
*/
protected Type getDeclaredBeanType()
{
Type type = getClass();
if (type instanceof ParameterizedType)
{
ParameterizedType parameterizedType = (ParameterizedType) type;
if (parameterizedType.getActualTypeArguments().length == 1)
{
return parameterizedType.getActualTypeArguments()[0];
}
}
return null;
}
/**
* Returns the declaring bean
*
* @return The bean representation
*/
public AbstractClassBean<?> getDeclaringBean()
{
return declaringBean;
}
/**
* Validates the producer method
*/
protected void checkProducerReturnType()
{
for (Type type : getAnnotatedItem().getActualTypeArguments())
{
if (!(type instanceof Class))
{
throw new DefinitionException("Producer type cannot be parameterized with type parameter or wildcard:\n" + this.getAnnotatedItem());
}
}
}
/**
* Initializes the bean and its metadata
*/
@Override
protected void init()
{
super.init();
checkProducerReturnType();
}
/**
* Validates the return value
*
* @param instance The instance to validate
*/
protected void checkReturnValue(T instance)
{
if (instance == null && !isDependent())
{
throw new IllegalProductException("Cannot return null from a non-dependent producer method");
}
boolean passivating = MetaDataCache.instance().getScopeModel(getScopeType()).isPassivating();
if (passivating && !Reflections.isSerializable(instance.getClass()))
{
throw new IllegalProductException("Producers cannot declare passivating scope and return a non-serializable class");
}
InjectionPoint injectionPoint = manager.getInjectionPoint();
if (injectionPoint == null)
{
return;
}
if (isDependent() && Beans.isPassivatingBean(injectionPoint.getBean()))
{
if (injectionPoint.getMember() instanceof Field)
{
if (!Reflections.isTransient(injectionPoint.getMember()) && !Reflections.isSerializable(instance.getClass()))
{
throw new IllegalProductException("Dependent scoped producers cannot produce non-serializable instances for injection into non-transient fields of passivating beans\n\nProducer: " + this.toString() + "\nInjection Point: " + injectionPoint.toString());
}
}
else if (injectionPoint.getMember() instanceof Method)
{
Method method = (Method) injectionPoint.getMember();
if (method.isAnnotationPresent(Initializer.class))
{
throw new IllegalProductException("Dependent scoped producers cannot produce non-serializable instances for injection into parameters of intializers of beans declaring passivating scope. Bean " + toString() + " being injected into " + injectionPoint.toString());
}
if (method.isAnnotationPresent(Produces.class))
{
throw new IllegalProductException("Dependent scoped producers cannot produce non-serializable instances for injection into parameters of producer methods declaring passivating scope. Bean " + toString() + " being injected into " + injectionPoint.toString());
}
}
else if (injectionPoint.getMember() instanceof Constructor)
{
throw new IllegalProductException("Dependent scoped producers cannot produce non-serializable instances for injection into parameters of constructors of beans declaring passivating scope. Bean " + toString() + " being injected into " + injectionPoint.toString());
}
}
}
@Override
protected void initScopeType()
{
Set<Annotation> scopeAnnotations = getAnnotatedItem().getMetaAnnotations(ScopeType.class);
if (scopeAnnotations.size() > 1)
{
throw new DefinitionException("At most one scope may be specified");
}
if (scopeAnnotations.size() == 1)
{
this.scopeType = scopeAnnotations.iterator().next().annotationType();
log.trace("Scope " + scopeType + " specified by annotation");
return;
}
initScopeTypeFromStereotype();
if (this.scopeType == null)
{
this.scopeType = Dependent.class;
log.trace("Using default @Dependent scope");
}
}
@Override
protected void initDeploymentType()
{
Set<Annotation> deploymentTypes = getAnnotatedItem().getMetaAnnotations(DeploymentType.class);
if (deploymentTypes.size() > 1)
{
throw new DefinitionException("At most one deployment type may be specified (" + deploymentTypes + " are specified) on " + getAnnotatedItem().toString());
}
else if (deploymentTypes.size() == 1)
{
this.deploymentType = deploymentTypes.iterator().next().annotationType();
log.trace("Deployment type " + deploymentType + " specified by annotation");
return;
}
initDeploymentTypeFromStereotype();
if (this.deploymentType == null)
{
this.deploymentType = getDefaultDeploymentType();
log.trace("Using default " + this.deploymentType + " deployment type");
return;
}
}
@Override
protected void initSerializable()
{
_serializable = true;
}
/**
* Gets the receiver of the product
*
* @return The receiver
*/
protected Object getReceiver(CreationalContext<?> creationalContext)
{
// This is a bit dangerous, as it means that producer methods can end of
// executing on partially constructed instances. Also, it's not required
// by the spec...
if (creationalContext instanceof CreationalContextImpl)
{
CreationalContextImpl<?> creationalContextImpl = (CreationalContextImpl<?>) creationalContext;
if (creationalContextImpl.containsIncompleteInstance(getDeclaringBean()))
{
log.warn("Executing producer field or method " + getAnnotatedItem() + " on incomplete declaring bean " + getDeclaringBean() + " due to circular injection");
return creationalContextImpl.getIncompleteInstance(getDeclaringBean());
}
}
return getAnnotatedItem().isStatic() ? null : manager.getInstance(getDeclaringBean());
}
/**
* Creates an instance of the bean
*
* @returns The instance
*/
public T create(CreationalContext<T> creationalContext)
{
DependentStorageRequest dependentStorageRequest = DependentStorageRequest.of(dependentInstancesStore, new Object());
try
{
if (getDeclaringBean().isDependent())
{
DependentContext.INSTANCE.startCollectingDependents(dependentStorageRequest);
}
DependentContext.INSTANCE.setActive(true);
T instance = produceInstance(creationalContext);
checkReturnValue(instance);
return instance;
}
finally
{
if (getDeclaringBean().isDependent())
{
DependentContext.INSTANCE.stopCollectingDependents(dependentStorageRequest);
dependentInstancesStore.destroyDependentInstances(dependentStorageRequest.getKey());
}
DependentContext.INSTANCE.setActive(false);
}
}
public void destroy(T instance)
{
/*
* try { DependentContext.INSTANCE.setActive(true); } finally {
* DependentContext.INSTANCE.setActive(false); }
*/
}
protected abstract T produceInstance(CreationalContext<T> creationalContext);
/**
* Gets a string representation
*
* @return The string representation
*/
@Override
public String toString()
{
StringBuilder buffer = new StringBuilder();
buffer.append("Annotated " + Names.scopeTypeToString(getScopeType()));
if (getName() == null)
{
buffer.append("unnamed producer bean");
}
else
{
buffer.append("simple producer bean '" + getName() + "'");
}
buffer.append(" [" + getType().getName() + "] API types " + getTypes() + ", binding types " + getBindings());
return buffer.toString();
}
@Override
public boolean equals(Object other)
{
if (other instanceof AbstractProducerBean)
{
AbstractProducerBean<?, ?> that = (AbstractProducerBean<?, ?>) other;
return super.equals(other) && this.getDeclaringBean().equals(that.getDeclaringBean());
}
else
{
return false;
}
}
}