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.apache.juddi.subscription.SubscriptionNotifier.java

/**
 * Deletes the subscription. i.e. when it is expired.
 * @param subscription/*from   w  w w  . j  a  v a  2  s  .  c om*/
 */
protected void deleteSubscription(Subscription subscription) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        em.remove(subscription);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testUniqueApplicationName() throws Exception {
    ApplicationEntity applicationEntity = new ApplicationEntity("app");
    ApplicationEntity applicationEntity2 = new ApplicationEntity("app");

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();//from w  w  w .  ja va 2 s . co m
    this.entityManager.persist(applicationEntity);
    entityTransaction.commit();

    entityTransaction.begin();
    assertTrue(ApplicationEntity.hasApplication(this.entityManager, "app"));
    try {
        this.entityManager.persist(applicationEntity2);
        fail();
    } catch (PersistenceException e) {
        entityTransaction.rollback();
    }
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

/**
 * A utility class to load the user directory.
 * // w w w .  j  a  v a2  s.  com
 * @param user
 *          the user object
 */
public void addUser(JpaUser user) {

    // Create a JPA user with an encoded password.
    String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
    user = new JpaUser(user.getUsername(), encodedPassword, user.getOrganization(), user.getRoles());

    // Then save the user
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        em.persist(user);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.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 {/*from w  ww.ja  v  a2s. 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.apache.james.user.jpa.JPAUsersRepository.java

/**
 * @see//from w  w w .jav  a  2s .c  om
 * org.apache.james.user.lib.AbstractUsersRepository#doAddUser(java.lang.String, java.lang.String)
 */
protected void doAddUser(String username, String password) throws UsersRepositoryException {
    String lowerCasedUsername = username.toLowerCase();
    if (contains(lowerCasedUsername)) {
        throw new UsersRepositoryException(lowerCasedUsername + " already exists.");
    }
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        JPAUser user = new JPAUser(lowerCasedUsername, password, algo);
        entityManager.persist(user);
        transaction.commit();
    } catch (PersistenceException e) {
        getLogger().debug("Failed to save user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to add user" + username, e);
    } finally {
        entityManager.close();
    }
}

From source file:org.apache.juddi.v3.auth.jboss.JBossAuthenticator.java

public UddiEntityPublisher identify(String authInfo, String authorizedName) throws AuthenticationException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    Publisher publisher = null;/*  w  w w.j a  va 2 s . c o  m*/
    try {
        tx.begin();
        publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));

        AuthToken at = em.find(AuthToken.class, authInfo);
        if (at == null)
            throw new AuthTokenRequiredException(new ErrorMessage("E_authTokenRequired", authInfo));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return publisher;
}

From source file:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * {@inheritDoc}/*from ww w. ja va2 s.c  o  m*/
 */
@Override
public void removeRecord(final String id) throws RecordStorageException {
    if (id == null) {
        throw new RecordStorageException("parameter id is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final RecordDao dao = findRecordDao(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 RecordStorageException(e, "error removing record id: " + id);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not remove record id: " + id + ". no record with this id exists.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testKeyStoreEntityUniqueName() throws Exception {
    String keyStoreName = UUID.randomUUID().toString();
    KeyStoreEntity keyStoreEntity = new KeyStoreEntity(keyStoreName, KeyStoreType.PKCS12,
            "/home/fcorneli/test.p12", "test", 0);

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();/* w ww.j a v  a2s  .c om*/
    this.entityManager.persist(keyStoreEntity);
    entityTransaction.commit();

    KeyStoreEntity keyStoreEntity2 = new KeyStoreEntity(keyStoreName, KeyStoreType.PKCS12,
            "/home/fcorneli/test.p12", "test", 0);

    entityTransaction.begin();
    try {
        this.entityManager.persist(keyStoreEntity2);
        fail();
    } catch (PersistenceException e) {
        entityTransaction.rollback();
    }
}

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

public static void setImageState(String imageId, ImageMetadata.State state) throws NoSuchImageException {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {//from ww  w.j  a  v  a  2 s. c o m
        ImageInfo img = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        img.setState(state);
        db.commit();
    } catch (final Exception e) {
        db.rollback();
        throw new NoSuchImageException("Failed to update image state: " + imageId);
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:com.sdl.odata.datasource.jpa.JPADataSource.java

@Override
public void delete(ODataUri uri, EntityDataModel entityDataModel) throws ODataException {
    Option<Object> entity = extractEntityWithKeys(uri, entityDataModel);

    if (entity.isDefined()) {
        Object jpaEntity = entityMapper.convertODataEntityToDS(entity.get(), entityDataModel);
        if (jpaEntity != null) {
            EntityManager entityManager = getEntityManager();
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();//w w  w  . j a va2 s  .c o m

                Object attached = entityManager.merge(jpaEntity);
                entityManager.remove(attached);
            } catch (PersistenceException e) {
                LOG.error("Could not remove entity: {}", entity);
                throw new ODataDataSourceException("Could not remove entity", e);
            } finally {
                if (transaction.isActive()) {
                    transaction.commit();
                } else {
                    transaction.rollback();
                }
            }
        } else {
            throw new ODataDataSourceException("Could not remove entity, could not be loaded");
        }
    }
}