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:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

public void close() {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }/*from   ww w  . j  av  a  2  s. co  m*/

    // rollback transaction and close entity manager
    EntityTransaction transaction = entityManager.getTransaction();
    if (transaction.isActive()) {
        transaction.rollback();
    }
    entityManager.clear();
    entityManager.close();
    entityManager = null;
}

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

public TModelList findTModel(FindTModel body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {/*from  w w w.  j  a  va 2s .c om*/
        new ValidateInquiry(null).validateFindTModel(body, false);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
        findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());

        List<?> keysFound = InquiryHelper.findTModel(body, findQualifiers, em);

        TModelList result = InquiryHelper.getTModelListFromKeys(body, findQualifiers, em, keysFound);

        tx.rollback();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.SUCCESS, procTime);

        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.isatools.isatab.ISATABUnloader.java

public void unload() {
    List<Study> studies = new LinkedList<Study>();

    EntityManager emgr = daoFactory.getEntityManager();
    Session session = (Session) emgr.getDelegate();
    EntityTransaction ts = emgr.getTransaction();

    if (studyAcc != null) {
        StudyDAO dao = daoFactory.getStudyDAO();
        Study study = dao.getByAcc(studyAcc);
        if (study == null) {
            log.warn("Study with accession '" + studyAcc + "' not found, no undeletion performed.");
            return;
        }/*from www .ja  va2  s .  c om*/
        studies.add(study);

        unloadMgr = new UnloadManager(daoFactory, study.getSubmissionTs());
        StudyUnloader unloader = (StudyUnloader) unloadMgr.getUnloader(Study.class);
        unloader.queueByAcc(studyAcc);
    } else {
        studies.addAll(daoFactory.getStudyDAO().getBySubmissionTs(unloadMgr.getSubmissionTs()));
        unloadMgr.queueAll(studies);
    }

    try {
        if (!ts.isActive()) {
            ts.begin();
        }
        unloadMgr.delete();
        ts.commit();
    } catch (HibernateException e) {
        if (ts.isActive()) {
            ts.rollback();
        }
        throw new TabInternalErrorException("Error while performing the unloading:" + e.getMessage());
    } finally {
        session.flush();
    }

    DataFilesDispatcher fileDispatcher = new DataFilesDispatcher(daoFactory.getEntityManager());
    fileDispatcher.undispatch(studies);
}

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

public BusinessList findBusiness(FindBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {/*from  w  ww.ja  v a 2 s . c o  m*/
        new ValidateInquiry(null).validateFindBusiness(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.FAILED, procTime);
        throw drfm;
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
        findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());

        List<?> keysFound = InquiryHelper.findBusiness(body, findQualifiers, em);

        BusinessList result = InquiryHelper.getBusinessListFromKeys(body, findQualifiers, em, keysFound);

        tx.rollback();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.SUCCESS, procTime);

        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java

@Override
public void deleteTheme(long id) throws ThemesServiceDatabaseException, NotFoundException {
    EntityManager em = null;/*  w  w  w. jav  a2 s. c  om*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        ThemeDto themeDto = getThemeDto(id, em);
        if (themeDto == null)
            throw new NotFoundException("No theme with id=" + id + " exists");

        tx = em.getTransaction();
        tx.begin();
        em.remove(themeDto);
        tx.commit();
        messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue,
                ThemeItem.delete(id));
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete theme '{}': {}", id, ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();
        throw new ThemesServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes every article older than the creationTime of the UXBEntity
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *///from w  ww  . ja  v  a 2 s.co m
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                Article art = (Article) obj;
                em.remove(art);
            }
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

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

