Example usage for javax.persistence EntityTransaction isActive

List of usage examples for javax.persistence EntityTransaction isActive

Introduction

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

Prototype

public boolean isActive();

Source Link

Document

Indicate whether a resource transaction is in progress.

Usage

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * Creates or updates an entry in the delta indexing database and sets the visited flag.
 * //from   ww  w.j ava  2s  . c  om
 * @param em
 *          the EntityManager
 * @param dao
 *          the DeltaIndexingDao if a former entry exists or null
 * @param id
 *          the id of the record (just for logging)
 * @param hash
 *          the delta indexing hash
 * @param isCompound
 *          boolean flag if the record identified by id is a compound record (true) or not (false)
 * @throws DeltaIndexingException
 *           if any error occurs
 */
private void visitNewOrChangedDao(final EntityManager em, DeltaIndexingDao dao, final ConnectivityId id,
        final String hash, final boolean isCompound) throws DeltaIndexingException {
    final EntityTransaction transaction = em.getTransaction();
    try {
        transaction.begin();
        if (dao == null) {
            dao = new DeltaIndexingDao(id, hash, isCompound, true);
            em.persist(dao);
            if (_log.isTraceEnabled()) {
                _log.trace("created and visited id: " + id);
            }
        } else {
            dao.modifyAndVisit(hash);
            em.merge(dao);
            if (_log.isTraceEnabled()) {
                _log.trace("visited Id:" + id);
            }
        }
        transaction.commit();
    } catch (final Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new DeltaIndexingException("error visiting id: " + id, e);
    }
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@DELETE
@Path("{id}")
public Response unsubscribeFeed(@Context SecurityContext context, @PathParam("id") int feedId) {
    EntityManager em;//w  ww . j  a  v  a  2  s  .  com
    EntityTransaction tx;
    User user;
    Feed f;
    FeedData fd;

    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();
    user = (User) context.getUserPrincipal();

    try {
        tx.begin();

        try {
            f = (Feed) em.createQuery("from Feed where id = :id", Feed.class).setParameter("id", feedId)
                    .getSingleResult();
        } catch (NoResultException e) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!f.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        fd = f.getData();
        em.remove(f);

        if (fd.getFeeds().isEmpty())
            em.remove(fd);

        tx.commit();

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/* w  ww .  j  a v a2  s. c o m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#clear()
 */
@Override
public void clear() throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            // delete delta indexing entries
            final Query diQuery = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_DELETE_ALL);
            diQuery.executeUpdate();
            // delete source
            final Query dsQuery = em.createNamedQuery(DataSourceDao.NAMED_QUERY_DELETE_SOURCES);
            dsQuery.executeUpdate();

            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("cleared delta indexing");
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error clearing delta indexing", e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

@Override
public void deleteSeries(String seriesId) throws SeriesServiceDatabaseException, NotFoundException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from   w ww  .  j ava 2  s  . com
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            throw new NotFoundException("Series with ID " + seriesId + " does not exist");
        }
        // Ensure this user is allowed to delete this series
        String accessControlXml = entity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, EDIT_SERIES_PERMISSION)) {
                throw new UnauthorizedException(
                        currentUser + " is not authorized to update series " + seriesId);
            }
        }
        em.remove(entity);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete series: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*from  ww  w . jav a 2  s  . c om*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#clear(String)
 */
