private void releaseUnclosedEntityManager(EntityManager em) {
   if (em == null) {
     return;
   }
   if (!em.isOpen()) {
     em = null;
     return;
   }
   if (JtaStatusHelper.isActive(TestingJtaPlatformImpl.INSTANCE.getTransactionManager())) {
     log.warn("Cleaning up unfinished transaction");
     try {
       TestingJtaPlatformImpl.INSTANCE.getTransactionManager().rollback();
     } catch (SystemException ignored) {
     }
   }
   try {
     if (em.getTransaction().isActive()) {
       em.getTransaction().rollback();
       log.warn(
           "You left an open transaction! Fix your test case. For now, we are closing it for you.");
     }
   } catch (IllegalStateException e) {
   }
   if (em.isOpen()) {
     // as we open an EM beforeQuery the test runs, it will still be open if the test uses a custom
     // EM.
     // or, the person may have forgotten to close. So, do not raise a "fail", but log the fact.
     em.close();
     log.warn("The EntityManager is not closed. Closing it.");
   }
 }
예제 #2
0
 @Override
 public ModelService rollback() {
   if (entityManager.isOpen() && entityManager.getTransaction().isActive()) {
     entityManager.getTransaction().rollback();
   }
   return this;
 }
 // r�cup�rer un EntityManager neuf
 private static EntityManager getNewEntityManager() {
   if (em != null && em.isOpen()) {
     em.close();
   }
   em = emf.createEntityManager();
   return em;
 }
예제 #4
0
 @TransactionAttribute(TransactionAttributeType.REQUIRED)
 public boolean crearRegistrosEstados(int periodo) {
   try {
     if (em.isOpen()) {
       // em.getTransaction().begin();
       StoredProcedureQuery storedProcedure =
           em.createStoredProcedureQuery("fn_calcular_registro_estado_default");
       // set parameters
       storedProcedure.registerStoredProcedureParameter(
           "id_periodo", Integer.class, ParameterMode.IN);
       storedProcedure.registerStoredProcedureParameter(
           "result", Boolean.class, ParameterMode.OUT);
       storedProcedure.setParameter("id_periodo", periodo);
       // execute SP
       storedProcedure.execute();
       // get result
       Boolean result = (Boolean) storedProcedure.getOutputParameterValue("result");
       System.out.println("result is: " + result);
       return result;
     }
   } catch (Exception e) {
     e.printStackTrace();
     ;
   }
   return false;
 }
 public AppCatalogResource get(Object identifier) throws AppCatalogException {
   EntityManager em = null;
   try {
     em = AppCatalogJPAUtils.getEntityManager();
     em.getTransaction().begin();
     AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(GLOBUS_SUBMISSION);
     generator.setParameter(GlobusJobSubmissionConstants.SUBMISSION_ID, identifier);
     Query q = generator.selectQuery(em);
     GlobusJobSubmission globusJobSubmission = (GlobusJobSubmission) q.getSingleResult();
     GlobusJobSubmissionResource globusJobSubmissionResource =
         (GlobusJobSubmissionResource)
             AppCatalogJPAUtils.getResource(
                 AppCatalogResourceType.GLOBUS_SUBMISSION, globusJobSubmission);
     em.getTransaction().commit();
     em.close();
     return globusJobSubmissionResource;
   } catch (ApplicationSettingsException e) {
     logger.error(e.getMessage(), e);
     throw new AppCatalogException(e);
   } finally {
     if (em != null && em.isOpen()) {
       if (em.getTransaction().isActive()) {
         em.getTransaction().rollback();
       }
       em.close();
     }
   }
 }
