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:it.attocchi.jpa2.JpaController.java

public int executeUpdate(String query, Object... params) throws Exception {
    int res = 0;/*from   www  .j  ava 2 s  .  co  m*/

    EntityManager em = getEntityManager();

    try {
        if (!globalTransactionOpen)
            em.getTransaction().begin();

        Query q = em.createQuery(query);

        if (params != null) {
            int i = 1;
            for (Object o : params) {
                q.setParameter(i, o);
                i++;
            }
        }

        res = q.executeUpdate();

        if (!globalTransactionOpen)
            em.getTransaction().commit();

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

    return res;
}

From source file:nl.b3p.viewer.util.SelectedContentCache.java

public JSONObject getSelectedContent(HttpServletRequest request, Application app, boolean validXmlTags,
        boolean includeAppLayerAttributes, boolean includeRelations, EntityManager em,
        boolean shouldProcessCache) throws JSONException {

    // Don't use cache when any of these parameters is true, cache only
    // the JSON variant used when starting up the viewer
    boolean useExpanded = includeAppLayerAttributes || includeRelations;

    JSONObject cached = null;//ww w  . j a va 2 s .c  om
    if (mustCreateNewCache(app, validXmlTags, useExpanded)) {
        cached = createSelectedContent(app, validXmlTags, includeAppLayerAttributes, includeRelations, em);
        if (!validXmlTags) {
            ClobElement el = new ClobElement(cached.toString());
            app.getDetails().put(
                    useExpanded ? DETAIL_CACHED_EXPANDED_SELECTED_CONTENT : DETAIL_CACHED_SELECTED_CONTENT, el);
            setApplicationCacheDirty(app, false, useExpanded, em);
            em.getTransaction().commit();
        }
    } else {
        ClobElement el = app.getDetails()
                .get(useExpanded ? DETAIL_CACHED_EXPANDED_SELECTED_CONTENT : DETAIL_CACHED_SELECTED_CONTENT);
        cached = new JSONObject(el.getValue());
    }
    if (shouldProcessCache) {
        JSONObject selectedContent = processCache(request, cached, em);
        return selectedContent;
    } else {
        return cached;
    }
}

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

private ApplicationSettings getApplicationSettings() {
    if (applicationSettings == null) {
        EntityManager entityManager = getServletEntityManager();
        synchronized (entityManager) {
            TypedQuery<ApplicationSettings> query = entityManager
                    .createQuery("SELECT x FROM ApplicationSettings x", ApplicationSettings.class);
            List<ApplicationSettings> resultList = query.getResultList();
            if (resultList == null || resultList.isEmpty()) {
                applicationSettings = new ApplicationSettings();
                entityManager.getTransaction().begin();
                try {
                    entityManager.persist(applicationSettings);
                    entityManager.getTransaction().commit();
                } catch (RuntimeException e) {
                    entityManager.getTransaction().rollback();
                    throw e;
                }//from w w  w.j a  v a 2 s  .  c om
            } else {
                applicationSettings = resultList.get(0);
            }
        }
    }
    return applicationSettings;
}

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

/**
 * Retrieves the current model and checks if its lifetime is already exceeded.
 * In this case the model's TaskState will be set to {@code failed} and a {@link FailedException} is thrown,
 * which will stop the the main loop in {@code execute()}.
 *
 * Otherwise, the model's TaskState is set to {@code newState} and {@link #transit(TaskState, AbstractTask)}
 * will be invoked,//  w  w w  . j av a 2 s. co m
 * which calls a method corresponding to the TaskState {@code newState} and throws a {@code TransitException} after its
 * execution specifying the next TaskSate value for the model.
 *
 * The model is made persistent by the EntityManager and the changed model will be 
 * commited to the database.
 * If something goes wrong while commiting the new model, a stable rollback is assured.
 *
 * @param newState the new TaskState for the model
 */
@SuppressWarnings({ "CaughtExceptionImmediatelyRethrown", "ThrowableInstanceNeverThrown" })
private void transit(final TaskState newState) {

    if (getCancelled()) {
        log.debug("cancelled");
        throw new StopException(TaskState.IN_PROGRESS_UNKNOWN);
    }

    EntityManager em = getEntityManager();
    @NotNull
    AbstractTask model = getModel();

    // this throws a stop exception on timeout
    if (!(TaskState.FINISHED.equals(newState) || TaskState.FAILED.equals(newState)))
        checkTimeout(model, em);

    try {
        em.getTransaction().begin();
        if (newState != null) {
            if (!em.contains(model)) {
                log.debug("model not in EntityManager");
                try {
                    try {
                        em.persist(model);
                    } catch (EntityExistsException e) {
                        log.debug("persisting failed merging", e);
                        rewindTransaction(em.getTransaction());
                        em.merge(model);
                    }
                } catch (RuntimeException e2) {
                    log.debug("probably persisting and merging failed", e2);
                    rewindTransaction(em.getTransaction());
                    final @NotNull AbstractTask newModel = em.find(AbstractTask.class, model.getId());
                    model.mold(newModel);
                    newModel.refresh(em);
                    setModel(newModel);
                    model = getModel();
                    log.debug("completed renewing of model");
                }
            }
        }

        model.transit(newState);

        boolean committed = false;
        try {
            em.getTransaction().commit();
            //                em.flush( );
            committed = true;
        } catch (Exception e) {
            log.debug("commit of transit (" + newState.name() + ") model failed ", e);
            try {
                rewindTransaction(em.getTransaction());
                // if this point is reached s.th. is terribly foobared
                // restore backup and fail
                model = Copier.copy(false, backup);
                em.merge(model);
                // backup should be clean so commit mustn't fail.
                model.fail(e);
                em.getTransaction().commit();
            } catch (Exception e2) {
                log.debug("restoring previous version failed", e2);
                try {
                    // refresh em for final commit
                    EntityManagerAux.rollbackAndClose(em);
                } catch (RuntimeException e3) {
                    log.debug("rollback old em failed", e3);
                }

                EntityManager nem = emf.createEntityManager();
                TxFrame tx = new TxFrame(nem);
                try {
                    log.debug("loading fresh model");
                    model = nem.find(model.getClass(), backup.getId());
                    boolean unkown = (model == null);
                    model = Copier.copy(false, backup);
                    model.fail(e2);
                    if (unkown)
                        nem.persist(model);
                    //     else
                    //         nem.merge( model );
                    tx.commit();
                    setModel(model);
                } catch (RuntimeException e3) {
                    log.debug("exception during refresh: ", e3);
                    throw e3;
                } finally {
                    tx.finish();
                    setOwnEntityManager(nem);
                    em = nem;
                }
            }
        }

        // if model could be commited it has a clean state
        // refresh backup
        if (committed)
            setBackup(Copier.copy(false, model));

        final TaskState modelState = model.getState();
        refreshTaskResource();
        //noinspection HardcodedFileSeparator
        trace("on" + modelState + "()", null);
        transit(modelState, model);
    }
    // for debugging
    catch (RuntimeException e) {
        throw e;
    } finally {
        try {
            // for debuggin'
            boolean ta = em.getTransaction().isActive();
            if (ta) {
                log.debug("final rollback");
                em.getTransaction().rollback();
            }
        } catch (Exception e) {
            log.debug("final rollback failed", e);
        }
    }
}

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

private void runPayload() {
    // Set thread name
    Thread.currentThread().setName(threadName);

    // One log per launch?
    if (System.out instanceof MultiplexPrintStream) {
        String fileName = StringUtils.leftPad("" + this.job.getId(), 10, "0");
        MultiplexPrintStream mps = (MultiplexPrintStream) System.out;
        mps.registerThread(String.valueOf(fileName + ".stdout.log"));
        mps = (MultiplexPrintStream) System.err;
        mps.registerThread(String.valueOf(fileName + ".stderr.log"));
    }//w  w  w .ja  v a2  s  .  c  om

    EntityManager em = null;
    final Map<String, String> params;
    final JarClassLoader jobClassLoader;

    // Block needing the database
    try {
        em = Helpers.getNewEm();

        // Refresh entities from the current EM
        this.job = em.find(JobInstance.class, job.getId());
        this.node = em.find(Node.class, job.getNode().getId());

        // Log
        this.resultStatus = State.SUBMITTED;
        jqmlogger.debug("A loader/runner thread has just started for Job Instance " + job.getId() + ". Jar is: "
                + job.getJd().getJarPath() + " - class is: " + job.getJd().getJavaClassName());

        // Disabled
        if (!this.job.getJd().isEnabled()) {
            jqmlogger.info("Job Instance " + job.getId()
                    + " will actually not truly run as its Job Definition is disabled");
            em.getTransaction().begin();
            this.job.setProgress(-1);
            em.getTransaction().commit();
            resultStatus = State.ENDED;
            endOfRun();
            return;
        }

        // Parameters
        params = new HashMap<String, String>();
        for (RuntimeParameter jp : em
                .createQuery("SELECT p FROM RuntimeParameter p WHERE p.ji = :i", RuntimeParameter.class)
                .setParameter("i", job.getId()).getResultList()) {
            jqmlogger.trace("Parameter " + jp.getKey() + " - " + jp.getValue());
            params.put(jp.getKey(), jp.getValue());
        }

        // Update of the job status, dates & co
        em.getTransaction().begin();
        em.refresh(job, LockModeType.PESSIMISTIC_WRITE);
        if (!job.getState().equals(State.KILLED)) {
            // Use a query to avoid locks on FK checks (with setters, every field is updated!)
            em.createQuery(
                    "UPDATE JobInstance j SET j.executionDate = current_timestamp(), state = 'RUNNING' WHERE j.id = :i")
                    .setParameter("i", job.getId()).executeUpdate();
        }
        em.getTransaction().commit();

        jobClassLoader = this.clm.getClassloader(job, em);
    } catch (JqmPayloadException e) {
        jqmlogger.warn("Could not resolve CLASSPATH for job " + job.getJd().getApplicationName(), e);
        resultStatus = State.CRASHED;
        endOfRun();
        return;
    } catch (MalformedURLException e) {
        jqmlogger.warn("The JAR file path specified in Job Definition is incorrect "
                + job.getJd().getApplicationName(), e);
        resultStatus = State.CRASHED;
        endOfRun();
        return;
    } catch (RuntimeException e) {
        firstBlockDbFailureAnalysis(e);
        return;
    } finally {
        Helpers.closeQuietly(em);
    }

    // Class loader switch
    classLoaderToRestoreAtEnd = Thread.currentThread().getContextClassLoader();
    try {
        // Switch
        jqmlogger.trace("Setting class loader");
        Thread.currentThread().setContextClassLoader(jobClassLoader);
        jqmlogger.trace("Class Loader was set correctly");
    } catch (Exception e) {
        jqmlogger.error("Could not switch classloaders", e);
        this.resultStatus = State.CRASHED;
        endOfRun();
        return;
    }

    // Go! (launches the main function in the startup class designated in the manifest)
    try {
        jobClassLoader.launchJar(job, params);
        this.resultStatus = State.ENDED;
    } catch (JqmKillException e) {
        jqmlogger.info("Job instance  " + job.getId() + " has been killed.");
        this.resultStatus = State.KILLED;
    } catch (Exception e) {
        jqmlogger.info("Job instance " + job.getId() + " has crashed. Exception was:", e);
        this.resultStatus = State.CRASHED;
    }

    // Job instance has now ended its run
    try {
        endOfRun();
    } catch (Exception e) {
        jqmlogger.error("An error occurred while finalizing the job instance.", e);
    }

    jqmlogger.debug("End of loader for JobInstance " + this.job.getId() + ". Thread will now end");
}

From source file:op.allowance.PnlAllowance.java

private PnlTX getPnlTX(Resident resident, final Allowance allowance) {
    final BigDecimal editAmount = allowance != null ? allowance.getAmount() : null;
    final Allowance allow = (allowance == null ? new Allowance(resident) : allowance);

    return new PnlTX(allow, new Closure() {
        @Override/*from   w ww  . ja v  a  2s  . co m*/
        public void execute(Object o) {
            if (o != null) {

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();
                    final Allowance myAllowance = em.merge((Allowance) o);
                    em.lock(em.merge(myAllowance.getResident()), LockModeType.OPTIMISTIC);
                    em.getTransaction().commit();

                    DateTime txDate = new DateTime(myAllowance.getPit());

                    final String keyResident = myAllowance.getResident().getRID();
                    final String keyYear = myAllowance.getResident().getRID() + "-" + txDate.getYear();
                    final String keyMonth = myAllowance.getResident().getRID() + "-" + txDate.getYear() + "-"
                            + txDate.getMonthOfYear();

                    if (!lstResidents.contains(myAllowance.getResident())) {
                        lstResidents.add(myAllowance.getResident());
                        Collections.sort(lstResidents);
                    }

                    if (!cashmap.containsKey(keyMonth)) {
                        cashmap.put(keyMonth,
                                AllowanceTools.getMonth(myAllowance.getResident(), myAllowance.getPit()));
                    } else {

                        if (cashmap.get(keyMonth).contains(myAllowance)) {
                            cashmap.get(keyMonth).remove(myAllowance);
                        }
                        cashmap.get(keyMonth).add(myAllowance);

                        Collections.sort(cashmap.get(keyMonth));
                    }

                    // little trick to fix the carries
                    if (editAmount != null) {
                        updateCarrySums(myAllowance.getResident(), new LocalDate(myAllowance.getPit()),
                                editAmount.negate());
                    }
                    // add the new / edited amount
                    updateCarrySums(myAllowance);

                    createCP4(myAllowance.getResident());

                    try {
                        if (cpMap.get(keyResident).isCollapsed())
                            cpMap.get(keyResident).setCollapsed(false);
                        if (cpMap.get(keyYear).isCollapsed())
                            cpMap.get(keyYear).setCollapsed(false);
                        if (cpMap.get(keyMonth).isCollapsed())
                            cpMap.get(keyMonth).setCollapsed(false);
                    } catch (PropertyVetoException e) {
                        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                    }

                    buildPanel();

                    GUITools.scroll2show(jspCash, cpMap.get(keyMonth), cpsCash, new Closure() {
                        @Override
                        public void execute(Object o) {
                            GUITools.flashBackground(linemap.get(myAllowance), Color.YELLOW, 2);
                        }
                    });

                } catch (OptimisticLockException ole) {
                    OPDE.warn(ole);
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                        OPDE.getMainframe().emptyFrame();
                        OPDE.getMainframe().afterLogin();
                    }
                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                } catch (Exception e) {
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    OPDE.fatal(e);
                } finally {
                    em.close();
                }

            }
        }
    });
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * handle the update and save process./*  w ww  .j  a  v  a  2  s .  c  o m*/
 *
 * @param entity the newsdrilldown entity
 * @throws Exception the exception
 */
