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.v3.auth.JUDDIAuthenticator.java

public UddiEntityPublisher identify(String authInfo, String authorizedName) throws AuthenticationException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {// w  w w.j  a v  a2 s. co 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: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 www .  j  a v a 2s. c o m*/
 *
 * @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();
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default remove: bring back to persistence context if required and delete
 * /*  w w w  .jav  a2s .c o m*/
 * @param obj
 *            object to remove
 * @return remove object
 * @throws Exception
 *             on errors (transaction is being rolled back)
 */
public T remove(T obj) throws Exception {
    if (obj == null) {
        return null;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        T tmp = em.contains(obj) ? obj : em.merge(obj);
        em.remove(tmp);
        t.commit();
        return tmp;
    } catch (Exception e) {
        t.rollback();
        throw e;
    }
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default merge/* w  ww .j  a v a  2 s .  co m*/
 * 
 * @param objs
 *            objects to merge
 * @return list of merged/managed objects
 * @throws MergeException
 *             on errors (transaction is being rolled back)
 */
public Collection<T> merge(Collection<T> objs) throws MergeException {
    if (objs == null || objs.isEmpty()) {
        return null;
    }
    final Collection<T> tmp = new ArrayList<T>();
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        for (T obj : objs) {
            tmp.add(em.merge(obj));
        }
        t.commit();
        return tmp;
    } catch (Exception e) {
        t.rollback();
        throw new MergeException("Cannot merge changes to " + String.valueOf(objs) + " into the database", e);
    }
}

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

/**
 * Retrieve a task list for the user./*  w  w  w. j av  a  2s.c  o  m*/
 * Tasks are retrieved from the storage for the user performing the request.
 *
 * @return A list of tasks
 */
private List<Task> retrieveTaskList() {
    List<Task> lstTasks = new LinkedList<>();
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    List<Object[]> taskList = null;
    try {
        et = em.getTransaction();
        et.begin();
        taskList = em.createNamedQuery("tasks.userAll").setParameter("user", getUser()).getResultList();
        et.commit();
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to retrieve the task list");
        log.error(re);
        throw new RuntimeException("Impossible to access the task list");
    } finally {
        em.close();
    }
    if (taskList != null && !taskList.isEmpty()) {
        for (Object[] elem : taskList) {
            int idElem = 0;
            Task tmpTask = new Task();
            tmpTask.setId((String) elem[idElem++]);
            tmpTask.setDescription((String) elem[idElem++]);
            tmpTask.setStatus((Task.STATUS) elem[idElem++]);
            tmpTask.setDateCreated((Date) elem[idElem]);
            lstTasks.add(tmpTask);
        }
    }
    return lstTasks;
}

From source file:test.unit.be.fedict.eid.applet.beta.PersistenceTest.java

@After
public void tearDown() throws Exception {
    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    LOG.debug("entity manager open: " + this.entityManager.isOpen());
    LOG.debug("entity transaction active: " + entityTransaction.isActive());
    if (entityTransaction.isActive()) {
        if (entityTransaction.getRollbackOnly()) {
            entityTransaction.rollback();
        } else {//  w ww  . j a va 2  s . c o m
            entityTransaction.commit();
        }
    }
    this.entityManager.close();
}

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

public UddiEntityPublisher identify(String authInfo, String authorizedName) throws AuthenticationException {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   ww  w . ja  va 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:nl.b3p.kaartenbalie.struts.KaartenbalieCrudAction.java

/** Execute method which handles all incoming request.
 *
 * @param mapping action mapping// ww w  . ja v a  2s .  c  o m
 * @param dynaForm dyna validator form
 * @param request servlet request
 * @param response servlet response
 *
 * @return ActionForward defined by Apache foundation
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) method.">
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Object identity = null;

    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        ActionForward forward = null;
        String msg = null;

        EntityManager em = getEntityManager();
        EntityTransaction tx = em.getTransaction();

        try {
            tx.begin();

            forward = super.execute(mapping, form, request, response);

            tx.commit();

            return forward;
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured, rollback", e);

            if (e instanceof org.hibernate.JDBCException) {
                msg = e.toString();
                SQLException sqle = ((org.hibernate.JDBCException) e).getSQLException();
                msg = msg + ": " + sqle;
                SQLException nextSqlE = sqle.getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else if (e instanceof java.sql.SQLException) {
                msg = e.toString();
                SQLException nextSqlE = ((java.sql.SQLException) e).getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else {
                msg = e.toString();
            }

            addAlternateMessage(mapping, request, null, msg);
        }

        try {
            tx.begin();

            prepareMethod((DynaValidatorForm) form, request, LIST, EDIT);

            tx.commit();
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured in second session, rollback", e);

            addAlternateMessage(mapping, request, null, e.toString());
        }
    } catch (Throwable e) {
        log.error("Exception occured while getting EntityManager: ", e);
        addAlternateMessage(mapping, request, null, e.toString());

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }

    return getAlternateForward(mapping, request);
}

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();/*  w  w  w  . jav  a 2s  .  c o m*/
    try {
        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:org.opencastproject.comments.persistence.CommentDatabaseImpl.java

@Override
public CommentDto storeComment(Comment comment) throws CommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   w ww.  j  av a  2s. 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();
    }
}