예제 #6
0
 private boolean auto(String operation) {
   long startTime = System.currentTimeMillis();
   System.out.println("Operation: " + operation + "...");
   HibernateEntityManagerFactory emf = null;
   EntityManager em = null;
   try {
     Map<String, String> map = getPeristencePropertiesFixedMap();
     if (operation != null) {
       map.put("hibernate.hbm2ddl.auto", operation);
     }
     if (operation.equals("update")) {
       if (getDriver().equals(TestStation.Driver.derby)) {
         String url = map.get("hibernate.connection.url");
         if (!url.contains("create=true")) {
           url += ";create=true";
         }
         //                    if (!url.contains("logDevice=")) {
         //                        url += ";logDevice=" + getUserHome() + File.separator +
         // ".jtstand";
         //                    }
         map.put("hibernate.connection.url", url);
       }
     }
     emf =
         (HibernateEntityManagerFactory)
             Persistence.createEntityManagerFactory(getTestProject().getPun(), map);
     //            emf.getSessionFactory().getAllClassMetadata();
     //            System.out.println(emf.getSessionFactory().getAllClassMetadata());
     em = emf.createEntityManager();
     em.getTransaction().begin();
     em.getTransaction().commit();
     //            System.out.println("Closing entity manager");
     em.close();
     //            System.out.println("Closing entity manager factory");
     emf.close();
     System.out.println(
         "Database "
             + operation
             + " operation succeeded in "
             + Long.toString(System.currentTimeMillis() - startTime)
             + "ms");
     return true;
   } catch (Exception ex) {
     ex.printStackTrace();
     System.out.println(ex.getMessage());
     if (em != null && em.isOpen()) {
       em.close();
     }
     if (emf != null && emf.isOpen()) {
       emf.close();
     }
   }
   System.out.println(
       "Database "
           + operation
           + " operation failed in "
           + Long.toString(System.currentTimeMillis() - startTime)
           + "ms");
   return false;
 }
  private void beginTrx() {
    try {

      UserTransaction trx = userTransactionProvider.get();
      String trxStatus = "";

      if (trx.getStatus() == Status.STATUS_NO_TRANSACTION) {
        trx.begin();
      }
      EntityManager em = emProvider.get();
      em.joinTransaction();

      trxStatus =
          trx.getStatus()
              + "; em = "
              + em
              + "[Open="
              + em.isOpen()
              // +", joinedToTrx="+em.isJoinedToTransaction()+"]"
              + "; UserTrx="
              + trx;
      log.debug(": Executing beginTrx ; TrxStatus " + trxStatus);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #8
0
  public static EntityManager getInstance() {
    if ((em == null) || (!em.isOpen())) {
      em = emf.createEntityManager();
    }

    return em;
  }
 protected EntityManager createEntityManager(Map properties) {
   // always reopen a new EM and close the existing one
   if (em != null && em.isOpen()) {
     em.close();
   }
   em = entityManagerFactory.createEntityManager(properties);
   return em;
 }
 private void close() {
   if (!entityManager.isOpen()) {
     entityManager.close();
   }
   if (factory.isOpen()) {
     factory.close();
   }
 }
예제 #11
0
 /** @see contact.service.DaoFactory#shutdown() */
 @Override
 public void shutdown() {
   try {
     if (em != null && em.isOpen()) em.close();
     if (emf != null && emf.isOpen()) emf.close();
   } catch (IllegalStateException ex) {
     logger.log(Level.SEVERE, ex.getMessage());
   }
 }
 public static void closeEntityManager(EntityManager entityManager) {
   try {
     if (entityManager != null && entityManager.isOpen()) {
       entityManager.close();
     }
   } catch (Exception e) {
     LOGGER.log(Level.SEVERE, "", e);
   }
 }
  @Test
  public void testSMPCCreationObserved()
      throws NotSupportedException, SystemException, SecurityException, IllegalStateException,
          RollbackException, HeuristicMixedException, HeuristicRollbackException {
    em.isOpen(); // need to make a call on the EM to force creation

    Assert.assertTrue(observer.isObserverRun());
    Assert.assertEquals(FlushModeType.COMMIT, em.getFlushMode());
  }
  private void open() {

    if (!factory.isOpen()) {
      factory = Persistence.createEntityManagerFactory("Introducao_a_Design_PatternsPU");
    }
    if (!entityManager.isOpen()) {
      entityManager = factory.createEntityManager();
    }
  }
예제 #15
0
파일: JPAUtil.java 프로젝트: cfran90/pos
 public static EntityManager getEntityManager() {
   if (entityManagerFactory == null) {
     entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
   }
   EntityManager entityManager = threadEntityManager.get();
   if (entityManager == null || !entityManager.isOpen()) {
     entityManager = entityManagerFactory.createEntityManager();
     JPAUtil.threadEntityManager.set(entityManager);
   }
   return entityManager;
 }
 @Override
 public List<E> selectAll() {
   if (em == null || !em.isOpen()) {
     em = EntityManageFactoryTest.getInstance().getEmf().createEntityManager();
   }
   try {
     return em.createQuery("Select tbl from " + clsName.getSimpleName() + " tbl").getResultList();
   } catch (Exception e) {
     return null;
   }
 }
예제 #17
0
 public void cleanup(EntityManager em) {
   // close JPA
   try {
     if (null != em && em.isOpen()) {
       em.close();
       // emf.close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
예제 #18
0
  /** Closes this instance. */
  public void close() {
    if (em != null && em.isOpen()) {
      rollbackTx();
      em.close();
    }

    if (emf != null && emf.isOpen()) {
      emf.close();
    }

    removeInstance();
  }
예제 #19
0
 public static void closeEntityManager() {
   if (em == null) {
     return;
   }
   if (em.getTransaction().isActive()) {
     em.getTransaction().commit();
   }
   if (em.isOpen()) {
     em.close();
   }
   em = null;
 }
예제 #20
0
 public void desconectarRetaguarda() throws Exception {
   if (emRetaguarda != null && emRetaguarda.isOpen()) {
     try {
       emRetaguarda.getTransaction().commit();
     } catch (Exception e) {
       emRetaguarda.getTransaction().rollback();
       throw e;
     } finally {
       emRetaguarda.close();
     }
   }
 }
예제 #21
0
 public void desconectarLocal() throws Exception {
   if (emLocal != null && emLocal.isOpen()) {
     try {
       emLocal.getTransaction().commit();
     } catch (Exception e) {
       emLocal.getTransaction().rollback();
       throw e;
     } finally {
       emLocal.close();
     }
   }
 }
예제 #22
0
 public static synchronized EntityManager getEntityManager() {
   if (em == null) {
     em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager();
   }
   if (!em.isOpen()) {
     em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager();
   }
   if (!em.getTransaction().isActive()) {
     em.getTransaction().begin();
   }
   // log.debug("created EntityManager");
   return em;
 }
 @Override
 public E getById(long id) {
   if (em == null || !em.isOpen()) {
     em = EntityManageFactoryTest.getInstance().getEmf().createEntityManager();
   }
   try {
     return (E) em.find(clsName, id);
   } catch (Exception e) {
     return null;
   } finally {
     em.close();
   }
 }
 /**
  * Close the given JPA EntityManager, catching and logging any cleanup exceptions thrown.
  *
  * @param em the JPA EntityManager to close (may be {@code null})
  * @see javax.persistence.EntityManager#close()
  */
 public static void closeEntityManager(EntityManager em) {
   if (em != null) {
     logger.debug("Closing JPA EntityManager");
     try {
       if (em.isOpen()) {
         em.close();
       }
     } catch (PersistenceException ex) {
       logger.debug("Could not close JPA EntityManager", ex);
     } catch (Throwable ex) {
       logger.debug("Unexpected exception on closing JPA EntityManager", ex);
     }
   }
 }
예제 #25
0
  public static void main(String[] args) {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager();
    if (em.isOpen()) System.out.println("haha");

    em.getTransaction().begin();
    Personnel p = new Personnel();
    p.setNom("test");
    p.setPrenom("test2");
    p.setFonction("test3");
    p.setNaissance("naissance");
    em.persist(p);
    em.getTransaction().commit();
    em.close();
  }
 @Override
 public boolean update(E object) {
   if (em == null || !em.isOpen()) {
     em = EntityManageFactoryTest.getInstance().getEmf().createEntityManager();
   }
   try {
     em.getTransaction().begin();
     em.merge(object);
     em.getTransaction().commit();
     return true;
   } catch (Exception e) {
     return false;
   } finally {
     em.close();
   }
 }
 public boolean salvar(T entity) {
   try {
     entityManager.getTransaction().begin();
     entityManager.persist(entity);
     entityManager.getTransaction().commit();
     return true;
   } catch (Exception ex) {
     if (entityManager.isOpen()) {
       if (entityManager.getTransaction().isActive()) {
         entityManager.getTransaction().rollback();
       }
     }
     log.error("Erro ao Salvar objeto: " + entity.toString());
     log.error("Causa do erro: " + ex.getMessage());
     return false;
   }
 }
 @Override
 public void onEndRequest(RequestCycle cycle) {
   super.onEndRequest(cycle);
   EntityManager em = getEntityManager();
   if (em != null) {
     if (em.getTransaction().isActive()) {
       em.getTransaction().commit();
     }
     if (em.isOpen()) {
       em.close();
     }
   }
   if (cycle.getMetaData(END_CONVERSATION_META_DATA_KEY)) {
     // this is not implemented in Wicket 1.5
     //            cycle.getRequest().getPage().getPageMap().remove();
   }
 }
 public boolean atualizar(T entity) {
   try {
     entityManager.getTransaction().begin();
     entityManager.merge(entity);
     entityManager.getTransaction().commit();
     return true;
   } catch (Exception ex) {
     if (entityManager.isOpen()) {
       if (entityManager.getTransaction().isActive()) {
         entityManager.getTransaction().rollback();
       }
     }
     log.error("Erro ao Editar Objeto: " + entity.toString());
     log.error("Causa do erro: " + ex.getMessage());
     ex.printStackTrace();
     return false;
   }
 }
 @Override
 public IRequestHandler onException(RequestCycle cycle, Exception e) {
   EntityManager em = getEntityManager();
   if (em != null) {
     if (em.getTransaction().isActive()) {
       em.getTransaction().rollback();
     }
     if (em.isOpen()) {
       em.close();
     }
   }
   if (e instanceof PageExpiredException) {
     Session.get().error("The page you requested has expired.");
     IPageProvider pageProvider = new PageProvider(new MainPage());
     return new RenderPageRequestHandler(pageProvider);
   }
   return super.onException(cycle, e);
 }