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.james.user.jpa.JPAUsersRepository.java

/**
 * Update the repository with the specified user object. A user object with
 * this username must already exist.// w  w w.  j  a v a 2s .  c om
 * 
 * @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.objectstorage.entities.upgrade.ObjectStorage400Upgrade.java

private static void generateCanonicaIDs() throws Exception {
    EntityTransaction tran = Entities.get(AccountEntity.class);
    try {// w w  w. j ava2 s . c  o m
        List<AccountEntity> accounts = Entities.query(new AccountEntity());
        if (accounts != null && accounts.size() > 0) {
            for (AccountEntity account : accounts) {
                if (account.getCanonicalId() == null || account.getCanonicalId().equals("")) {
                    account.populateCanonicalId();
                    LOG.debug("Assigning canonical id " + account.getCanonicalId() + " for account "
                            + account.getAccountNumber());
                }
            }
        }
        tran.commit();
    } catch (Exception e) {
        LOG.error("Failed to generate and assign canonical ids", e);
        tran.rollback();
        throw e;
    } finally {
        if (tran.isActive()) {
            tran.commit();
        }
    }
}

From source file:nl.b3p.kaartenbalie.service.MapFileListener.java

private void saveServiceProvider(String wmsUrl, String name) {
    Object identity = null;/*from   www.j av a  2s.  c om*/
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);

        EntityTransaction tx = em.getTransaction();
        tx.begin();

        try {
            String getCap = "&service=WMS&request=GetCapabilities&version=1.1.1";

            Long number = getUniqueAbbr(name, em);
            String abbr = name + number;

            ServiceProvider saveServiceProvider = WmsServerAction.saveServiceProvider(wmsUrl + getCap, null,
                    name, abbr, em);
            Organization org = (Organization) em.createQuery("FROM Organization WHERE name = :name")
                    .setParameter("name", organization).getSingleResult();
            WmsServerAction.addAllLayersToGroup(org, saveServiceProvider, em);

            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            log.error("Kan nieuwe server niet posten", ex);
        }
    } catch (Throwable e) {
        log.error("Exception occured while getting EntityManager: ", e);
    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * /*w  w  w . j  a  v  a2s  .c  o m*/
 * @param em
 *            entity manager
 * @throws PersistenceException
 *             if we blow up
 */
private static void createOrUpdateDBVersion(EntityManager em) throws PersistenceException {
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();

        try {
            DBVersionPO version = (DBVersionPO) em.createQuery("select version from DBVersionPO as version") //$NON-NLS-1$
                    .getSingleResult();
            version.setMajorVersion(IVersion.JB_DB_MAJOR_VERSION);
            version.setMinorVersion(IVersion.JB_DB_MINOR_VERSION);
            em.merge(version);
        } catch (NoResultException nre) {
            em.merge(new DBVersionPO(IVersion.JB_DB_MAJOR_VERSION, IVersion.JB_DB_MINOR_VERSION));
        }

        tx.commit();
    } catch (PersistenceException pe) {
        if (tx != null) {
            tx.rollback();
        }
        throw pe;
    }
}

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

@Override
public void deleteEvent(long eventId) throws NotFoundException, SchedulerServiceDatabaseException {
    EntityManager em = null;/*from  w w  w  . j a va  2s.  co  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)
 *//*  w  w w .j  ava2  s .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();
    }
}

From source file:org.opencastproject.comments.persistence.CommentDatabaseImpl.java

@Override
public void deleteComment(long commentId) throws CommentDatabaseException, NotFoundException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from  ww  w  .ja  va 2s. c  om*/
        tx.begin();
        Option<CommentDto> dto = CommentDatabaseUtils.find(Option.some(commentId), em, CommentDto.class);
        if (dto.isNone())
            throw new NotFoundException("Comment with ID " + commentId + " does not exist");

        CommentDatabaseUtils.deleteReplies(dto.get().getReplies(), em);

        dto.get().setReplies(new ArrayList<CommentReplyDto>());
        em.remove(dto.get());
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete comment: {}", ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();

        throw new CommentDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.apache.juddi.replication.ReplicationNotifier.java

@Deprecated
private Node getNode(String messageSender) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = null;
    try {/* w  ww .  j  a  va 2  s. c  om*/
        tx = em.getTransaction();
        tx.begin();
        Node api = new Node();
        org.apache.juddi.model.Node find = em.find(org.apache.juddi.model.Node.class, messageSender);
        if (find != null) {
            MappingModelToApi.mapNode(find, api);
        }
        tx.commit();
        return api;
    } catch (Exception ex) {
        log.error("error", ex);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        em.close();
    }
    return null;
}

From source file:nl.b3p.kaartenbalie.service.SecurityRealm.java

@Override
public Principal getAuthenticatedPrincipal(String username, String password) {
    Object identity = null;//ww w .  ja  va2 s. com
    EntityTransaction tx = null;
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.REALM_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.REALM_EM);
        tx = em.getTransaction();
        tx.begin();
        try {
            User user = (User) em.createQuery("from User u where " + "lower(u.username) = lower(:username) ")
                    .setParameter("username", username).getSingleResult();
            return user;
        } catch (NoResultException nre) {
            return null;
        }
    } catch (Exception e) {
        log.error("Exception getting authenticated user from database", e);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        if (tx != null && tx.isActive() && !tx.getRollbackOnly()) {
            tx.commit();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.REALM_EM);
    }
    return null;
}

From source file:it.infn.ct.futuregateway.apiserver.v1.TaskCollectionService.java

/**
 * Register a new task.//from www.  j a v a 2s  . co  m
 *
 * @param task The task to register
 * @return The task registered
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Task createTask(final Task task) {
    if (task.getApplicationId() == null) {
        throw new BadRequestException("A valid application for the task" + " must be provided");
    }
    task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool()));
    task.setDateCreated(new Date());
    task.setUserName(getUser());
    task.setStatus(Task.STATUS.WAITING);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        Application app = em.find(Application.class, task.getApplicationId());
        if (app == null) {
            throw new BadRequestException("Application id not valid");
        }
        task.setApplicationDetail(app);
        em.persist(task);
        et.commit();
        log.debug("New task registered: " + task.getId());
    } catch (BadRequestException bre) {
        throw bre;
    } catch (RuntimeException re) {
        log.error("Impossible to create a task");
        log.debug(re);
        throw re;
    } finally {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        em.close();
    }
    return task;
}