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:it.infn.ct.futuregateway.apiserver.v1.InfrastructureService.java

/**
 * Removes the infrastructure. Delete the infrastructure only if there are
 * not applications associated with it to avoid inconsistency in the DB.
 * <p>/*from www .j  av  a2 s .  co m*/
 * Infrastructures with associated applications can only be disabled to
 * avoid future execution of applications.
 *
 * @param id Id of the infrastructure to remove
 */
@DELETE
public final void deleteInfra(@PathParam("id") final String id) {
    Infrastructure infra;
    EntityManager em = getEntityManager();
    try {
        infra = em.find(Infrastructure.class, id);
        if (infra == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> appsForInfra = em.createNamedQuery("applications.forInfrastructure")
                    .setParameter("infraId", id).setMaxResults(1).getResultList();
            if (appsForInfra == null || appsForInfra.isEmpty()) {
                em.remove(infra);
            } else {
                throw new WebApplicationException("The infrastructure "
                        + "cannot be removed because there are associated " + "applications",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the infrastructure");
            throw new InternalServerErrorException("Errore to remove " + "the infrastructure " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new BadRequestException("Task '" + id + "' does not exist!");
    } finally {
        em.close();
    }
}

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

@Override
public CommentDto storeComment(Comment comment) throws CommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//ww w.  ja  v a 2  s  .  c o m
        tx.begin();
        CommentDto mergedComment = CommentDatabaseUtils.mergeComment(comment, em);
        tx.commit();
        return mergedComment;
    } catch (Exception e) {
        logger.error("Could not update or store comment: {}", ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();

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

From source file:de.peterspan.csv2db.converter.Converter.java

@Override
protected Void doInBackground() throws Exception {
    EntityTransaction tx = null;
    try {/*from  ww w.  j  a  v  a 2 s  .c o m*/
        tx = entityManager.getTransaction();
        tx.begin();
        List<String[]> allLines = readFile();

        double increment = 100.0 / allLines.size();
        double progress = 0.0;
        for (String[] line : allLines) {
            progress = progress + increment;
            setProgress((int) Math.round(progress));

            if (line[0].equals("locnumber")) {
                //This is the header! Create a single instance header object
                Header.getInstance().init(line);
                continue;
            }
            if (line[0].equals("")) {
                continue;
            }
            readLine(line);
        }

        entityManager.flush();
        tx.commit();

    } catch (HibernateException he) {
        log.error("An error occured. Tx will be rolledback!", he);
        if (tx != null) {
            tx.rollback();
        }
    }

    return null;
}

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

/**
 * Register a new infrastructure.// w w w  . j ava 2s  .co  m
 *
 * @param infra The infrastructure to register
 * @return The registered infrastructure
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Infrastructure createInfrastructure(final Infrastructure infra) {
    Date now = new Date();
    infra.setDateCreated(now);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        em.persist(infra);
        et.commit();
        log.debug("New infrastructure registered: " + infra.getId());
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to create the infrastructure");
        log.error(re);
    } finally {
        em.close();
    }
    return infra;
}

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

/**
 * Retrieve the application list./*from  w w w .  j  a v  a2s  .c o m*/
 * The fields not requested for the list are cleaned.
 * @return The list of applications
 */
private List<Infrastructure> retrieveInfrastructureList() {
    List<Infrastructure> lstInfras;
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        lstInfras = em.createNamedQuery("infrastructures.all", Infrastructure.class).getResultList();
        et.commit();
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new RuntimeException("Impossible to access the " + "infrastructures list");
    } finally {
        em.close();
    }
    if (lstInfras != null) {
        for (Infrastructure in : lstInfras) {
            in.setDescription(null);
            in.setParameters(null);
        }
    }
    return lstInfras;
}

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

/**
 * Removes the application. Delete the application only if there are not
 * tasks associated with it because tasks must be associated with an
 * application./*from  www.  j  a v  a 2  s. c  o m*/
 * <p>
 * Applications with associated tasks can only be disabled to avoid future
 * execution of new tasks. Nevertheless, a task can be associated with a
 * disabled application and in this case will stay waiting until the
 * application is enabled.
 *
 * @param id Id of the application to remove
 */
@DELETE
public final void deleteApp(@PathParam("id") final String id) {
    Application app;
    EntityManager em = getEntityManager();
    try {
        app = em.find(Application.class, id);
        if (app == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> taskForApp = em.createNamedQuery("tasks.forApplication").setParameter("appId", id)
                    .setMaxResults(1).getResultList();
            if (taskForApp == null || taskForApp.isEmpty()) {
                em.remove(app);
            } else {
                log.info("Application " + id + " has tasks and cannot be" + " deleted");
                throw new WebApplicationException(
                        "The application cannot " + "be removed because there are associated tasks",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the application");
            throw new InternalServerErrorException("Error to remove " + "the application " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the application list");
        log.error(re);
        throw new BadRequestException("Application '" + id + "' " + "does not exist!");
    } finally {
        em.close();
    }
}

From source file:com.edugility.substantia.substance.TestCasePerson.java

@Test
public void testingJPA() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
    assertNotNull(emf);/* w  w w  .j a  v  a2s  .  co  m*/

    final EntityManager em = emf.createEntityManager();
    assertNotNull(em);

    final EntityTransaction et = em.getTransaction();
    assertNotNull(et);
    et.begin();

    final Person p = new Person();
    em.persist(p);
    em.flush();
    assertFalse(p.isTransient());
    assertTrue(p.isVersioned());
    assertEquals(Long.valueOf(1L), p.getId());
    assertEquals(Integer.valueOf(1), p.getVersion());

    et.commit();
    et.begin();

    final Person p2 = em.find(Person.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    assertNotNull(p2);
    assertFalse(p2.isTransient());
    assertTrue(p2.isVersioned());
    assertEquals(Long.valueOf(1L), p2.getId());
    assertEquals(Integer.valueOf(1), p2.getVersion());

    et.commit();
    et.begin();

    final Person p3 = em.getReference(Person.class, 1L);
    assertNotNull(p3);
    assertFalse(p3.isTransient());
    assertTrue(p3.isVersioned());
    assertEquals(Long.valueOf(1L), p3.getId());
    assertEquals(Integer.valueOf(2), p3.getVersion());

    et.commit();
    et.begin();

    assertTrue(em.contains(p));
    em.remove(p);

    et.commit();

    em.close();

    emf.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 w  w w . j  a  v  a 2 s . 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:com.google.constructor.cip.orm.jpa.BaseJPAService.java

public void insert(T entity) {
    Validate.notNull(entity, "Null Entity parameter");
    EntityTransaction tx = getEntityManager().getTransaction();
    tx.begin();
    getEntityManager().persist(entity);//w ww . j  a  v a2 s. co  m
    tx.commit();
}

From source file:com.google.constructor.cip.orm.jpa.BaseJPAService.java

public void update(T entity, boolean refresh) {
    Validate.notNull(entity, "Null Entity parameter");
    EntityTransaction tx = getEntityManager().getTransaction();
    tx.begin();
    getEntityManager().merge(entity);//from   www  . j a v a  2  s  .c o m
    tx.commit();
}