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:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testPersist() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {/*from  www  . j  a v a  2s . c o m*/
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final Shadow shadow = persistInstance(manager, null, null);
            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java

@Override
public void remove() {

    if (taskAction != null) {
        Log log = taskAction.getLog();/*from  www .ja  va 2s  .  co m*/
        log.debug("Removing task resource: " + getID());
        AbstractTask tsk = taskAction.getModel();
        boolean cleanUp = false;
        if (tsk != null) {
            if (!tsk.isDone()) {
                // task is still running cancel it and cleanup entity manager
                taskAction.setCancelled(true);
                log.debug("cancel task " + tsk.getWid());
                cleanUp = true;
                if (future != null) {
                    future.cancel(true);
                    try {
                        // give cancel some time
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        logger.debug(e);
                    }
                }

                try {
                    EntityManager em = taskAction.getEntityManager();
                    if (em != null && em.isOpen()) {
                        try {
                            EntityTransaction tx = em.getTransaction();
                            if (tx.isActive())
                                tx.rollback();
                        } finally {
                            em.close();
                        }
                    }
                } catch (Exception e) {
                    // don't bother with exceptions
                    log.debug("Exception on task future cancel: " + e.toString(), e);
                }
            }

            EntityManager em = home.getEntityManagerFactory().createEntityManager();
            TxFrame tx = new TxFrame(em);
            // cleanup if necessary
            try {
                try {
                    Task t = em.find(Task.class, tsk.getId());
                    t.setPostMortem(true);
                    tx.commit();

                    if (cleanUp) {
                        log.debug("Triggering task cleanup");
                        try {
                            taskAction.setOwnEntityManager(em);
                            taskAction.cleanUpOnFail(t);
                        } catch (Exception e) {
                            log.debug("Exception on cleanup: " + e.toString());
                        }
                    }

                    // remove task from db
                    log.debug("Removing task: " + t.getId());
                    tx.begin();
                    em.remove(t);
                    tx.commit();
                } finally {
                    tx.finish();
                    if (em.isOpen())
                        em.close();
                }
            } catch (Exception e) {
                log.debug("Exception on task resource removal: " + e.toString());
                e.printStackTrace();
            }
        }
    }
}

From source file:com.sdl.odata.datasource.jpa.JPADataSource.java

@Override
public Object create(ODataUri uri, Object entity, EntityDataModel entityDataModel) throws ODataException {
    Object jpaEntity = entityMapper.convertODataEntityToDS(entity, entityDataModel);
    EntityManager entityManager = getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {//  w w w  . ja va 2 s  .co m
        transaction.begin();

        LOG.info("Persisting entity: {}", jpaEntity);
        entityManager.persist(jpaEntity);

        return entityMapper.convertDSEntityToOData(jpaEntity, entity.getClass(), entityDataModel);
    } finally {
        if (transaction.isActive()) {
            transaction.commit();
        } else {
            transaction.rollback();
        }
    }
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * //w  w w  .  ja  va 2  s.  c o  m
 * @param em
 *            entity manager
 * @throws PersistenceException
 *             if we blow up
 */
private static void createOrUpdateDBGuard(EntityManager em) throws PersistenceException {
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();

        try {
            em.createQuery("select guard from DbGuardPO as guard").getSingleResult(); //$NON-NLS-1$
        } catch (NoResultException nre) {
            LockManager.initDbGuard(em);
        }

        tx.commit();
    } catch (PersistenceException pe) {
        if (tx != null) {
            tx.rollback();
        }
        throw pe;
    }
}

From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java

public UddiEntityPublisher identify(String authInfo, String authorizedName)
        throws AuthenticationException, FatalErrorException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from w w  w.jav a2  s . c o  m*/
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

private String getUsername(String authinfo) {
    String user = "N/A";

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//  w ww  .ja  v  a 2s. c om

        tx.begin();
        user = publishService.getEntityPublisher(em, authinfo).getAuthorizedName();
        tx.commit();
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return user;
}

From source file:org.debux.webmotion.jpa.Transactional.java

/**
 * Create the transaction and the GenericDAO if the entity name is not 
 * empty or null.//from  w w w .  j a va 2s  .c om
 * 
 * @param request set EntityManager, EntityTransaction and GenericDAO into the request
 * @param persistenceUnitName precise the persistence unit
 * @param packageEntityName precise the package of entity
 * @param entityName precise the class name of the entity
 * 
 * @throws Exception catch execption to rollback the transaction
 */
public void tx(HttpServletRequest request, String persistenceUnitName, Properties properties,
        String packageEntityName, String entityName) throws Exception {

    // Create factory
    if (persistenceUnitName == null || persistenceUnitName.isEmpty()) {
        persistenceUnitName = DEFAULT_PERSISTENCE_UNIT_NAME;
    }
    EntityManagerFactory factory = factories.get(persistenceUnitName);
    if (factory == null) {
        Configuration subset = properties.subset(persistenceUnitName);
        java.util.Properties additionalProperties = ConfigurationConverter.getProperties(subset);

        factory = Persistence.createEntityManagerFactory(persistenceUnitName, additionalProperties);
        factories.put(persistenceUnitName, factory);
    }

    // Create manager
    EntityManager manager = (EntityManager) request.getAttribute(CURRENT_ENTITY_MANAGER);
    if (manager == null) {
        manager = factory.createEntityManager();
        request.setAttribute(CURRENT_ENTITY_MANAGER, manager);
    }

    // Create generic DAO each time if callback an action on an other entity
    if (entityName != null) {
        String fullEntityName = null;
        if (packageEntityName != null && !packageEntityName.isEmpty()) {
            fullEntityName = packageEntityName + "." + entityName;
        } else {
            fullEntityName = entityName;
        }

        GenericDAO genericDAO = new GenericDAO(manager, fullEntityName);
        request.setAttribute(CURRENT_GENERIC_DAO, genericDAO);

    } else {
        request.setAttribute(CURRENT_GENERIC_DAO, null);
    }

    // Create transaction
    EntityTransaction transaction = (EntityTransaction) request.getAttribute(CURRENT_ENTITY_TRANSACTION);
    if (transaction == null) {
        transaction = manager.getTransaction();
        request.setAttribute(CURRENT_ENTITY_TRANSACTION, transaction);

        transaction.begin();

        try {
            doProcess();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }

        if (transaction.isActive()) {
            transaction.commit();
        }
        manager.close();

    } else {
        doProcess();
    }
}

From source file:info.dolezel.jarss.rest.v1.ws.UnreadNotificationEndpoint.java

@OnWebSocketMessage
public void onMessage(Session session, String text) {
    EntityManager em = null;/* w w  w.  ja v  a  2s . co m*/
    EntityTransaction tx = null;
    try {
        JsonReader reader;
        JsonObject object;
        Token token;

        em = HibernateUtil.getEntityManager();
        tx = em.getTransaction();

        tx.begin();

        reader = Json.createReader(new StringReader(text));
        object = reader.readObject();

        token = Token.loadToken(em, object.getString("token"));
        if (token == null) {
            tx.rollback();

            Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.WARNING,
                    "Invalid token provided over WebSocket");
            session.close();
        } else {
            synchronized (sessions) {
                sessions.put(session, token.getUser());
            }
            synchronized (userSessions) {
                userSessions.put(token.getUser(), session);
            }
        }

        tx.commit();
    } catch (Exception ex) {
        if (tx != null)
            tx.rollback();

        Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.SEVERE,
                "Error processing incoming WebSocket message", ex);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default remove: bring back to persistence context if required and delete
 * // w  w w. jav a 2  s .  c o  m
 * @param objs
 *            objects to remove
 * @return removed objects
 * @throws Exception
 *             on errors (transaction is being rolled back)
 */
public Collection<T> remove(Collection<T> objs) throws Exception {
    if (objs == null || objs.isEmpty()) {
        return null;
    }
    Collection<T> res = new ArrayList<T>();
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        for (T obj : objs) {
            T tmp = em.contains(obj) ? obj : em.merge(obj);
            em.remove(tmp);
            res.add(tmp);
        }
        t.commit();
        return res;
    } catch (Exception e) {
        t.rollback();
        throw e;
    }
}

From source file:com.eucalyptus.objectstorage.entities.upgrade.ObjectStorage400Upgrade.java

private static void populateSnapshotBucketsAndObjects() {
    EntityTransaction tran = Entities.get(WalrusSnapshotInfo.class);
    try {/* w  ww  . ja  v  a  2s .  c o m*/
        List<WalrusSnapshotInfo> walrusSnapshots = Entities.query(new WalrusSnapshotInfo(), Boolean.TRUE);
        for (WalrusSnapshotInfo walrusSnapshot : walrusSnapshots) {
            walrusSnapshotBuckets.add(walrusSnapshot.getSnapshotBucket());
            walrusSnapshotObjects.add(walrusSnapshot.getSnapshotId());
        }
        tran.commit();
    } catch (Exception e) {
        LOG.error("Failed to lookup snapshots stored in Walrus", e);
        tran.rollback();
        throw e;
    } finally {
        if (tran.isActive()) {
            tran.commit();
        }
    }
}