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:org.opennaas.core.security.acl.ACLManager.java

private void executeSqlQuery(String sqlQuery) {
    log.debug("Executing SQL query: [ " + sqlQuery + " ]");
    EntityManager em = securityRepository.getEntityManager();
    EntityTransaction et = em.getTransaction();
    et.begin();
    try {/*  w w w .ja  v  a2 s.co  m*/
        em.createNativeQuery(sqlQuery).executeUpdate();
        em.flush();
        et.commit();
        log.debug("SQL query executed.");
    } catch (Exception e) {
        log.error("Error executing SQL query, rollbacking", e);
        et.rollback();
    }
}

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

/**
 * Register a new task.//from  ww  w  .  ja v  a2  s .  c  o  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;
}

From source file:info.san.books.app.model.listener.LivreListener.java

@EventHandler
public void handle(LivreCreatedEvent e) {
    EntityManager em = Persistence.getInstance().createEntityManager();

    EntityTransaction t = em.getTransaction();

    t.begin();

    LivreEntry entry = new LivreEntry();
    entry.setEditeur(e.getEditeur());//from w  w  w.  jav a  2  s.  c  o m
    entry.setFormat(e.getFormat());
    entry.setImagePath(e.getImagePath());
    entry.setIsbn(e.getIsbn());
    entry.setLangue(e.getLangue());
    entry.setNbPage(e.getNbPage());
    entry.setResume(e.getResume());
    entry.setTitre(e.getTitre());
    entry.setTitreOriginal(e.getTitreOriginal());
    entry.setLu(e.isLu());
    entry.setPossede(e.isPossede());
    try {
        entry.setImageAsBase64(this.getImageAsBase64(e.getImagePath()));
    } catch (IOException ioe) {
        LivreListener.LOGGER.warn("Cannot save the thumbnail in database: ", ioe);
        entry.setImageAsBase64(null);
    }

    if (e.getSagaId() != null && !e.getSagaId().trim().isEmpty()) {
        SagaEntry saga = em.getReference(SagaEntry.class, e.getSagaId());
        entry.setSaga(saga);
    }

    em.persist(entry);

    t.commit();
}

From source file:com.github.jrh3k5.membership.renewal.mailer.service.jpa.JpaMembershipService.java

private void updateMembership(EntityManager entityManager, JpaMembershipRecord membership) {
    final EntityTransaction transaction = entityManager.getTransaction();
    try {/*from  w  ww .  j a v a2 s . c  om*/
        transaction.begin();
        entityManager.merge(membership);
        transaction.commit();
    } catch (RuntimeException e) {
        transaction.rollback();
        throw e;
    }
}

From source file:info.san.books.app.model.listener.LivreListener.java

@EventHandler
public void handle(LivreUpdatedEvent e) {
    EntityManager em = Persistence.getInstance().createEntityManager();

    EntityTransaction t = em.getTransaction();

    t.begin();

    LivreEntry entry = em.find(LivreEntry.class, e.getIsbn());
    entry.setEditeur(e.getEditeur());//from ww w .j  a v  a2  s .  c o  m
    entry.setFormat(e.getFormat());
    entry.setImagePath(e.getImagePath());
    entry.setIsbn(e.getIsbn());
    entry.setLangue(e.getLangue());
    entry.setNbPage(e.getNbPage());
    entry.setResume(e.getResume());
    entry.setTitre(e.getTitre());
    entry.setTitreOriginal(e.getTitreOriginal());
    entry.setLu(e.isLu());
    entry.setPossede(e.isPossede());
    try {
        entry.setImageAsBase64(this.getImageAsBase64(e.getImagePath()));
    } catch (IOException ioe) {
        LivreListener.LOGGER.warn("Cannot save the thumbnail in database: ", ioe);
        entry.setImageAsBase64(null);
    }

    if (e.getImagePath() == null || e.getImagePath().isEmpty()) {
        entry.setImageAsBase64(null);
    }

    if (e.getSagaId() != null && !e.getSagaId().trim().isEmpty()) {
        SagaEntry saga = em.getReference(SagaEntry.class, e.getSagaId());
        entry.setSaga(saga);
    } else {
        entry.setSaga(null);
    }

    t.commit();
}

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

/**
 * Removes the task. Task is deleted and all the associated activities and
 * or files removed./* w  ww.j  a va2s  .co  m*/
 *
 * @param id Id of the task to remove
 */
