Example usage for javax.persistence EntityTransaction begin

List of usage examples for javax.persistence EntityTransaction begin

Introduction

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

Prototype

public void begin();

Source Link

Document

Start a resource transaction.

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   www.  ja  v a  2  s .c o  m*/
 * @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:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*from ww w  .  ja v a 2 s  .  co  m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasources()
 */
@Override
public void unlockDatasources() throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_KILL_ALL_SESSIONS);
            query.executeUpdate();
            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("removed all delta indexing sessions and unlocked all data sources");
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error unlocking delta indexing data sources", e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

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

/**
 * {@inheritDoc}/*ww  w  .  ja  v  a 2  s.  c  o m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasource(String)
 */
@Override
public void unlockDatasource(final String dataSourceID) throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_KILL_SESSION);
            query.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dataSourceID);
            query.executeUpdate();
            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("removed delta indexing sessions and unlocked data source " + dataSourceID);
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error unlocking delta indexing data source " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

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

/**
 * {@inheritDoc}/*from   w  w w .j  a  v  a2 s. c o m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#finish(String)
 */
@Override
public void finish(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();
            final DataSourceDao unlockedDao = new DataSourceDao(dao.getDataSourceId(), null);
            em.merge(unlockedDao);
            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("finished session " + sessionId + " with data source: " + dao.getDataSourceId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error finishing delta indexing for data source: " + dao.getDataSourceId(), e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

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

/**
 * {@inheritDoc}/*from w w w.  j ava2  s  .c om*/
 * 
 * @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.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//w  w w . j a  v  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:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from  ww  w . j  a va 2s .co m
public Response subscribeFeed(@Context SecurityContext context, FeedSubscriptionData data) {
    FeedCategory fc = null;
    EntityManager em;
    EntityTransaction tx;
    User user;
    FeedData feedData;
    Feed f;
    boolean createdNewFD = false;

    if (data.getUrl() == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorDescription("Feed URL missing"))
                .build();
    }

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

    try {
        if (data.getCategoryId() != 0) {
            try {
                fc = (FeedCategory) em
                        .createQuery("select fc from FeedCategory fc where fc.id = :id", FeedCategory.class)
                        .setParameter("id", data.getCategoryId()).getSingleResult();
            } catch (NoResultException e) {
                return Response.status(Response.Status.NOT_FOUND)
                        .entity(new ErrorDescription("Feed category not found")).build();
            }

            if (!fc.getUser().equals(user)) {
                return Response.status(Response.Status.FORBIDDEN)
                        .entity(new ErrorDescription("Feed category not owned by user")).build();
            }
        }

        // Try to look up existing FeedData
        try {
            feedData = (FeedData) em.createNamedQuery("FeedData.getByUrl").setParameter("url", data.getUrl())
                    .getSingleResult();
        } catch (NoResultException e) {
            feedData = new FeedData();
            feedData.setUrl(data.getUrl());

            try {
                loadFeedDetails(feedData);
            } catch (Exception ex) {
                e.printStackTrace();
                return Response.status(Response.Status.BAD_GATEWAY)
                        .entity(new ErrorDescription("Cannot fetch the feed")).build();
            }

            em.persist(feedData);
            createdNewFD = true;
        }

        f = new Feed();
        f.setUser(user);
        f.setFeedCategory(fc);
        f.setData(feedData);
        f.setName(feedData.getTitle());

        em.persist(f);

        tx.commit();

        if (createdNewFD)
            FeedsEngine.getInstance().submitFeedRefresh(feedData);

        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}/*  ww  w .j  a v a  2s.  c  om*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#delete(String, Id)
 */
@Override
public void delete(final String sessionId, final ConnectivityId id)
        throws DeltaIndexingSessionException, DeltaIndexingException {
    if (id == null) {
        throw new DeltaIndexingException("parameter id is null");
    }
    _lock.readLock().lock();
    try {
        assertSession(sessionId, id.getDataSourceId());
        final EntityManager em = createEntityManager();
        try {
            final DeltaIndexingDao dao = findDeltaIndexingDao(em, id);
            if (dao != null) {
                final EntityTransaction transaction = em.getTransaction();
                try {
                    transaction.begin();
                    em.remove(dao);
                    transaction.commit();
                } catch (final Exception e) {
                    if (transaction.isActive()) {
                        transaction.rollback();
                    }
                    throw new DeltaIndexingException("error deleting id: " + id, e);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not delete id: " + id + ". Id does not exist.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

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

/**
 * {@inheritDoc}//from   w  w  w .  j a v  a  2 s  .c  om
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#init(java.lang.String)
 */
@Override
public String init(final String dataSourceID) throws DeltaIndexingException {
    if (dataSourceID == null) {
        throw new DeltaIndexingException("parameter dataSourceID is null");
    }

    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final DataSourceDao dao = findDataSourceDao(em, dataSourceID);
            if (dao != null && dao.getSessionId() != null) {
                throw new DeltaIndexingException(
                        "data source " + dataSourceID + " is already locked by another session");
            }

            final String sessionId = UUID.randomUUID().toString();

            final DataSourceDao lockedDao = new DataSourceDao(dataSourceID, sessionId);
            // lock the data source
            if (dao == null) {
                em.persist(lockedDao);
            } else {
                em.merge(lockedDao);
            }

            // reset visited and modified flags
            resetFlags(em, dataSourceID);

            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("created session " + sessionId + " for data source: " + dataSourceID);
            }
            return sessionId;
        } catch (final DeltaIndexingException e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error initializing delta indexing for data source: " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

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

/**
 * {@inheritDoc}/*from  ww  w.  ja v a  2 s .c o m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#checkForUpdate(String, Id, String)
 */
@Override
public boolean checkForUpdate(final String sessionId, final ConnectivityId id, final String hash)
        throws DeltaIndexingSessionException, DeltaIndexingException {
    if (id == null) {
        throw new DeltaIndexingException("parameter id is null");
    }
    if (hash == null) {
        throw new DeltaIndexingException("parameter hash is null");
    }
    _lock.readLock().lock();
    try {
        assertSession(sessionId, id.getDataSourceId());
        final EntityManager em = createEntityManager();
        try {
            final DeltaIndexingDao dao = findDeltaIndexingDao(em, id);
            if (dao == null || !hash.equals(dao.getHash())) {
                return true;
            } else {
                final EntityTransaction transaction = em.getTransaction();
                try {
                    transaction.begin();
                    visitUnchangedDaos(em, dao);
                    transaction.commit();
                } catch (final Exception e) {
                    if (transaction.isActive()) {
                        transaction.rollback();
                    }
                    throw new DeltaIndexingException("error visiting id: " + id, e);
                }
                return false;
            }
        } catch (final Exception e) {
            throw new DeltaIndexingException("error checking for update for id: " + id, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}