Example usage for javax.persistence EntityTransaction isActive

List of usage examples for javax.persistence EntityTransaction isActive

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction isActive.

Prototype

public boolean isActive();

Source Link

Document

Indicate whether a resource transaction is in progress.

Usage

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

/**
 * Retrieve the application list./*  w w w.java 2s.co m*/
 * The fields not requested for the list are cleaned.
 * @return The list of applications
 */
private List<Application> retrieveApplicationList() {
    List<Application> lstApps;
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        lstApps = em.createNamedQuery("applications.all", Application.class).getResultList();
        et.commit();
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to retrieve the Application list");
        log.error(re);
        throw new RuntimeException("Impossible to access the " + "application list");
    } finally {
        em.close();
    }
    if (lstApps != null) {
        for (Application ap : lstApps) {
            ap.setDescription(null);
            ap.setParameters(null);
        }
    }
    return lstApps;
}

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

@Override
public Object create(ODataUri uri, Object entity, EntityDataModel entityDataModel) throws ODataException {
    Object jpaEntity = entityMapper.convertODataEntityToDS(entity, entityDataModel);
    EntityManager entityManager = getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {//from   w w w . j  a  v  a  2  s.  c om
        transaction.begin();

        LOG.info("Persisting entity: {}", jpaEntity);
        entityManager.persist(jpaEntity);

        return entityMapper.convertDSEntityToOData(jpaEntity, entity.getClass(), entityDataModel);
    } finally {
        if (transaction.isActive()) {
            transaction.commit();
        } else {
            transaction.rollback();
        }
    }
}

From source file:org.apache.ranger.audit.provider.DbAuditProvider.java

private boolean commitTransaction() {
    boolean ret = false;
    EntityTransaction trx = null;

    try {//from   w  w  w.  j  a v  a2s  .  com
        trx = getTransaction();

        if (trx != null && trx.isActive()) {
            trx.commit();

            ret = true;
        } else {
            throw new Exception("trx is null or not active");
        }
    } catch (Exception excp) {
        logDbError("DbAuditProvider.commitTransaction(): failed", excp);

        cleanUp(); // so that next insert will try to init()
    } finally {
        clearEntityManager();
    }

    return ret;
}

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 {//from   w w w . ja v  a2s .com
        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   ww w .  j  a v a2s  .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:nl.b3p.kaartenbalie.struts.KaartenbalieCrudAction.java

/** Execute method which handles all incoming request.
 *
 * @param mapping action mapping/*from  w w  w  .ja  v  a 2s .c  om*/
 * @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:it.infn.ct.futuregateway.apiserver.v1.TaskCollectionService.java

/**
 * Retrieve a task list for the user./*  w w  w . ja v a  2s  . c  om*/
 * 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: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 {/* w  ww .j  a  v a2s.  c  om*/
        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:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java

@Override
public void remove() {

    if (taskAction != null) {
        Log log = taskAction.getLog();//w w w. java 2  s .c o  m
        log.debug("Removing task resource: " + getID());
        AbstractTask tsk = taskAction.getModel();
        boolean cleanUp = false;
        if (tsk != null) {
            if (!tsk.isDone()) {
                // task is still running cancel it and cleanup entity manager
                taskAction.setCancelled(true);
                log.debug("cancel task " + tsk.getWid());
                cleanUp = true;
                if (future != null) {
                    future.cancel(true);
                    try {
                        // give cancel some time
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        logger.debug(e);
                    }
                }

                try {
                    EntityManager em = taskAction.getEntityManager();
                    if (em != null && em.isOpen()) {
                        try {
                            EntityTransaction tx = em.getTransaction();
                            if (tx.isActive())
                                tx.rollback();
                        } finally {
                            em.close();
                        }
                    }
                } catch (Exception e) {
                    // don't bother with exceptions
                    log.debug("Exception on task future cancel: " + e.toString(), e);
                }
            }

            EntityManager em = home.getEntityManagerFactory().createEntityManager();
            TxFrame tx = new TxFrame(em);
            // cleanup if necessary
            try {
                try {
                    Task t = em.find(Task.class, tsk.getId());
                    t.setPostMortem(true);
                    tx.commit();

                    if (cleanUp) {
                        log.debug("Triggering task cleanup");
                        try {
                            taskAction.setOwnEntityManager(em);
                            taskAction.cleanUpOnFail(t);
                        } catch (Exception e) {
                            log.debug("Exception on cleanup: " + e.toString());
                        }
                    }

                    // remove task from db
                    log.debug("Removing task: " + t.getId());
                    tx.begin();
                    em.remove(t);
                    tx.commit();
                } finally {
                    tx.finish();
                    if (em.isOpen())
                        em.close();
                }
            } catch (Exception e) {
                log.debug("Exception on task resource removal: " + e.toString());
                e.printStackTrace();
            }
        }
    }
}

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 {//w  w w. jav  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();
    }
}