@DELETE
public final void deleteTask(@PathParam("id") final String id) {
    Task task;
    EntityManager em = getEntityManager();
    try {
        task = em.find(Task.class, id);
        if (task == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            em.remove(task);
            et.commit();
        } catch (RuntimeException re) {
            if (et != null && et.isActive()) {
                et.rollback();
            }
            log.error(re);
            log.error("Impossible to remove the task");
            em.close();
            throw new InternalServerErrorException("Errore to remove " + "the task " + id);
        }
        try {
            Storage store = getStorage();
            store.removeAllFiles(Storage.RESOURCE.TASKS, id);
        } catch (IOException ex) {
            log.error("Impossible to remove the directory associated with " + "the task " + id);
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the task list");
        log.error(re);
        throw new BadRequestException("Task '" + id + "' has a problem!");
    } finally {
        em.close();
    }
}

From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java

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

From source file:test.unit.be.fedict.trust.service.PersistenceTest.java

private void refresh() {
    // we clear the hibernate cache
    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.commit();/*from  w  w w . j  av  a  2s . c  o  m*/
    this.entityManager.clear();
    entityTransaction.begin();
}

From source file:facades.PersonFacadeDB.java

@Override
public RoleSchool addRole(String json, Integer id) throws NotFoundException {
    Person p = gson.fromJson(getPerson(id), Person.class);
    HashMap<String, String> map = new Gson().fromJson(json, new TypeToken<HashMap<String, String>>() {
    }.getType());/*from  w w  w . j  av  a  2 s . co  m*/

    String roleName = map.get("roleName");
    RoleSchool role;

    switch (roleName) {
    case "Teacher Assistant":
        //Create role
        RoleSchool ta = new TeacherAssistant();
        ta.setPerson(p);
        role = ta;
        break;
    case "Teacher":

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        String dateInString = map.get("date");
        Date date = new Date();

        try {
            date = formatter.parse(dateInString);
        } catch (ParseException e) {
            e.printStackTrace(System.out);
        }

        RoleSchool t = new Teacher(date, map.get("degree"));
        t.setPerson(p);
        role = t;
        break;
    case "Student":
        RoleSchool s = new Student(map.get("semester"));
        s.setPerson(p);
        role = s;
        break;
    default:
        throw new IllegalArgumentException("no such role");
    }
    //save this info
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    try {
        em.persist(role);
        transaction.commit();
        em.getEntityManagerFactory().getCache().evictAll();
    } catch (Exception e) {
        throw new NotFoundException("Couldnt add role");
    } finally {
        em.close();
    }

    return role;

}

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

/**
 * Uploads input files. The method store input files for the specified task.
 * Input files are provided as a <i>multipart form data</i> using the field
 * file. This can contains multiple file using the html input attribute
 * <i>multiple="multiple"</i> which allows to associate multiple files with
 * a single field.//from ww  w .j av a 2  s . c om
 *
 * @param id The task id retrieved from the url path
 * @param lstFiles List of file in the POST body
 */
@Path("/input")
@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public final void setInputFile(@PathParam("id") final String id,
        @FormDataParam("file") final List<FormDataBodyPart> lstFiles) {
    if (lstFiles == null || lstFiles.isEmpty()) {
        throw new BadRequestException("Input not accessible!");
    }
    EntityManager em = getEntityManager();
    Task task = em.find(Task.class, id);
    task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool()));
    if (task == null) {
        throw new NotFoundException("Task " + id + " does not exist");
    }
    for (FormDataBodyPart fdbp : lstFiles) {
        final String fName = fdbp.getFormDataContentDisposition().getFileName();
        try {
            Storage store = getStorage();
            store.storeFile(Storage.RESOURCE.TASKS, id, fdbp.getValueAs(InputStream.class), fName);
            EntityTransaction et = em.getTransaction();
            try {
                et.begin();
                task.updateInputFileStatus(fName, TaskFile.FILESTATUS.READY);
                et.commit();
            } catch (RuntimeException re) {
                if (et != null && et.isActive()) {
                    et.rollback();
                }
                log.error(re);
                log.error("Impossible to update the task");
                throw new InternalServerErrorException("Errore to update " + "the task");
            } finally {
                em.close();
            }
        } catch (IOException ex) {
            log.error(ex);
            throw new InternalServerErrorException("Errore to store input " + "files");
        }
    }
    em.close();
}