/** This method creates a entity manager. */
  private EntityManager getEntityManager(KieRuntimeEvent event) {
    Environment env = event.getKieRuntime().getEnvironment();

    /**
     * It's important to set the sharedEM flag with _every_ operation otherwise, there are
     * situations where: 1. it can be set to "true" 2. something can happen 3. the "true" value can
     * no longer apply (I've seen this in debugging logs.. )
     */
    sharedEM = false;
    if (emf != null) {
      return emf.createEntityManager();
    } else if (env != null) {
      EntityManager em = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
      if (em != null) {
        sharedEM = true;
        return em;
      }
      EntityManagerFactory emf =
          (EntityManagerFactory) env.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
      if (emf != null) {
        return emf.createEntityManager();
      }
    }
    throw new RuntimeException("Could not find or create a new EntityManager!");
  }
 @Before
 public void setUp() throws Exception {
   context = setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME);
   Environment env = EnvironmentFactory.newEnvironment();
   env.set(
       EnvironmentName.ENTITY_MANAGER_FACTORY,
       context.get(EnvironmentName.ENTITY_MANAGER_FACTORY));
   logService = new JPAAuditLogService(env);
 }
  @Override
  protected StatefulKnowledgeSession createSession(KnowledgeBase kbase) {

    EnvironmentBuilder envBuilder = new KnowledgeSessionStorageEnvironmentBuilder(storage);
    Environment env = KieServices.Factory.get().newEnvironment();
    env.set(EnvironmentName.TRANSACTION_MANAGER, envBuilder.getTransactionManager());
    env.set(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, envBuilder.getPersistenceContextManager());

    return JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
  }
 protected StatefulKnowledgeSession createKnowledgeSession(KnowledgeBase kbase) {
   if (context == null) {
     context = DroolsPersistenceUtil.setupWithPoolingDataSource(DROOLS_PERSISTENCE_UNIT_NAME);
   }
   KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
   Environment env = createEnvironment(context);
   if (this.locking) {
     env.set(EnvironmentName.USE_PESSIMISTIC_LOCKING, true);
   }
   return JPAKnowledgeService.newStatefulKnowledgeSession(kbase, ksconf, env);
 }
  @Override
  protected StatefulKnowledgeSession disposeAndReloadSession(
      StatefulKnowledgeSession ksession, KnowledgeBase kbase) {
    long sessionId = ksession.getIdentifier();
    ksession.dispose();
    EnvironmentBuilder envBuilder = new KnowledgeSessionStorageEnvironmentBuilder(storage);
    Environment env = KieServices.Factory.get().newEnvironment();
    env.set(EnvironmentName.TRANSACTION_MANAGER, envBuilder.getTransactionManager());
    env.set(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, envBuilder.getPersistenceContextManager());

    return JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId, kbase, null, env);
  }
 private void setupPersistence() {
   context = DroolsPersistenceUtil.setupWithPoolingDataSource(DROOLS_PERSISTENCE_UNIT_NAME);
   env = createEnvironment(context);
   if (locking) {
     env.set(EnvironmentName.USE_PESSIMISTIC_LOCKING, true);
   }
 }
  public void initTransactionManager(Environment env) {
    Object tm = env.get(EnvironmentName.TRANSACTION_MANAGER);
    if (env.get(EnvironmentName.TASK_PERSISTENCE_CONTEXT_MANAGER) != null
        && env.get(EnvironmentName.TRANSACTION_MANAGER) != null) {
      this.txm = (TransactionManager) tm;
      this.tpm =
          (TaskPersistenceContextManager) env.get(EnvironmentName.TASK_PERSISTENCE_CONTEXT_MANAGER);
    } else {
      if (tm != null && isSpringTransactionManager(tm.getClass())) {
        try {
          logger.debug("Instantiating KieSpringTransactionManager");
          Class<?> cls = Class.forName("org.kie.spring.persistence.KieSpringTransactionManager");
          Constructor<?> con = cls.getConstructors()[0];
          this.txm = (TransactionManager) con.newInstance(tm);
          env.set(EnvironmentName.TRANSACTION_MANAGER, this.txm);
          cls = Class.forName("org.kie.spring.persistence.KieSpringTaskJpaManager");
          con = cls.getConstructors()[0];
          this.tpm = (TaskPersistenceContextManager) con.newInstance(new Object[] {env});
        } catch (Exception e) {

          logger.warn("Could not instantiate DroolsSpringTransactionManager");
          throw new RuntimeException(
              "Could not instantiate org.kie.container.spring.beans.persistence.DroolsSpringTransactionManager",
              e);
        }
      } else {
        logger.debug("Instantiating JtaTransactionManager");
        this.txm =
            new JtaTransactionManager(
                env.get(EnvironmentName.TRANSACTION),
                env.get(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY),
                tm);
        env.set(EnvironmentName.TRANSACTION_MANAGER, this.txm);
        try {
          this.tpm = new JPATaskPersistenceContextManager(env);
        } catch (Exception e) {
          throw new RuntimeException("Error creating JPATaskPersistenceContextManager", e);
        }
      }
      env.set(EnvironmentName.TASK_PERSISTENCE_CONTEXT_MANAGER, this.tpm);
      env.set(EnvironmentName.TRANSACTION_MANAGER, this.txm);
    }
  }
 @Override
 protected RuntimeEnvironment getRuntimeEnvironment(final KieBase kieBase) {
   final EntityManagerFactory emf =
       (EntityManagerFactory) environment.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
   return RuntimeEnvironmentBuilder.Factory.get()
       .newEmptyBuilder()
       .knowledgeBase(kieBase)
       .classLoader(this.getClass().getClassLoader())
       .entityManagerFactory(emf)
       .persistence(true)
       // the default MVELUserGroupCallback does not work due to NCDFError, see the error in
       // debugger - BZ 1316974
       .userGroupCallback(new JBossUserGroupCallbackImpl(new Properties()))
       .addEnvironmentEntry(EnvironmentName.ENTITY_MANAGER_FACTORY, emf)
       .addEnvironmentEntry(
           EnvironmentName.TRANSACTION_MANAGER,
           environment.get(EnvironmentName.TRANSACTION_MANAGER))
       .addEnvironmentEntry(
           EnvironmentName.TRANSACTION, environment.get(EnvironmentName.TRANSACTION))
       .addEnvironmentEntry(
           EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY,
           environment.get(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY))
       .get();
 }
 public void beginCommandScopedEntityManager() {
   EntityManager cmdScopedEntityManager =
       (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
   if (cmdScopedEntityManager == null
       || (this.cmdScopedEntityManager != null && !this.cmdScopedEntityManager.isOpen())) {
     internalCmdScopedEntityManager = true;
     this.cmdScopedEntityManager =
         this.emf
             .createEntityManager(); // no need to call joinTransaction as it will do so if one
                                     // already exists
     this.cmdScopedEntityManager.setFlushMode(FlushModeType.COMMIT);
     this.env.set(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, this.cmdScopedEntityManager);
     cmdScopedEntityManager = this.cmdScopedEntityManager;
   } else {
     internalCmdScopedEntityManager = false;
   }
   cmdScopedEntityManager.joinTransaction();
   appScopedEntityManager.joinTransaction();
 }
  @Before
  public void setUp() throws Exception {
    String methodName = testName.getMethodName();
    // Rules marshalling uses ObjectTypeNodes which screw up marshalling.
    if ("testLocalTransactionPerStatement".equals(methodName)
        || "testUserTransactions".equals(methodName)
        || "testPersistenceRuleSet".equals(methodName)
        || "testSetFocus".equals(methodName)
        // Constraints in ruleflows are rules as well (I'm guessing?), so OTN's again..
        || "testPersistenceState".equals(methodName)) {
      context = setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME, false);
    } else {
      context = setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME);
    }

    env = createEnvironment(context);
    if (useLocking) {
      env.set(EnvironmentName.USE_PESSIMISTIC_LOCKING, true);
    }
  }
 public JpaPersistenceContextManager(Environment env) {
   this.env = env;
   this.emf = (EntityManagerFactory) env.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
 }
 private void internalSetIsJTA(Environment env) {
   Boolean bool = (Boolean) env.get("IS_JTA_TRANSACTION");
   if (bool != null) {
     isJTA = bool.booleanValue();
   }
 }