Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Initializes a TaskAction by denoting an EntityManager and a model.
 *
 * The model is made persistent by the EntityManager.
 * The EntityManager and the model are stored, using {@code setOwnEntityManager()} and {@code setModelAndBackup()}.
 * A Backup of the model is done./*w ww .  ja  va2  s . com*/
 *
 *
 * @param em an EntityManager, storing AbstractTasks
 * @param model an AbstractTask to be stored as model of {@code this} and to be stored in the database
 */
public void initFromModel(final EntityManager em, AbstractTask model) {

    boolean wasActive = em.getTransaction().isActive();
    if (!wasActive)
        em.getTransaction().begin();
    try {
        final boolean contained = em.contains(model);
        if (!contained) {
            try {
                em.persist(model);
            } catch (EntityExistsException e) {
                model = em.merge(model);
            }
        }
        if (!wasActive)
            em.getTransaction().commit();
        setOwnEntityManager(em);
        setModelAndBackup(model);
    } finally {
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();
    }
}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 *
 * Retrieves the AbstractTask from the database, which corresponds to {@code getModel()).
 * It is marked as done, by invoking {@code setDone(true)} on it and restored to the database.
 *
 * It will be set as {@code this}' the new model by calling {@code setModelAndBackup()}, which also makes a backup
 * of the new model.// w  ww  . j  a va 2  s.c om
 *
 */
private void markAsDone() {
    final @NotNull AbstractTask model = getModel();
    if (!(getCancelled() || model.isDone())) {
        final EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            AbstractTask newModel = em.find(AbstractTask.class, getModel().getId());
            newModel.setDone(true);
            em.getTransaction().commit();
            setModelAndBackup(newModel);
        } catch (RuntimeException e) {
            trace("Non throwable exception: ", e);
        } finally {
            try {
                if (em.getTransaction().isActive())
                    em.getTransaction().rollback();
            } catch (RuntimeException e) {
                trace("Non throwable exception: ", e);
            }
        }
    }
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public ApplicationSettings updateApplicationSettings(ApplicationSettings applicationSettings) {
    if (applicationSettings == null) {
        return getApplicationSettings();
    } else {//from w w  w.  j a v  a  2s .c o  m
        EntityManager entityManager = getServletEntityManager();
        synchronized (entityManager) {
            User user = getSessionUser();
            if (user.getAdmin()) {
                entityManager.getTransaction().begin();
                try {
                    entityManager.merge(applicationSettings);
                    entityManager.getTransaction().commit();
                    this.applicationSettings = applicationSettings;
                    return applicationSettings;
                } catch (RuntimeException e) {
                    entityManager.getTransaction().rollback();
                    throw e;
                }
            } else {
                throw new SecurityException();
            }
        }
    }
}

From source file:com.enioka.jqm.tools.JobManagerHandler.java

private Integer addDeliverable(String path, String fileLabel) throws IOException {
    Deliverable d = null;/*  ww w  .  j a v  a  2  s  . c  o m*/
    EntityManager em = Helpers.getNewEm();
    try {
        this.ji = em.find(JobInstance.class, ji.getId());

        String outputRoot = this.ji.getNode().getDlRepo();
        String ext = FilenameUtils.getExtension(path);
        String relDestPath = "" + ji.getJd().getApplicationName() + "/" + ji.getId() + "/" + UUID.randomUUID()
                + "." + ext;
        String absDestPath = FilenameUtils.concat(outputRoot, relDestPath);
        String fileName = FilenameUtils.getName(path);
        FileUtils.moveFile(new File(path), new File(absDestPath));
        jqmlogger.debug("A deliverable is added. Stored as " + absDestPath + ". Initial name: " + fileName);

        em.getTransaction().begin();
        d = Helpers.createDeliverable(relDestPath, fileName, fileLabel, this.ji.getId(), em);
        em.getTransaction().commit();
    } finally {
        em.close();
    }
    return d.getId();
}

From source file:de.zib.gndms.infra.system.GNDMSystem.java

/**
 * Refreshes all resources corresponding to a specific GNDMPersistentServiceHome
 * @param home the GNDMPersistentServiceHome,whose Resource will be refreshed
 * @param <M>  the model type//from w ww.j  a  va 2  s  . c  o  m
 */
