Example usage for javax.persistence EntityTransaction rollback

List of usage examples for javax.persistence EntityTransaction rollback

Introduction

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

Prototype

public void rollback();

Source Link

Document

Roll back the current resource transaction.

Usage

From source file:de.peterspan.csv2db.converter.location.LocationConverter.java

@Override
protected Void doInBackground() throws Exception {
    EntityTransaction tx = null;
    try {//from   www  .  j a va2  s  .  c  o m
        tx = entityManager.getTransaction();
        tx.begin();
        List<String[]> allLines = readFile();

        double increment = 100.0 / allLines.size();
        double progress = 0.0;
        // Removing the header
        // Remove the empty line
        for (String[] line : allLines) {
            progress = progress + increment;
            setProgress((int) Math.round(progress));
            if (line[0].equals("Standort-Nr.")) {
                continue;
            }
            if (line[0].equals("")) {
                continue;
            }
            readLine(line);

        }

        entityManager.flush();
        tx.commit();
    } catch (HibernateException he) {
        if (tx != null) {
            tx.rollback();
        }
    }

    return null;
}

From source file:com.eucalyptus.images.Images.java

public static KernelImageInfo lookupKernel(final String kernelId) {
    EntityTransaction tx = Entities.get(KernelImageInfo.class);
    KernelImageInfo ret = new KernelImageInfo();
    try {//from ww  w .  j  ava2  s .  c  om
        ret = Entities.uniqueResult(Images.exampleKernelWithImageId(kernelId));
        tx.commit();
    } catch (Exception e) {
        LOG.error("Kernel '" + kernelId + "' does not exist" + e);
        throw new NoSuchElementException("InvalidAMIID.NotFound");
    } finally {
        if (tx.isActive())
            tx.rollback();
    }
    return ret;
}

From source file:com.eucalyptus.images.Images.java