public ResetImageAttributeResponseType resetImageAttribute(ResetImageAttributeType request)
        throws EucalyptusCloudException {
    ResetImageAttributeResponseType reply = (ResetImageAttributeResponseType) request.getReply();
    reply.set_return(true);
    EntityTransaction tx = Entities.get(ImageInfo.class);
    try {//ww  w  .  java2s.  com
        ImageInfo imgInfo = Entities
                .uniqueResult(Images.exampleWithImageId(imageIdentifier(request.getImageId())));
        if (canModifyImage(imgInfo)) {
            imgInfo.resetPermission();
            tx.commit();
            return reply.markWinning();
        } else {
            tx.rollback();
            return reply.markFailed();
        }
    } catch (EucalyptusCloudException e) {
        LOG.error(e, e);
        tx.rollback();
        return reply.markFailed();
    } catch (TransactionException | NoSuchElementException ex) {
        tx.rollback();
        return reply.markFailed();
    }
}

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

/**
 * Removes the infrastructure. Delete the infrastructure only if there are
 * not applications associated with it to avoid inconsistency in the DB.
 * <p>//from w  w w  .  j  a  va  2  s. c  o m
 * Infrastructures with associated applications can only be disabled to
 * avoid future execution of applications.
 *
 * @param id Id of the infrastructure to remove
 */
@DELETE
public final void deleteInfra(@PathParam("id") final String id) {
    Infrastructure infra;
    EntityManager em = getEntityManager();
    try {
        infra = em.find(Infrastructure.class, id);
        if (infra == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> appsForInfra = em.createNamedQuery("applications.forInfrastructure")
                    .setParameter("infraId", id).setMaxResults(1).getResultList();
            if (appsForInfra == null || appsForInfra.isEmpty()) {
                em.remove(infra);
            } else {
                throw new WebApplicationException("The infrastructure "
                        + "cannot be removed because there are associated " + "applications",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the infrastructure");
            throw new InternalServerErrorException("Errore to remove " + "the infrastructure " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new BadRequestException("Task '" + id + "' does not exist!");
    } finally {
        em.close();
    }
}

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

public RelatedBusinessesList findRelatedBusinesses(FindRelatedBusinesses body)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//from   w  ww  .  j ava 2s  . com
        new ValidateInquiry(null).validateFindRelatedBusinesses(body, false);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.FAILED, procTime);
        throw drfm;
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        // TODO: findQualifiers aren't really used for this call, except maybe for sorting.  Sorting must be done in Java due to the retrieval method used.  Right now
        // no sorting is performed.
        org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
        findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());

        RelatedBusinessesList result = InquiryHelper.getRelatedBusinessesList(body, em);

        tx.rollback();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.SUCCESS, procTime);

        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java

/**
 * Finalize any operation which affected the EntityManager. This method has
 * the following tasks:/*from   www .j  av a  2s . c o  m*/
 *
 * <ul>
 * <li>Commit the provided transaction</li>
 * <li>If the commit fails, rollback the transaction</li>
 * <li>Clear the cache of the EntityManager (make all entities
 * unmanaged)</li>
 * </ul>
 *
 * If no transaction is provided (after an operation which did not affect
 * the data backend, e.g. find()), only the cache is cleared.
 *
 * @param <T> Generic entity type.
 * @param methodName Description of the method which was performed (for
 * debugging).
 * @param transaction The transaction to finalize.
 * @param entity Affected entity or entity class (for debugging).
 */
private <T> void finalizeEntityManagerAccess(String methodName, EntityTransaction transaction, T entity) {
    if (transaction != null) {
        try {
            LOGGER.debug("Flushing entityManager");
            entityManager.flush();
            LOGGER.debug("Committing current transaction");
            transaction.commit();
        } catch (Exception e) {
            LOGGER.warn("Failed to commit transaction for operation '" + methodName + "'", e);
        } finally {
            if (transaction.isActive()) {
                LOGGER.debug("Transaction is still active. Performing rollback.");
                transaction.rollback();
                LOGGER.error("Method '" + methodName + "' fails for entity/class '" + entity + "'");
            }
            LOGGER.debug("Clearing entityManager cache");
            entityManager.clear();
            LOGGER.debug("Cache cleared.");
        }
    } else {
        LOGGER.debug("Clearing entityManager cache");
        entityManager.clear();
        LOGGER.debug("Cache cleared.");
    }
}