private void handle(UXBEntity entity) throws Exception {
    /**
     * Due to a hibernate problem when updating or saving a newsdrilldown with
     * related categories we have to perform these step for saving the newsdrilldown
     *
     * 1. save/update all categories and remove them from the newsdrilldown
     *    1.1 save/update all metaCategories and remove them from the categories
     *    1.2 save the categories
     *    1.3 read all metaCategories to the categories
     *    1.4 save the categories again to create the relations
     * 2. save the newsdrilldown
     * 3. read all categories to the newsdrilldown
     */

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        News news = buildNews(entity);
        List<Long> categories = new ArrayList<Long>();

        /*
        * 1. update or save all categories
        * Steps 1.1 - 1.4
        */
        if (news.getCategories() != null && !news.getCategories().isEmpty()) {
            for (NewsCategory cat : news.getCategories()) {
                cat = saveNewsCategory(cat);
                if (!categories.contains(cat.getFs_id())) {
                    categories.add(cat.getFs_id());
                }
            }
            news.setCategories(new ArrayList<NewsCategory>());
        }

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        // 2. save the newsdrilldown
        news = saveNews(news, em);

        // 3. read all categories to the newsdrilldown
        if (!categories.isEmpty()) {
            for (Long cat : categories) {
                NewsCategory ncat = getNewsCategory(cat, news.getLanguage(), em);
                news.getCategories().add(ncat);
            }
        }

        tx.commit();

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves all the existing AnnotationStatus
 * @return/*ww w.  j ava2  s .  c  o m*/
 */
public List<AnnotationStatus> retrieveAnnotationStatus() {
    //   EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        List<AnnotationStatus> annotationstatus = em.createQuery("from AnnotationStatus").getResultList();
        tx.commit();
        return annotationstatus;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println(
                "[RetrieveAnnotationStatus.retrieveAnnotationStatus] unable to retrieve AnnotationStatus"
                        + " cause : " + e.getMessage());
        return new ArrayList<AnnotationStatus>();
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves an AnnotationStatus in the database according to the specified label
 * @param label//from   w  w w  .j  av a 2s . c o  m
 * @return an AnnotationStatus that may be a new UriStatus with no value.
 */
public AnnotationStatus retrieveAnnotationStatus(String label) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        AnnotationStatus annotationstatus = (AnnotationStatus) em
                .createQuery("from AnnotationStatus where label = ?").setParameter(1, label).getSingleResult();
        tx.commit();
        return annotationstatus;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println(
                "[RetrieveAnnotationStatus.retrieveAnnotationStatus] unable to retrieve AnnotationStatus"
                        + " label : " + label + " cause : " + e.getMessage());
        return new AnnotationStatus();
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves a list of Annotation according to the specified label
 * @param label//from  w  w  w.java 2  s. co  m
 * @return
 */
public List<Annotation> retrieveAnnotation(String label) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        //List docs = em.createQuery("from Annotation where label = '" + label + "'").getResultList();
        List<Annotation> docs = ((List<Annotation>) em.createQuery("from Annotation where label = ?")
                .setParameter(1, label).getResultList());
        tx.commit();
        return docs;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotation] unable to retrieve Annotation" + " label : "
                + label + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}