@Override
public void clear(final String sessionId) throws DeltaIndexingSessionException, DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final DataSourceDao dao = assertSession(sessionId);

        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            // delete delta indexing entries
            final Query diQuery = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_DELETE_BY_SOURCE);
            diQuery.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dao.getDataSourceId())
                    .executeUpdate();

            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("cleared delta indexing for sessionId: " + sessionId + " with data source "
                        + dao.getDataSourceId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error clearing delta indexing for session id: " + sessionId, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:ar.com.zauber.commons.repository.closures.OpenEntityManagerClosure.java

/** @see Closure#execute(Object) */
public final void execute(final T t) {
    if (dryrun) {
        //permite evitar que se hagan commit() en el ambiente de test
        target.execute(t);//w ww . j  a va 2s  . c  o m
    } else {
        boolean participate = false;
        EntityTransaction transaction = null;

        if (TransactionSynchronizationManager.hasResource(emf)) {
            // Do not modify the EntityManager: just set the participate flag.
            participate = true;
        } else {
            try {
                final EntityManager em = emf.createEntityManager();
                if (openTx) {
                    if (!warningPrinted) {
                        logger.warn(
                                "The OpenEntityManagerClosure has Transactions enabled and is not recommended"
                                        + ". This behaviour will change in the future. Check setOpenTx(), ");
                    }
                    transaction = em.getTransaction();
                    transaction.begin();
                }

                TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
            } catch (PersistenceException ex) {
                throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
            }
        }

        if (transaction != null) {
            try {
                target.execute(t);
                if (transaction.getRollbackOnly()) {
                    transaction.rollback();
                } else {
                    transaction.commit();
                }
            } catch (final Throwable e) {
                if (transaction != null && transaction.isActive()) {
                    transaction.rollback();
                }
                throw new UnhandledException(e);
            } finally {
                if (!participate) {
                    final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                            .unbindResource(emf);
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }
        } else {
            try {
                target.execute(t);
            } finally {
                if (!participate) {
                    final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                            .unbindResource(emf);
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }

        }
    }
}

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  w  w  w. j a  v  a2 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:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

@SuppressWarnings("unchecked")
public UserAction addUserFootprint(UserAction a) throws UserTrackingException {
    a.setType("FOOTPRINT");
    EntityManager em = null;/*ww w  .j av a 2  s  . c om*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        Query q = em.createNamedQuery("findLastUserFootprintOfSession");
        q.setMaxResults(1);
        q.setParameter("sessionId", a.getSessionId());
        Collection<UserAction> userActions = q.getResultList();

        if (userActions.size() >= 1) {
            UserAction last = userActions.iterator().next();
            if (last.getMediapackageId().equals(a.getMediapackageId()) && last.getType().equals(a.getType())
                    && last.getOutpoint() == a.getInpoint()) {
                last.setOutpoint(a.getOutpoint());
                a = last;
                a.setId(last.getId());
            } else {
                em.persist(a);
            }
        } else {
            em.persist(a);
        }
        tx.commit();
        return a;
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new UserTrackingException(e);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

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

/**
 * Gets all client subscription information. This is used for server to server subscriptions
 * Administrative privilege required.//from w w w .  j a  v a  2 s  .  c o m
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage 
 */
@SuppressWarnings("unchecked")
public ClientSubscriptionInfoDetail getAllClientSubscriptionInfoDetail(GetAllClientSubscriptionInfoDetail body)
        throws DispositionReportFaultMessage {

    new ValidateClientSubscriptionInfo(null).validateGetAllClientSubscriptionDetail(body);

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

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

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        Query query = em.createQuery("SELECT cs from ClientSubscriptionInfo as cs");
        List<org.apache.juddi.model.ClientSubscriptionInfo> modelClientSubscriptionInfoList = query
                .getResultList();

        for (ClientSubscriptionInfo modelClientSubscriptionInfo : modelClientSubscriptionInfoList) {

            org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();

            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

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

}

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

public List<AssertionStatusItem> getAssertionStatusReport(String authInfo, CompletionStatus completionStatus)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   w  w  w.java 2  s  .c  om*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        List<org.uddi.api_v3.AssertionStatusItem> result = PublicationHelper
                .getAssertionStatusItemList(publisher, completionStatus, em);

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.GET_ASSERTIONSTATUSREPORT, QueryStatus.SUCCESS, procTime);

        return result;
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.GET_ASSERTIONSTATUSREPORT, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}