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

/**
 * {@inheritDoc}//from w ww.j  av  a 2  s  .  c om
 *
 * @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.images.Images.java

public static void registerFromPendingImage(String imageId) throws Exception {
    EntityTransaction tx = Entities.get(PutGetImageInfo.class);
    try {/*from www. j  a  v a2 s  .c  o m*/
        ImageInfo ret = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        ret.setState(State.available);
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw new EucalyptusCloudException(
                "Failed to update image: " + imageId + " because of: " + e.getMessage(), e);
    }
}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testPuthenticate() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {/*from w ww . ja v a  2  s .c  o m*/
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            final byte[] password = newPassword();

            final Shadow shadow = persistInstance(manager, username, password);

            Assert.assertTrue(shadow.puthenticate(shadow, password));

            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

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

private static PutGetImageInfo persistRegistration(UserFullName creator, ImageManifest manifest,
        PutGetImageInfo ret) throws Exception {

    EntityTransaction tx = Entities.get(PutGetImageInfo.class);
    try {/*w  w w. j  a  v  a 2s.  co  m*/
        ret = Entities.merge(ret);
        tx.commit();
        LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + creator);
    } catch (Exception e) {
        tx.rollback();
        throw new EucalyptusCloudException(
                "Failed to register image: " + manifest + " because of: " + e.getMessage(), e);
    }
    // TODO:GRZE:RESTORE
    // for( String p : extractProductCodes( inputSource, xpath ) ) {
    // imageInfo.addProductCode( p );
    // }
    // imageInfo.grantPermission( ctx.getAccount( ) );
    LOG.info("Triggering cache population in Walrus for: " + ret.getDisplayName());
    if (ret instanceof ImageMetadata.StaticDiskImage && ret.getRunManifestLocation() != null) {
        StaticDiskImages.prepare(ret.getRunManifestLocation());
    }
    return ret;
}

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

public static ImageInfo lookupImage(String imageId) {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {/*from   w  ww.  j  av a2s. c o m*/
        final ImageInfo found = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        db.commit();
        return found;
    } catch (final NoSuchElementException ex) {
        db.rollback();
        throw ex;
    } catch (final Exception ex) {
        db.rollback();
        throw Exceptions.toUndeclared(ex);
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

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//from   ww w .j a v  a  2s. c  om
 * @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:com.eucalyptus.images.Images.java

public static void enableImage(String imageId) throws NoSuchImageException {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {//from   w w  w  .  j  a  v a2s .  c om
        final ImageInfo img = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        img.setState(ImageMetadata.State.available);
        db.commit();
    } catch (final NoSuchElementException e) {
        db.rollback();
        throw new NoSuchImageException("Failed to lookup image: " + imageId, e);
    } catch (final Exception e) {
        db.rollback();
        throw new NoSuchImageException("Failed to lookup image: " + imageId, e);
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

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  .  j  a  v  a  2s  .co 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/*  ww 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//  w w w  . j a v a  2 s .  co m
 * 
 * @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();
    }
}