public static RamdiskImageInfo lookupRamdisk(final String ramdiskId) {
    EntityTransaction tx = Entities.get(RamdiskImageInfo.class);
    RamdiskImageInfo ret = new RamdiskImageInfo();
    try {//  ww w .  java  2 s  . c om
        ret = Entities.uniqueResult(Images.exampleRamdiskWithImageId(ramdiskId));
        tx.commit();
    } catch (Exception e) {
        LOG.error("Ramdisk '" + ramdiskId + "' does not exist" + e);
        throw new NoSuchElementException("InvalidAMIID.NotFound");
    } finally {
        if (tx.isActive())
            tx.rollback();
    }
    return ret;
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public UserAction addUserTrackingEvent(UserAction a) throws UserTrackingException {
    EntityManager em = null;//from  www  .ja  va 2s . c  om
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        em.persist(a);
        tx.commit();
        return a;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserTrackingException(e);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:org.eclipse.smila.binarystorage.persistence.jpa.JPABinaryPersistence.java

/**
 * Stores the given BinaryStorageDao, updating an existing one or creating a new one.
 *
 * @param dao//  w w w .  j a  v  a2 s.c o m
 *          the BinaryStorageDao to store
 * @throws BinaryStorageException
 *           if any error occurs
 */
// TODO: don't know if this synchronize is good, was needed to pass the JUNit test TestConcurrentBSSAccessJPA
private synchronized void store(final BinaryStorageDao dao) throws BinaryStorageException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            if (findBinaryStorageDao(em, dao.getId()) == null) {
                em.persist(dao);
            } else {
                em.merge(dao);
            }
            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("stored content of id:" + dao.getId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new BinaryStorageException(e, "error storing record id: " + dao.getId());
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

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();//  w  w  w.j ava  2 s  . c  o  m
    this.entityManager.persist(applicationEntity);
    entityTransaction.commit();
    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:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * {@inheritDoc}//from ww w.  j a v  a2s .  co m
 */
@Override
public void storeRecord(final Record record) throws RecordStorageException {
    if (record == null) {
        throw new RecordStorageException("parameter record is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            final RecordDao dao = new RecordDao(record);
            transaction.begin();
            if (findRecordDao(em, record.getId()) == null) {
                em.persist(dao);
            } else {
                em.merge(dao);
            }
            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("stored record Id:" + record.getId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new RecordStorageException(e, "error storing record id: " + record.getId());
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void updateEvent(DublinCoreCatalog event) throws NotFoundException, SchedulerServiceDatabaseException {
    if (event == null) {
        throw new SchedulerServiceDatabaseException("Cannot update <null> event");
    }//from   w  w w.j a v  a2 s  . c o  m
    Long eventId = Long.parseLong(event.getFirst(DublinCore.PROPERTY_IDENTIFIER));
    String dcXML;
    try {
        dcXML = serializeDublinCore(event);
    } catch (Exception e1) {
        logger.error("Could not serialize Dublin Core: {}", e1);
        throw new SchedulerServiceDatabaseException(e1);
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID " + eventId + " does not exist.");
        }
        entity.setEventDublinCore(dcXML);
        em.merge(entity);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store event: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }

}

From source file:name.livitski.tools.persista.TransactionalWork.java

/**
 * Performs the {@link #code database operations} provided by
 * the subclass in JPA transactional brackets. If there is currently
 * no active transaction at the entity manager, a new transaction
 * is started.//from  w  w w  . j  av a 2 s .  c om
 * If the code finishes normally and does not request the rollback,
 * the transaction is committed if it was started by this method
 * (local transaction).
 * If the implementor's code throws an exception or requests the
 * rollback, the local transaction is rolled back and any ongoing
 * transaction is marked
 * {@link EntityTransaction#setRollbackOnly() rollback-only}.
 * @param db the entity manager the operation will be performed with
 * @return <code>true</code> if the transaction has or may still
 * be committed
 * @throws AbstractStorageException indicates an error during
 * the operation
 * @throws RuntimeException any unchecked implementor's exceptions
 * will be rethrown
 * @see EntityManager#getTransaction()
 */
public boolean exec(final EntityManager db) throws AbstractStorageException {
    final EntityTransaction transaction = db.getTransaction();
    boolean commit = false;
    Exception status = null;
    boolean localTransaction;
    if (transaction.isActive())
        localTransaction = false;
    else {
        transaction.begin();
        localTransaction = true;
    }
    try {
        commit = code(db);
        return commit;
    } catch (AbstractStorageException fault) {
        status = fault;
        throw fault;
    } catch (RuntimeException fault) {
        status = fault;
        throw fault;
    } finally {
        if (!localTransaction) {
            if (commit)
                db.flush();
            else
                transaction.setRollbackOnly();
        } else if (!commit || transaction.getRollbackOnly()) {
            try {
                transaction.rollback();
            } catch (RuntimeException fault) {
                if (null != status)
                    log().error("Transaction rollback failed", fault);
                else
                    throw fault;
            }
        } else // commit local transaction
        {
            try {
                transaction.commit();
            } catch (RuntimeException fault) {
                throw fault;
            }
        }
    }
}

From source file:org.apache.juddi.replication.ReplicationNotifier.java

/**
 * Note: this is for locally originated changes only, see null null null         {@link org.apache.juddi.api.impl.UDDIReplicationImpl.PullTimerTask#PersistChangeRecord PersistChangeRecord
 * } for how remote changes are processed
 *
 * @param j must be one of the UDDI save APIs
 *
 *///w  ww  .j  a va 2 s.  co  m
protected void ProcessChangeRecord(org.apache.juddi.model.ChangeRecord j) {
    //store and convert the changes to database model

    //TODO need a switch to send the notification without persisting the record
    //this is to support multihop notifications
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();
        j.setIsAppliedLocally(true);
        em.persist(j);
        j.setOriginatingUSN(j.getId());
        em.merge(j);
        log.info("CR saved locally, it was from " + j.getNodeID() + " USN:" + j.getOriginatingUSN() + " Type:"
                + j.getRecordType().name() + " Key:" + j.getEntityKey() + " Local id:" + j.getId());
        tx.commit();
    } catch (Exception ex) {
        log.fatal("unable to store local change record locally!!", ex);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        JAXB.marshal(MappingModelToApi.mapChangeRecord(j), System.out);
    } finally {
        em.close();
    }

    log.debug("ChangeRecord: " + j.getId() + "," + j.getEntityKey() + "," + j.getNodeID() + ","
            + j.getOriginatingUSN() + "," + j.getRecordType().toString());
    SendNotifications(j.getId(), j.getNodeID(), false);

}