@SuppressWarnings({ "ConstantConditions" })
public final <M extends GridResource> void refreshAllResources(
        final @NotNull GNDMPersistentServiceHome<M> home) {
    final EntityManager manager = home.getEntityManagerFactory().createEntityManager();
    try {
        try {
            manager.getTransaction().begin();
            for (String id : listAllResources(home, manager)) {
                try {
                    if (isDebugging())
                        logger.debug("Restoring " + home.getNickName() + ':' + id);
                    home.find(home.getKeyForId(id));
                } catch (ResourceException e) {
                    logger.warn(e);
                }
            }
            manager.getTransaction().commit();
        } finally {
            if (manager.getTransaction().isActive())
                manager.getTransaction().rollback();
        }
    } finally {
        if (manager.isOpen())
            manager.close();
    }
}

From source file:de.zib.gndms.infra.system.GNDMSystem.java

/**
 * Returns a list of all {@link org.globus.wsrf.Resource}s, which are managed by an EntityManager, corresponding to
 * the given EntityManagerFactory and//  w  w  w.j av  a2s  .  com
 * which are managed by the {@code GNDMPersistentServiceHome} {@link de.zib.gndms.infra.system.GNDMSystemDirectory#getHome(Class)}    
 *
 * @param emg the factory to create the EntityManager, used for the {@code list all} query
 * @param clazz the class, whose corresponding GNDMPersistentServiceHome will be used for the query.(See {@link de.zib.gndms.infra.system.GNDMSystemDirectory#homes})
 * @param <M> the model type
 * @return  a list of all {@code Resources}, corresponding to a specific EntityManager and GNDMPersistentServiceHome.
 */
public final @NotNull <M extends GridResource> List<String> listAllResources(
        final @NotNull EntityManagerFactory emg, final @NotNull Class<M> clazz) {
    final EntityManager manager = emg.createEntityManager();
    List<String> retList = null;
    try {
        try {
            manager.getTransaction().begin();
            retList = listAllResources(getInstanceDir().getHome(clazz), manager);
            manager.getTransaction().commit();
        } finally {
            if (manager.getTransaction().isActive())
                manager.getTransaction().rollback();
        }
    } finally {
        if (manager.isOpen())
            manager.close();
    }
    return retList;
}

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    try {//from   w w w.  ja va 2  s.co m
        CurrentUser currentUser = CurrentUser.getInstance();
        Map<String, String> persistenceMap = Utils.getInstance().getPersistenceMap();
        EntityManager entityManager = Persistence.createEntityManagerFactory("mg_PU", persistenceMap)
                .createEntityManager();
        entityManager.getTransaction().begin();

        List<TblEntidades> list = (List<TblEntidades>) entityManager.createQuery("select e from TblEntidades e")
                .getResultList();

        for (TblEntidades e : list) {
            String nombreviejo = e.getNombres();
            if (nombreviejo.contains(",")) {
                String[] parts = nombreviejo.split(",");
                e.setNombres(parts[0].trim());
                e.setApellidos(parts[1].trim());
                entityManager.merge(e);
            }
        }

        entityManager.getTransaction().commit();
        entityManager.getTransaction().begin();
        JOptionPane.showMessageDialog(null, "Nombres actualizados!");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
    }
}

From source file:nl.b3p.viewer.solr.SolrUpdateJob.java

