}
private Instance newInstance(Object primaryKey, Class beanClass, Map<EntityManagerFactory, EntityManager> entityManagers) throws OpenEJBException {
Instance instance = null;
ThreadContext threadContext = ThreadContext.getThreadContext();
Operation currentOperation = threadContext.getCurrentOperation();
try {
ThreadContext callContext = ThreadContext.getThreadContext();
CoreDeploymentInfo deploymentInfo = callContext.getDeploymentInfo();
Context ctx = deploymentInfo.getJndiEnc();
// Get or create the session context
SessionContext sessionContext;
synchronized (this) {
try {
sessionContext = (SessionContext) ctx.lookup("java:comp/EJBContext");
} catch (NamingException e1) {
StatefulUserTransaction userTransaction = new StatefulUserTransaction(new EjbUserTransaction(), entityManagerRegistry);
sessionContext = new StatefulContext(securityService, userTransaction);
ctx.bind("java:comp/EJBContext", sessionContext);
}
}
// Create bean instance
InjectionProcessor injectionProcessor = new InjectionProcessor(beanClass, deploymentInfo.getInjections(), null, null, ctx);
try {
if (SessionBean.class.isAssignableFrom(beanClass) || beanClass.getMethod("setSessionContext", SessionContext.class) != null) {
callContext.setCurrentOperation(Operation.INJECTION);
injectionProcessor.setProperty("sessionContext", sessionContext);
}
} catch (NoSuchMethodException ignored) {
// bean doesn't have a setSessionContext method, so we don't need to inject one
}
Object bean = injectionProcessor.createInstance();
// Create interceptors
HashMap<String, Object> interceptorInstances = new HashMap<String, Object>();
for (InterceptorData interceptorData : deploymentInfo.getAllInterceptors()) {
if (interceptorData.getInterceptorClass().equals(beanClass)) {
continue;
}
Class clazz = interceptorData.getInterceptorClass();
InjectionProcessor interceptorInjector = new InjectionProcessor(clazz, deploymentInfo.getInjections(), ctx);
try {
Object interceptorInstance = interceptorInjector.createInstance();
interceptorInstances.put(clazz.getName(), interceptorInstance);
} catch (ConstructionException e) {
throw new Exception("Failed to create interceptor: " + clazz.getName(), e);
}
}
interceptorInstances.put(beanClass.getName(), bean);
// Invoke post construct method
callContext.setCurrentOperation(Operation.POST_CONSTRUCT);
List<InterceptorData> callbackInterceptors = deploymentInfo.getCallbackInterceptors();
InterceptorStack interceptorStack = new InterceptorStack(bean, null, Operation.POST_CONSTRUCT, callbackInterceptors, interceptorInstances);
interceptorStack.invoke();
// Wrap-up everthing into a object