01: package org.vraptor.plugin.jpa;
02:
03: import java.lang.reflect.Field;
04: import java.text.MessageFormat;
05:
06: import javax.persistence.EntityManager;
07:
08: import org.apache.log4j.Logger;
09: import org.vraptor.LogicRequest;
10: import org.vraptor.component.BeanConstructor;
11: import org.vraptor.component.ComponentInstantiationException;
12: import org.vraptor.introspector.BeanProvider;
13:
14: /**
15: * Wraps the standard {@link BeanConstructor} injecting an {@link EntityManager}
16: * at the construction time.
17: *
18: * @author Fabio Kung
19: * @since 2.3.2
20: */
21: public class EntityManagerInjector implements BeanConstructor {
22:
23: private final EntityManagerIntrospector introspector;
24:
25: private final BeanConstructor beanConstructor;
26:
27: private static final Logger LOG = Logger
28: .getLogger(EntityManagerInjector.class);
29:
30: public EntityManagerInjector(BeanConstructor constructor,
31: EntityManagerIntrospector introspector) {
32: this .beanConstructor = constructor;
33: this .introspector = introspector;
34: }
35:
36: public Object newInstance(LogicRequest request,
37: BeanProvider provider)
38: throws ComponentInstantiationException {
39: Object instance = beanConstructor
40: .newInstance(request, provider);
41: injectPersistenceContext(request, instance);
42:
43: return instance;
44: }
45:
46: private void injectPersistenceContext(LogicRequest request,
47: Object component) throws ComponentInstantiationException {
48: EntityManager entityManager = (EntityManager) request
49: .getRequestContext().getAttribute(
50: EntityManager.class.getName());
51:
52: Field field = introspector.getEntityManagerField(request
53: .getLogicDefinition().getComponentType());
54: if (field != null) {
55: try {
56: LOG
57: .debug(MessageFormat
58: .format(
59: "Injecting EntityManager in the component: {0}.{1}",
60: field.getType().getName(),
61: field.getName()));
62: field.setAccessible(true);
63: field.set(component, entityManager);
64: } catch (IllegalAccessException e) {
65: throw new ComponentInstantiationException(
66: "Problem injecting the EntityManager", e);
67: }
68: }
69: }
70:
71: }
|