List of usage examples for javax.persistence LockModeType PESSIMISTIC_WRITE
LockModeType PESSIMISTIC_WRITE
To view the source code for javax.persistence LockModeType PESSIMISTIC_WRITE.
Click Source Link
From source file:org.tdmx.lib.control.service.ControlJobServiceRepositoryImpl.java
@Override @Transactional(value = "ControlDB") public List<ControlJob> reserve(int maxJobs) { ControlJobSearchCriteria sc = new ControlJobSearchCriteria(new PageSpecifier(0, maxJobs)); sc.setStatus(ControlJobStatus.NEW);//from w w w . j av a 2s. c om sc.setScheduledTimeBefore(new Date()); List<ControlJob> result = getControlJobDao().fetch(sc, LockModeType.PESSIMISTIC_WRITE); for (ControlJob e : result) { e.setStatus(ControlJobStatus.RUN); } // we rely on the transaction finishing on exit and persisting the data without us calling dao explicitly // later the caller shall call createOrUpdate to persist further job changes after running the job. return result; }
From source file:entity.service.EntryFacadeREST.java
@POST @Path("result/{raceid}") @Produces({ "application/json" }) public Response setRacetime(@PathParam("raceid") Integer raceid, ResultData resultData) { EntryPK key = new EntryPK(raceid, resultData.getRacenum()); Entry entry = em.find(Entry.class, key, LockModeType.PESSIMISTIC_WRITE); if (entry.getStatus().equals("CHECKED") && entry.getRacetime() == null) { entry.setFinishtime(new Date()); entry.setRacetime(resultData.getRacetime()); entry.applyResultmods(resultData, parameters.getResultmods()); entry.applyRaceadjustments(parameters.getRaceadjustmentsToRace(raceid)); entry.setStatus("FINISHED"); em.merge(entry);/* w w w .ja v a 2 s .c o m*/ } else { JsonObject jsonMsg = JsonBuilder.getJsonMsg( "Az eredmny mr rgztsre kerlt vagy nem a megfelel llapotban van!", JsonBuilder.MsgType.WARNING, null); return Response.status(500).entity(jsonMsg).build(); } String msg = "Eredmny rgztve: " + entry.getContestant().getName() + " (" + entry.getKey().getRacenum() + ") - " + Utils.simpleTimeFormat.format(entry.getRacetime()); JsonObject jsonMsg = JsonBuilder.getJsonMsg(msg, JsonBuilder.MsgType.INFO, null); NotificationEndpoint.send(msg); return Response.ok(jsonMsg).build(); }
From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java
@Override public boolean removeCluster(final Cluster cluster) { beginTransaction();//from w w w .j a va2 s . co m TagEntity tagEntity = getEntityManager().find(TagEntity.class, new TagId(cluster), LockModeType.PESSIMISTIC_WRITE); try { if (tagEntity == null) { LOG.error("Cluster {} hasn't been created", cluster); throw new MySQLTaskQueueException(); } if (tagEntity.getLocks() == 1) { LOG.error("Cluster {} is already locked, cannot remove.", cluster); throw new MySQLTaskQueueException(); } } catch (MySQLTaskQueueException e) { getEntityManager().getTransaction().rollback(); return false; } getEntityManager().remove(tagEntity); getEntityManager().getTransaction().commit(); return true; }
From source file:org.jasig.cas.ticket.registry.support.JpaLockingStrategy.java
/** {@inheritDoc} */ @Transactional(readOnly = false)/* ww w . j a va 2 s . c o m*/ public void release() { final Lock lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE); if (lock == null) { return; } // Only the current owner can release the lock final String owner = lock.getUniqueId(); if (uniqueId.equals(owner)) { lock.setUniqueId(null); lock.setExpirationDate(null); logger.debug("Releasing {} lock held by {}.", applicationId, uniqueId); entityManager.persist(lock); } else { throw new IllegalStateException("Cannot release lock owned by " + owner); } }
From source file:org.cleverbus.core.common.dao.ExternalCallDaoJpaImpl.java
@Override @SuppressWarnings("unchecked") public ExternalCall lockConfirmation(final ExternalCall extCall) { Assert.notNull(extCall, "the extCall must not be null"); Assert.isTrue(extCall.getState() != ExternalCallStateEnum.PROCESSING, "the extCall must not be locked in a processing state"); Assert.isTrue(em.contains(extCall), "the extCall must be attached"); em.lock(extCall, LockModeType.PESSIMISTIC_WRITE); extCall.setState(ExternalCallStateEnum.PROCESSING); return extCall; }
From source file:eu.clarin.cmdi.virtualcollectionregistry.VirtualCollectionRegistryMaintenanceImpl.java
protected void purgeDeletedCollections(EntityManager em, final Date nowDatePurge) { em.getTransaction().begin();/*ww w .ja va2s . com*/ TypedQuery<VirtualCollection> q = em.createNamedQuery("VirtualCollection.findAllByState", VirtualCollection.class); q.setParameter("state", VirtualCollection.State.DELETED); q.setParameter("date", nowDatePurge); q.setLockMode(LockModeType.PESSIMISTIC_WRITE); for (VirtualCollection vc : q.getResultList()) { vc.setState(VirtualCollection.State.DEAD); em.remove(vc); logger.debug("purged virtual collection (id={})", vc.getId()); } em.getTransaction().commit(); }
From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java
@Override public ProposalBag createBag(final ProposalBag bag, final long branchId) { Assert.notNull(bag, "No ProposalBag supplied !"); Assert.isNull(bag.getId(), "Id should not be set for creation !"); new TxCallback(this.getEmf()) { @Override// w ww. jav a 2 s . co m // @SuppressWarnings("unchecked") protected void executeInTransaction(final EntityManager em) { // Retrieve branch final ProposalBranch branch = em.find(ProposalBranch.class, branchId, LockModeType.PESSIMISTIC_WRITE); if (branch == null) { throw new ProposalBranchNotFoundException(); } // Retrieve base bag (parent bag) and lock the row // final Query findParentQuery = em.createNamedQuery(ProposalBag.FIND_LAST_BRANCH_BAG); // findParentQuery.setParameter("branchId", branchId); // findParentQuery.setLockMode(LockModeType.PESSIMISTIC_WRITE); // Persist bag with its parent // final ProposalBag parentBag = Iterables.getFirst(findParentQuery.getResultList(), null); // bag.setBaseProposal(parentBag); // em.persist(bag); // Persist bag with its parent bag.setBaseProposal(branch.getHead()); em.persist(bag); // Update branch head pointer branch.setHead(bag); em.merge(branch); } }; return bag; }
From source file:eu.clarin.cmdi.virtualcollectionregistry.VirtualCollectionRegistryMaintenanceImpl.java
protected void handleCollectionsInError(EntityManager em, final Date nowDateError) { em.getTransaction().begin();//w ww . j a v a 2 s. c o m TypedQuery<VirtualCollection> q = em.createNamedQuery("VirtualCollection.findAllByState", VirtualCollection.class); q.setParameter("state", VirtualCollection.State.ERROR); q.setParameter("date", nowDateError); q.setLockMode(LockModeType.PESSIMISTIC_WRITE); for (VirtualCollection vc : q.getResultList()) { VirtualCollection.State currentState = vc.getState(); logger.info("Found [{}] in error state.", vc.getName(), currentState); //TODO: handle virtual collections in error state } em.getTransaction().commit(); }
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 . j a v a 2 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:entity.service.EntryFacadeREST.java
@POST @Path("resultmod/{raceid}") @Produces({ "application/json" }) public Response applyResultmod(@PathParam("raceid") Integer raceid, ResultData resultData) { EntryPK key = new EntryPK(raceid, resultData.getRacenum()); Entry entry = em.find(Entry.class, key, LockModeType.PESSIMISTIC_WRITE); if (entry.getStatus().equals("FINISHED") && entry.getRacetime() != null) { entry.applyResultmods(resultData, parameters.getResultmods()); em.merge(entry);/*from w w w .ja v a 2s. c om*/ } else { JsonObject jsonMsg = JsonBuilder.getJsonMsg("Az eredmny nem a megfelel llapotban van!", JsonBuilder.MsgType.WARNING, null); return Response.status(500).entity(jsonMsg).build(); } String msg = "Eredmny mdost ttel alkalmazva: " + entry.getContestant().getName() + " (" + entry.getKey().getRacenum() + ") - " + Utils.simpleTimeFormat.format(entry.getRacetime()); JsonObject jsonMsg = JsonBuilder.getJsonMsg(msg, JsonBuilder.MsgType.INFO, null); NotificationEndpoint.send(msg); return Response.ok(jsonMsg).build(); }