Example usage for javax.persistence EntityTransaction setRollbackOnly

List of usage examples for javax.persistence EntityTransaction setRollbackOnly

Introduction

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

Prototype

public void setRollbackOnly();

Source Link

Document

Mark the current resource transaction so that the only possible outcome of the transaction is for the transaction to be rolled back.

Usage

From source file:com.pocketgorilla.stripesem.TransactionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (log.isDebugEnabled())
        log.debug("filtering " + ((HttpServletRequest) request).getRequestURI());

    try {/*  www .  j a  v a  2 s  .c  o m*/
        chain.doFilter(request, response);
    } catch (Exception ex) {
        try {
            EntityManager em = provider.getEntityManager(false);
            if (em != null) {
                EntityTransaction tx = em.getTransaction();
                if (tx.isActive()) {
                    tx.setRollbackOnly();
                }
            }
        } finally {
            throw new ServletException(ex);
        }
    } finally {
        doAfter();
    }
}

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 a v  a2s  . co  m*/
 * 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: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  w w .  j  a 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.blockstorage.BlockStorageController.java

private static boolean isSnapshotMarkedFailed(String snapshotId) {
    EntityTransaction db = Entities.get(SnapshotInfo.class);
    db.setRollbackOnly();
    try {/* w w w.  j a va  2 s  . c om*/
        SnapshotInfo snap = Entities.uniqueResult(new SnapshotInfo(snapshotId));
        if (snap != null && StorageProperties.Status.failed.toString().equals(snap.getStatus())) {
            return true;
        }
    } catch (Exception e) {
        LOG.error("Error determining status of snapshot " + snapshotId);
    } finally {
        db.rollback();
    }
    return false;
}

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

/**
 * Deletes a news article from the db//from   w  ww. jav a  2s  .  c  o m
 *
 * @param entity The article to delete
 */
public void delete(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.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString());
        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            Article art = (Article) query.getSingleResult();
            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.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Add or update a news article in the db
 *
 * @param entity The NewsItem/*from ww  w . j a va  2  s .  c o m*/
 */
public void add(UXBEntity entity) throws Exception {

    Article art = buildArticle(entity);

    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.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", art.getAid());
        query.setParameter("language", art.getLanguage());

        /*
        * If the item exists in the db, we update the content and the title of the existing item
        */
        if (query.getResultList().size() > 0) {
            Article db = (Article) query.getSingleResult();
            db.setContent(art.getContent());
            db.setTitle(art.getTitle());
            db.setUrl(art.getUrl());
            db.setCreated(art.getCreated());
            db.setAid(art.getAid());
            db.setLanguage(art.getLanguage());
            db.setVersion(art.getVersion());
            db.setLastmodified(art.getLastmodified());

            art = db;
        }
        // save to db
        em.persist(art);
        em.flush();

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while writing to the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * handle the update and save process.//w  w w .  j a v  a  2s .c o  m
 *
 * @param entity the newsdrilldown entity
 * @throws Exception the exception
 */
private void handle(UXBEntity entity) throws Exception {
    /**
     * Due to a hibernate problem when updating or saving a newsdrilldown with
     * related categories we have to perform these step for saving the newsdrilldown
     *
     * 1. save/update all categories and remove them from the newsdrilldown
     *    1.1 save/update all metaCategories and remove them from the categories
     *    1.2 save the categories
     *    1.3 read all metaCategories to the categories
     *    1.4 save the categories again to create the relations
     * 2. save the newsdrilldown
     * 3. read all categories to the newsdrilldown
     */

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        News news = buildNews(entity);
        List<Long> categories = new ArrayList<Long>();

        /*
        * 1. update or save all categories
        * Steps 1.1 - 1.4
        */
        if (news.getCategories() != null && !news.getCategories().isEmpty()) {
            for (NewsCategory cat : news.getCategories()) {
                cat = saveNewsCategory(cat);
                if (!categories.contains(cat.getFs_id())) {
                    categories.add(cat.getFs_id());
                }
            }
            news.setCategories(new ArrayList<NewsCategory>());
        }

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

        // 2. save the newsdrilldown
        news = saveNews(news, em);

        // 3. read all categories to the newsdrilldown
        if (!categories.isEmpty()) {
            for (Long cat : categories) {
                NewsCategory ncat = getNewsCategory(cat, news.getLanguage(), em);
                news.getCategories().add(ncat);
            }
        }

        tx.commit();

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * Deletes every item older than the creationTime of the UXBEntity.
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *//*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();

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

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                News art = (News) obj;
                em.remove(art);
            }
        }

        // Remove old newsCategories
        query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM category x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                NewsCategory art = (NewsCategory) obj;
                em.remove(art);
            }
        }

        // Remove old newsMetaCategories
        query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM metaCategory x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                NewsMetaCategory art = (NewsMetaCategory) obj;
                em.remove(art);
            }
        }

        tx.commit();
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        logger.error("Failure while deleting from the database", e);
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * saves or updates a newscategory.//from   www.  j  av  a  2s  .  c  o m
 *
 * @param category the category
 * @return the category with the new id
 * @throws Exception the exception
 */
private NewsCategory saveNewsCategory(NewsCategory category) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // try loading the category for the firstspirit id
        NewsCategory cat = getNewsCategory(category.getFs_id(), category.getLanguage(), em);

        if (cat != null) {

            List<NewsMetaCategory> metaCats = category.getMetaCategories();

            // the already persistent categories
            List<NewsMetaCategory> original_metaCats = cat.getMetaCategories();

            // update existing category
            cat.setMetaCategories(new ArrayList<NewsMetaCategory>());

            for (NewsMetaCategory metaCat : metaCats) {
                metaCat = saveNewsMetaCategory(metaCat, em);
                cat.getMetaCategories().add(metaCat);

                original_metaCats.remove(metaCat);
            }
            for (NewsMetaCategory mc : original_metaCats) {
                mc.setLastmodified(category.getLastmodified());
            }
            cat.getMetaCategories().addAll(original_metaCats);

            cat.setFs_id(category.getFs_id());
            cat.setLanguage(category.getLanguage());
            cat.setName(category.getName());
            cat.setVersion(category.getVersion());
            cat.setLastmodified(category.getLastmodified());

            // update
            category = em.merge(cat);
        } else {
            updateMetaCategories(category, em);
            // save to db
            em.persist(category);
        }

        tx.commit();

        return category;

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        logger.error("", e);
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * Deletes a newsdrilldown from the db.//  w ww.  ja v a2s  .  c om
 *
 * @param entity The newsdrilldown to delete
 */
public void delete(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("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString());
        query.setParameter("fs_id", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            News art = (News) query.getSingleResult();
            // delete file from filesystem
            URL url = new URL(art.getUrl());
            File file = new File(webpath + url.getPath());
            if (file.exists()) {
                // Try acquiring the lock without blocking. This method returns
                // null or throws an exception if the file is already locked.
                try {
                    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
                    // Try to lock the file
                    FileLock lock = channel.tryLock();
                    // Delete the file
                    file.delete();
                    // Release the lock
                    lock.release();
                    lock.channel().close();
                } catch (OverlappingFileLockException e) {
                    logger.info("File is already locked in this thread or virtual machine");
                } catch (MalformedURLException e) {
                    logger.info("wrong url", e);
                }
            }
            // remove article from content repository

            em.remove(art);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}