Example usage for javax.persistence EntityTransaction begin

List of usage examples for javax.persistence EntityTransaction begin

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction begin.

Prototype

public void begin();

Source Link

Document

Start a resource transaction.

Usage

From source file:com.google.inject.persist.jpa.KuneJpaLocalTxnInterceptor.java

@Override
public Object invoke(final MethodInvocation methodInvocation) throws Throwable, DefaultException {

    // Should we start a unit of work?
    if (!emProvider.isWorking()) {
        emProvider.begin();//from w  w w  .j a  va  2s  .c  o m
        didWeStartWork.set(true);
        LOG.debug("Starting transaction");
    }

    final KuneTransactional transactional = readTransactionMetadata(methodInvocation);
    final EntityManager em = this.emProvider.get();

    // Allow 'joining' of transactions if there is an enclosing
    // @KuneTransactional method.
    if (em.getTransaction().isActive()) {
        LOG.debug("Joining a previous transaction");
        return methodInvocation.proceed();
    }

    final EntityTransaction txn = em.getTransaction();
    txn.begin();

    Object result;
    try {
        result = methodInvocation.proceed();

    } catch (final Exception e) {
        // commit transaction only if rollback didnt occur
        LOG.debug("Exception in transaction", e);
        if (rollbackIfNecessary(transactional, e, txn)) {
            txn.commit();
        }

        // propagate whatever exception is thrown anyway
        throw e;
    } finally {
        // Close the em if necessary (guarded so this code doesn't run unless
        // catch fired).
        if (null != didWeStartWork.get() && !txn.isActive()) {
            didWeStartWork.remove();
            unitOfWork.end();
        }
    }

    // everything was normal so commit the txn (do not move into try block above
    // as it
    // interferes with the advised method's throwing semantics)
    try {
        LOG.debug("Trying to commit transaction");
        txn.commit();
    } finally {
        LOG.debug("Transaction commited");
        // close the em if necessary
        if (null != didWeStartWork.get()) {
            didWeStartWork.remove();
            unitOfWork.end();
        }
    }

    // or return result
    return result;
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testAudit() throws Exception {
    AuditEntity auditEntity = new AuditEntity("applicationName", "applicationKeyAlias", "keyStoreName",
            "keyStoreAlias", "digestValue");

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    this.entityManager.persist(auditEntity);
    entityTransaction.commit();//from w  w w  .j a v  a  2s. co  m
    long auditId = auditEntity.getId();

    entityTransaction.begin();
    List<AuditEntity> result = AuditEntity.listAll(this.entityManager);
    entityTransaction.commit();

    assertEquals(1, result.size());
    assertEquals(auditId, result.get(0).getId());
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testUniqueApplicationName() throws Exception {
    ApplicationEntity applicationEntity = new ApplicationEntity("app");
    ApplicationEntity applicationEntity2 = new ApplicationEntity("app");

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    this.entityManager.persist(applicationEntity);
    entityTransaction.commit();/*from  ww  w  . jav a  2 s . c o m*/

    entityTransaction.begin();
    assertTrue(ApplicationEntity.hasApplication(this.entityManager, "app"));
    try {
        this.entityManager.persist(applicationEntity2);
        fail();
    } catch (PersistenceException e) {
        entityTransaction.rollback();
    }
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testKeyStoreEntity() throws Exception {
    KeyStoreEntity keyStoreEntity = new KeyStoreEntity("name", KeyStoreType.PKCS12, "/home/fcorneli/test.p12",
            "test", 0);

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    entityManager.persist(keyStoreEntity);
    entityTransaction.commit();/* w  ww. j  a v a2s  . co  m*/
    long id = keyStoreEntity.getId();
    LOG.debug("keystore entity identifier: " + id);

    KeyStoreEntity resultEntity = this.entityManager.find(KeyStoreEntity.class, id);
    assertNotNull(resultEntity);
    LOG.debug("key store entity: " + resultEntity);

    List<KeyStoreEntity> keyStoreList = KeyStoreEntity.getList(this.entityManager);
    assertNotNull(keyStoreList);
    assertEquals(1, keyStoreList.size());
    assertTrue(KeyStoreEntity.hasKeyStore(this.entityManager, "name"));
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testKeyStoreEntityUniqueName() throws Exception {
    String keyStoreName = UUID.randomUUID().toString();
    KeyStoreEntity keyStoreEntity = new KeyStoreEntity(keyStoreName, KeyStoreType.PKCS12,
            "/home/fcorneli/test.p12", "test", 0);

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    this.entityManager.persist(keyStoreEntity);
    entityTransaction.commit();/*w  w w. j a v a  2s .  co  m*/

    KeyStoreEntity keyStoreEntity2 = new KeyStoreEntity(keyStoreName, KeyStoreType.PKCS12,
            "/home/fcorneli/test.p12", "test", 0);

    entityTransaction.begin();
    try {
        this.entityManager.persist(keyStoreEntity2);
        fail();
    } catch (PersistenceException e) {
        entityTransaction.rollback();
    }
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testApplicationKeyUniqueAlias() throws Exception {
    ApplicationEntity applicationEntity = new ApplicationEntity("app");

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    this.entityManager.persist(applicationEntity);
    entityTransaction.commit();/*from  ww w  . ja v a  2  s.  c  om*/
    long appId = applicationEntity.getId();

    entityTransaction.begin();
    applicationEntity = this.entityManager.find(ApplicationEntity.class, appId);
    ApplicationKeyEntity applicationKeyEntity = new ApplicationKeyEntity(applicationEntity, "alias");
    ApplicationKeyEntity applicationKeyEntity2 = new ApplicationKeyEntity(applicationEntity, "alias");
    this.entityManager.persist(applicationKeyEntity);
    try {
        this.entityManager.persist(applicationKeyEntity2);
        fail();
    } catch (EntityExistsException e) {
        entityTransaction.rollback();
    }
}

From source file:it.infn.ct.futuregateway.apiserver.v1.TaskCollectionService.java

/**
 * Retrieve a task list for the user./* ww  w. j a v  a 2  s  .  c  om*/
 * Tasks are retrieved from the storage for the user performing the request.
 *
 * @return A list of tasks
 */
private List<Task> retrieveTaskList() {
    List<Task> lstTasks = new LinkedList<>();
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    List<Object[]> taskList = null;
    try {
        et = em.getTransaction();
        et.begin();
        taskList = em.createNamedQuery("tasks.userAll").setParameter("user", getUser()).getResultList();
        et.commit();
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to retrieve the task list");
        log.error(re);
        throw new RuntimeException("Impossible to access the task list");
    } finally {
        em.close();
    }
    if (taskList != null && !taskList.isEmpty()) {
        for (Object[] elem : taskList) {
            int idElem = 0;
            Task tmpTask = new Task();
            tmpTask.setId((String) elem[idElem++]);
            tmpTask.setDescription((String) elem[idElem++]);
            tmpTask.setStatus((Task.STATUS) elem[idElem++]);
            tmpTask.setDateCreated((Date) elem[idElem]);
            lstTasks.add(tmpTask);
        }
    }
    return lstTasks;
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testApplicationCredential() throws Exception {
    ApplicationEntity applicationEntity = new ApplicationEntity("app");

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    this.entityManager.persist(applicationEntity);
    long appId = applicationEntity.getId();
    entityTransaction.commit();// w w  w.  ja  v a2  s .  c  o  m

    entityTransaction.begin();
    applicationEntity = this.entityManager.find(ApplicationEntity.class, appId);
    CredentialEntity credentialEntity = new CredentialEntity("hash", "credential".getBytes(),
            applicationEntity);
    this.entityManager.persist(credentialEntity);
    entityTransaction.commit();

    entityTransaction.begin();
    List<CredentialEntity> credentialList = CredentialEntity.getCredentials(this.entityManager,
            applicationEntity);
    assertNotNull(credentialList);
    assertEquals(1, credentialList.size());
}

From source file:nl.b3p.kaartenbalie.struts.KaartenbalieCrudAction.java

/** Execute method which handles all incoming request.
 *
 * @param mapping action mapping//ww  w  . j av  a 2  s  . co m
 * @param dynaForm dyna validator form
 * @param request servlet request
 * @param response servlet response
 *
 * @return ActionForward defined by Apache foundation
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) method.">
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Object identity = null;

    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        ActionForward forward = null;
        String msg = null;

        EntityManager em = getEntityManager();
        EntityTransaction tx = em.getTransaction();

        try {
            tx.begin();

            forward = super.execute(mapping, form, request, response);

            tx.commit();

            return forward;
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured, rollback", e);

            if (e instanceof org.hibernate.JDBCException) {
                msg = e.toString();
                SQLException sqle = ((org.hibernate.JDBCException) e).getSQLException();
                msg = msg + ": " + sqle;
                SQLException nextSqlE = sqle.getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else if (e instanceof java.sql.SQLException) {
                msg = e.toString();
                SQLException nextSqlE = ((java.sql.SQLException) e).getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else {
                msg = e.toString();
            }

            addAlternateMessage(mapping, request, null, msg);
        }

        try {
            tx.begin();

            prepareMethod((DynaValidatorForm) form, request, LIST, EDIT);

            tx.commit();
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured in second session, rollback", e);

            addAlternateMessage(mapping, request, null, e.toString());
        }
    } catch (Throwable e) {
        log.error("Exception occured while getting EntityManager: ", e);
        addAlternateMessage(mapping, request, null, e.toString());

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }

    return getAlternateForward(mapping, request);
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImplExt.java

public BusinessDetail saveBusinessFudge(SaveBusiness body, String nodeID) throws DispositionReportFaultMessage {

    if (!body.getBusinessEntity().isEmpty()) {
        log.debug("Inbound save business Fudger request for key "
                + body.getBusinessEntity().get(0).getBusinessKey());
    }//from  w ww . ja  v  a 2 s  .com
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        ValidatePublish validator = new ValidatePublish(publisher);
        validator.validateSaveBusiness(em, body, null);

        BusinessDetail result = new BusinessDetail();

        List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity();
        for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) {

            org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();

            MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity);
            nodeId = nodeID;

            setOperationalInfo(em, modelBusinessEntity, publisher);

            em.persist(modelBusinessEntity);

            result.getBusinessEntity().add(apiBusinessEntity);
        }

        //check how many business this publisher owns.
        validator.validateSaveBusinessMax(em);

        tx.commit();

        return result;
    } catch (DispositionReportFaultMessage drfm) {

        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}