@Override
public void execute(JobExecutionContext jec) throws JobExecutionException {
    log.info("Starting updating of the solr index.");
    server = SolrInitializer.getServerInstance();

    if (server == null) {
        log.error("Could not locate solr server. Terminate updating of index.");
        return;/*from  ww w.ja  v a2s .com*/
    }

    try {
        Stripersist.requestInit();
        EntityManager em = Stripersist.getEntityManager();
        WaitPageStatus status = new WaitPageStatus() {
            @Override
            public void setCurrentAction(String currentAction) {
                // no debug logging
                super.currentAction.set(currentAction);
            }

            @Override
            public void addLog(String message) {
                // no debug logging
                logs.add(message);
            }
        };

        List<SolrConf> configs = em.createQuery("FROM SolrConf", SolrConf.class).getResultList();
        for (SolrConf solrConfiguration : configs) {
            removeSolrConfigurationFromIndex(solrConfiguration, em, server);
            insertSolrConfigurationIntoIndex(solrConfiguration, em, status, server);
        }
        em.getTransaction().commit();

        log.info("Updating index complete.");
    } catch (Exception e) {
        log.error("Error", e);
    } finally {
        Stripersist.requestComplete();
    }
}

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    Map<String, String> persistenceMap = Utils.getInstance().getPersistenceMap();
    EntityManager entityManager = Persistence.createEntityManagerFactory("mg_PU", persistenceMap)
            .createEntityManager();// w w w  .  ja v  a 2  s  . c  om
    entityManager.getTransaction().begin();
    int suma = 0;
    List<TblTransferencias> listT = (List<TblTransferencias>) entityManager
            .createQuery("select t from TblTransferencias t").getResultList();
    for (TblTransferencias t : listT) {
        Integer sumAtAporte = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
        Integer sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
        if (t.getMontoAporte() < sumAtAporte) {
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (sumAtAporte - t.getTblAsientosTemporalesList().get(i).getMonto()
                            - t.getMontoAporte() == 0) {
                        System.out.println(t.getTblAsientosTemporalesList().get(i).getId());
                        suma += t.getTblAsientosTemporalesList().get(i).getMonto();
                        t.getTblAsientosTemporalesList().get(i).setMonto(0);
                        sumAtAporte = t.getTblAsientosTemporalesList().stream()
                                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
                        System.out.println(suma);
                        entityManager.merge(t);
                    }
                }
            }
        }
        if (t.getMontoDonacion() < sumAtDonacion) {
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (!t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (sumAtDonacion - t.getTblAsientosTemporalesList().get(i).getMonto()
                            - t.getMontoDonacion() == 0) {
                        System.out.println(t.getTblAsientosTemporalesList().get(i).getId());
                        suma += t.getTblAsientosTemporalesList().get(i).getMonto();
                        t.getTblAsientosTemporalesList().get(i).setMonto(0);
                        sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
                        System.out.println(suma);
                        entityManager.merge(t);
                    }
                }
            }
        }

    }
    for (TblTransferencias t : listT) {
        Integer sumAtAporte = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
        Integer sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
        if (t.getMontoAporte() < sumAtAporte) {
            int asientoValido = -1;
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (t.getTblAsientosTemporalesList().get(i).getMonto().equals(t.getMontoAporte())) {
                        asientoValido = t.getTblAsientosTemporalesList().get(i).getId();
                        for (int ii = 0; ii < t.getTblAsientosTemporalesList().size(); ii++) {
                            if (t.getTblAsientosTemporalesList().get(ii).getEsAporte()
                                    && t.getTblAsientosTemporalesList().get(ii).getId() != asientoValido) {
                                suma += t.getTblAsientosTemporalesList().get(ii).getMonto();
                                t.getTblAsientosTemporalesList().get(ii).setMonto(0);
                            }
                        }
                        entityManager.merge(t);
                    }
                }
            }
        }
        if (t.getMontoDonacion() < sumAtDonacion) {
            int asientoValido = -1;
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (!t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (t.getTblAsientosTemporalesList().get(i).getMonto().equals(t.getMontoDonacion())) {
                        asientoValido = t.getTblAsientosTemporalesList().get(i).getId();
                        for (int ii = 0; ii < t.getTblAsientosTemporalesList().size(); ii++) {
                            if (!t.getTblAsientosTemporalesList().get(ii).getEsAporte()
                                    && t.getTblAsientosTemporalesList().get(ii).getId() != asientoValido) {
                                suma += t.getTblAsientosTemporalesList().get(ii).getMonto();
                                t.getTblAsientosTemporalesList().get(ii).setMonto(0);
                            }
                        }
                        entityManager.merge(t);
                    }
                }
            }
        }
    }
    entityManager.getTransaction().commit();
    entityManager.getTransaction().begin();
    JOptionPane.showMessageDialog(null, suma);
}

From source file:com.enioka.jqm.tools.Loader.java

/**
 * Part of the endOfRun process that needs the database. May be deferred if the database is not available.
 */// w w w .  jav  a  2  s . co m
void endOfRunDb() {
    EntityManager em = Helpers.getNewEm();

    try {
        // Retrieve the object to update
        job = em.find(JobInstance.class, this.job.getId());

        // Which end time should we use? Default is always use DB time to avoid time lips between servers.
        Date dbTimeTmp = em.createQuery("SELECT current_timestamp() AS A from GlobalParameter", Date.class)
                .getSingleResult();
        Calendar dbTime = Calendar.getInstance();
        dbTime.setTime(dbTimeTmp);
        if (!this.isDelayed) {
            // In case of delayed finalization, use the stored time instead of db time.
            this.endDate = dbTime;
        }

        // Done: put inside history & remove instance from queue.
        em.getTransaction().begin();
        History h = Helpers.createHistory(job, em, this.resultStatus, endDate);
        jqmlogger.trace("An History was just created for job instance " + h.getId());
        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", job.getId()).executeUpdate();
        em.getTransaction().commit();
    } catch (RuntimeException e) {
        endBlockDbFailureAnalysis(e);
    } finally {
        Helpers.closeQuietly(em);
    }
}