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.binarystorage.persistence.jpa.JPABinaryPersistence.java

/**
 * {@inheritDoc}//from   w ww . jav a2 s . co m
 *
 * @see org.eclipse.smila.binarystorage.internal.impl.persistence.BinaryPersistence#deleteBinary(java.lang.String)
 */
@Override
public void deleteBinary(final String key) throws BinaryStorageException {
    if (key == null) {
        throw new BinaryStorageException("parameter key is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final BinaryStorageDao dao = findBinaryStorageDao(em, key);
            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 BinaryStorageException(e, "error removing record id: " + key);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not remove id: " + key + ". no binary object with this id exists.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

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

private static void populateSnapshotBucketsAndObjects() {
    EntityTransaction tran = Entities.get(WalrusSnapshotInfo.class);
    try {//from   www.j a  va2s  . 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();
        }
    }
}

From source file:uk.ac.horizon.ug.locationbasedgame.author.CRUDServlet.java

/** Create on POST.
 * E.g. curl -d '{...}' http://localhost:8888/author/configuration/
 * @param req//  w w  w .  j  a v  a 2s .c o m
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
private void doCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    try {
        Object o = parseObject(req);
        Key key = validateCreate(o);
        // try adding
        EntityManager em = EMF.get().createEntityManager();
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            if (em.find(getObjectClass(), key) != null)
                throw new RequestException(HttpServletResponse.SC_CONFLICT,
                        "object already exists (" + key + ")");
            em.persist(o);
            et.commit();
            logger.info("Added " + o);
        } finally {
            if (et.isActive())
                et.rollback();
            em.close();
        }
        resp.setCharacterEncoding(ENCODING);
        resp.setContentType(JSON_MIME_TYPE);
        Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING);
        JSONWriter jw = new JSONWriter(w);
        listObject(jw, o);
        w.close();
    } catch (RequestException e) {
        resp.sendError(e.getErrorCode(), e.getMessage());
    } catch (Exception e) {
        logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:org.apache.juddi.subscription.SubscriptionNotifier.java

/**
 * Obtains all subscriptions in the system.
 * @return Collection of All Subscriptions in the system.
 *//*from   ww w  . ja va2s. c  o  m*/
@SuppressWarnings("unchecked")
protected Collection<Subscription> getAllAsyncSubscriptions() {
    Collection<Subscription> subscriptions = null;
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Query query = em.createQuery("SELECT s FROM Subscription s WHERE s.bindingKey IS NOT NULL");
        subscriptions = (Collection<Subscription>) query.getResultList();
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return subscriptions;
}

From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Delete a user setting by using a unique id to find it.
 *
 * @param id/*from w  w w  .  j a v a  2 s  .  c  o  m*/
 *          The unique id for the user setting.
 * @throws UserSettingsServiceException
 */
public void deleteUserSetting(long id) throws UserSettingsServiceException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        UserSettingDto userSettingsDto = em.find(UserSettingDto.class, id);
        tx = em.getTransaction();
        tx.begin();
        em.remove(userSettingsDto);
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not delete user setting '%d': %s", id, ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * Removes a user from the repository//from   w w  w .j av  a2s.com
 * 
 * @param name
 *            the user to remove from the repository
 * @throws UsersRepositoryException
 */
public void removeUser(String name) throws UsersRepositoryException {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        if (entityManager.createNamedQuery("deleteUserByName").setParameter("name", name).executeUpdate() < 1) {
            transaction.commit();
            throw new UsersRepositoryException("User " + name + " does not exist");
        } else {
            transaction.commit();
        }
    } catch (PersistenceException e) {
        getLogger().debug("Failed to remove user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to remove user " + name, e);
    } finally {
        entityManager.close();
    }
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * Update the repository with the specified user object. A user object with
 * this username must already exist./*from  w  w  w.j a v  a 2s.c  o  m*/
 * 
 * @throws UsersRepositoryException
 */
public void updateUser(User user) throws UsersRepositoryException {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        if (contains(user.getUserName())) {
            transaction.begin();
            entityManager.merge(user);
            transaction.commit();
        } else {
            getLogger().debug("User not found");
            throw new UsersRepositoryException("User " + user.getUserName() + " not found");
        }
    } catch (PersistenceException e) {
        getLogger().debug("Failed to update user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to update user " + user.getUserName(), e);
    } finally {
        entityManager.close();
    }
}

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

public static List<ImageInfo> listAllImages() {
    final List<ImageInfo> images = Lists.newArrayList();
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {//  w  w w .jav  a  2  s .  c  om
        final List<ImageInfo> found = Entities.query(Images.ALL, true);
        images.addAll(found);
        db.rollback();
    } catch (final Exception e) {
        db.rollback();
        LOG.error("failed to query images", e);
    } finally {
        if (db.isActive())
            db.rollback();
    }
    return images;
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void deleteEvent(long eventId) throws NotFoundException, SchedulerServiceDatabaseException {
    EntityManager em = null;/* w ww. ja v a  2 s . c o m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID " + eventId + " does not exist");
        }
        em.remove(entity);
        tx.commit();
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (e instanceof NotFoundException) {
            throw (NotFoundException) e;
        }
        logger.error("Could not delete series: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java

/**
 * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#deleteOrganization(java.lang.String)
 *//*from  w  w w .j  a va  2s.c  o  m*/
@Override
public void deleteOrganization(String orgId) throws OrganizationDatabaseException, NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaOrganization organization = getOrganizationEntity(orgId);
        if (organization == null)
            throw new NotFoundException("Organization " + orgId + " does not exist");

        em.remove(organization);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete organization: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new OrganizationDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}