Example usage for javax.persistence EntityManager refresh

List of usage examples for javax.persistence EntityManager refresh

Introduction

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

Prototype

public void refresh(Object entity, LockModeType lockMode);

Source Link

Document

Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type.

Usage

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * @param s//  w ww. j  a va2s  .  co m
 *            session which contain object to refresh
 * @param po
 *            object to refresh
 * @param lockMode
 *            lock Mode for refresh operation
 * @throws PMDirtyVersionException
 *             in case of version conflict
 * @throws PMAlreadyLockedException
 *             if object is locked
 * @throws PMException
 *             if rollback failed
 * @throws ProjectDeletedException
 *             if the project was deleted in another instance
 */
public void refreshPO(EntityManager s, IPersistentObject po, LockModeType lockMode)
        throws PMDirtyVersionException, PMAlreadyLockedException, PMException, ProjectDeletedException {

    Validate.notNull(s, Messages.NoNullValueAllowed);
    try {
        s.refresh(po, lockMode);
    } catch (PersistenceException e) {
        PersistenceManager.handleDBExceptionForMasterSession(po, e);
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void deleteJob(int idJob) {
    jqmlogger.trace("Job status number " + idJob + " will be deleted");
    EntityManager em = null;

    try {//  w w  w .jav  a2s .c  o m
        em = getEm();

        // Two transactions against deadlock.
        JobInstance job = em.find(JobInstance.class, idJob);
        em.getTransaction().begin();
        em.refresh(job, LockModeType.PESSIMISTIC_WRITE);
        if (job.getState().equals(State.SUBMITTED)) {
            job.setState(State.CANCELLED);
        }
        em.getTransaction().commit();

        if (!job.getState().equals(State.CANCELLED)) {
            // Job is not in queue anymore - just return.
            return;
        }

        em.getTransaction().begin();
        em.createQuery("DELETE FROM Message WHERE ji = :i").setParameter("i", job.getId()).executeUpdate();
        em.createQuery("DELETE FROM RuntimeParameter WHERE ji = :i").setParameter("i", job.getId())
                .executeUpdate();
        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", job.getId()).executeUpdate();
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException(
                "An attempt was made to delete a job instance that did not exist.");
    } catch (Exception e) {
        throw new JqmClientException("could not delete a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

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"));
    }//from w  w w.jav  a 2s.  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");
}