List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:org.motechproject.server.omod.sdsched.TxSyncManWrapperImplTest.java
public void testIsSyncActive() { Object retVal = txTempl.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { return txSyncManWrapper.isSynchronizationActive(); }/* w ww . j a v a 2 s . co m*/ }); assertEquals(true, retVal); }
From source file:org.surfnet.cruncher.message.Aggregator.java
/** * Use the given LoginEntries to aggregate data in the database. * This will//from w ww . ja v a 2s . c o m * @param loginEntries */ public AggregateCounts aggregateLogin(final List<LoginEntry> loginEntries) { if (loginEntries == null) { throw new IllegalArgumentException("List of loginEntries cannot be null."); } AggregateCounts counts = transactionTemplate.execute(new TransactionCallback<AggregateCounts>() { @Override public AggregateCounts doInTransaction(TransactionStatus status) { AggregateCounts result = new AggregateCounts(); for (LoginEntry le : loginEntries) { result.total += 1; //aggregate the login if (entryForDayExists(le)) { LOG.trace("Updating existing aggregated record for date {}, record: {}", le.getLoginDate(), le); statisticsRepository.updateAggregated(le.getIdpEntityId(), le.getSpEntityId(), le.getLoginDate()); result.aggregated_update += 1; } else { LOG.trace("Inserting aggregated record for date {}, record: {}", le.getLoginDate(), le); statisticsRepository.insertAggregated(le); result.aggregated_insert += 1; } //aggregate for the user if (entryForUserExists(le)) { LOG.trace("Updating existing aggregated record for date {}, record: {}", le.getLoginDate(), le); statisticsRepository.updateLastLogin(le.getUserId(), le.getSpEntityId(), le.getLoginDate()); result.user_update += 1; } else { LOG.trace("Inserting aggregated record for date {}, record: {}", le.getLoginDate(), le); statisticsRepository.insertLastLogin(le); result.user_insert += 1; } //update the unique user login table if (!entryForUniqueUserExists(le)) { LOG.trace("Inserting unique user login record for user {}, record: {}", le.getUserId(), le); statisticsRepository.insertUniqueLoginInCache(le); } } if (loginEntries.size() > 0) { statisticsRepository.setLoginEntriesProcessed(loginEntries); } /* * If we have moved from one month to the other, we need to update * the unique user logins for this month. */ statisticsRepository.aggregateUniqueLoginsIfNeeded(); return result; } }); return counts; }
From source file:com.hypersocket.netty.Main.java
protected void createApplicationContext() { if (log.isInfoEnabled()) { log.info("Creating spring application context"); }/*w w w. j a va 2 s .c o m*/ applicationContext = new ClassPathXmlApplicationContext("classpath*:/applicationContext.xml"); if (log.isInfoEnabled()) { log.info("Obtaining platform transaction manager"); } PlatformTransactionManager transactionManager = (PlatformTransactionManager) applicationContext .getBean("transactionManager"); if (log.isInfoEnabled()) { log.info("Creating transaction template"); } TransactionTemplate txnTemplate = new TransactionTemplate(transactionManager); if (log.isInfoEnabled()) { log.info("Calling TransactionTemplate.afterPropertiesSet"); } txnTemplate.afterPropertiesSet(); if (log.isInfoEnabled()) { log.info("Creating transaction for upgrade"); } txnTemplate.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { UpgradeService upgradeService = (UpgradeService) applicationContext.getBean("upgradeService"); try { if (log.isInfoEnabled()) { log.info("Starting upgrade"); } upgradeService.upgrade(); if (log.isInfoEnabled()) { log.info("Completed upgrade"); } } catch (Throwable e) { log.error("Failed to upgrade", e); throw new IllegalStateException("Errors upgrading database"); } return null; } }); }
From source file:org.atomserver.core.dbstore.DBBasedAtomCollection.java
protected <T> T executeTransactionally(final TransactionalTask<T> task) { final String t_user = AtomServerUserInfo.getUser(); FutureTask<T> timeoutTask = null; try {/*from w ww . ja v a 2s .co m*/ // create new timeout task timeoutTask = new FutureTask<T>(new Callable() { public T call() throws Exception { return (T) getTransactionTemplate().execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { AtomServerUserInfo.setUser(t_user); StopWatch stopWatch = new AtomServerStopWatch(); try { // NOTE: we will actually wait for all of these to possibly finish, // unless the methods below honor InterruptedExceptions // BUT the transaction will still be rolled back eventually by the catch below. getWriteEntriesDAO().acquireLock(); return task.execute(); } catch (Exception ee) { if (ee instanceof EntryNotFoundException && (((EntryNotFoundException) ee) .getType() == EntryNotFoundException.EntryNotFoundType.DELETE)) { log.warn("Exception in DB transaction", ee); } else { log.error("Exception in DB transaction", ee); } // the following is not really required, but ensures that this will rollback, without question transactionStatus.setRollbackOnly(); if (ee instanceof InterruptedException) { // InterruptedException - if the current thread was interrupted while waiting // Re-assert the thread's interrupted status Thread.currentThread().interrupt(); } // NOTE: per the Spring manual, a transaction is ONLY rolled back // when a RuntimeException is thrown!!! // And the timeout causes an InterruptedException (via task.cancel()), // which is NOT Runtime!! // (AtomServerException extends RuntimeException) throw (ee instanceof AtomServerException) ? (AtomServerException) ee : new AtomServerException("A " + ee.getCause().getClass().getSimpleName() + " caught in Transaction", ee.getCause()); } finally { stopWatch.stop("DB.txn", "DB.txn"); } } }); } }); // start timeout task in a new thread new Thread(timeoutTask).start(); // wait for the execution to finish, timeout after X secs int timeout = (getTransactionTemplate().getTimeout() > 0) ? getTransactionTemplate().getTimeout() : DEFAULT_TXN_TIMEOUT; return timeoutTask.get(timeout, TimeUnit.SECONDS); } catch (AtomServerException ee) { log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage()); throw ee; } catch (ExecutionException ee) { log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage()); throw (ee.getCause() == null) ? new AtomServerException("A " + ee.getClass().getSimpleName() + " caught in Transaction", ee) : (ee.getCause() instanceof AtomServerException) ? (AtomServerException) ee.getCause() : new AtomServerException( "A " + ee.getCause().getClass().getSimpleName() + " caught in Transaction", ee.getCause()); } catch (Exception ee) { log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage()); throw new AtomServerException("A " + ee.getClass().getSimpleName() + " caught in Transaction", ee); } finally { // NOTE: We MUST call timeoutTask.cancel() here. // This is the ONLY way that we see an InterruptedException in the transaction task, // and thus, the ONLY way that we can make the transaction rollback. // NOTE: Calling cancel() on a completed task is a noop. log.debug("@@@@@@@@@@@@@@ Calling task.cancel"); timeoutTask.cancel(true); timeoutTask = null; } }
From source file:org.openremote.beehive.configuration.www.DevicesAPI.java
@DELETE @Path("/{deviceId}") public Response deleteDevice(@PathParam("deviceId") Long deviceId) { final Device existingDevice = account.getDeviceById(deviceId); new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Object>() { @Override/*ww w . j a v a 2 s. c om*/ public Object doInTransaction(TransactionStatus transactionStatus) { account.removeDevice(existingDevice); deviceRepository.delete(existingDevice); return null; } }); return Response.ok().build(); }
From source file:org.ensembl.gti.seqstore.database.JdbcSeqStore.java
@Override public void storeGene(long sessionId, Gene gene) { log.debug("Storing gene " + gene.getStableId() + " in session " + sessionId); transactionTemplate.execute(new TransactionCallback<Void>() { @Override// w ww. j a v a 2 s . c om public Void doInTransaction(TransactionStatus status) { String chk = storeSequence(sessionId, gene.getSequence()); String locStr = SeqStoreHashUtils.locationToString(gene); String modelHash = SeqStoreHashUtils.hashGeneModel(gene); try { template.update(STORE_GENE_SQL, gene.getStableId(), gene.getGenomeId(), locStr, modelHash, chk, sessionId); } catch (DuplicateKeyException e) { String msg = "Cannot store gene " + gene.getStableId() + " as it already exists"; log.error(msg, e); throw new DuplicateSeqObjException(msg, e); } for (Transcript t : gene.getTranscripts()) { storeTranscript(sessionId, gene.getGenomeId(), t); } return null; } }); for (Exon e : gene.getExons()) { storeExon(sessionId, gene.getGenomeId(), e); } log.debug("Completed storing gene " + gene.getStableId() + " in session " + sessionId); }
From source file:jp.go.aist.six.util.core.persist.castor.CastorDatastore.java
public <K, T extends Persistable<K>> int count(final Class<T> type, final Binding filter) { Integer p_count = _executeTx("count", type, filter, new TransactionCallback<Integer>() { public Integer doInTransaction(final TransactionStatus status) { return getDao(type).count(filter); }/*from w w w .j a v a 2s . c o m*/ }); return p_count.intValue(); }
From source file:org.openvpms.component.business.service.archetype.ArchetypeServiceListenerTestCase.java
/** * Verifies that callbacks are invoked on transaction commit. *///from w ww . j a v a 2 s.c om @Test public void testTransactionRemove() { final IArchetypeService service = getArchetypeService(); final Party person1 = createPerson(); final Party person2 = createPerson(); service.save(person1); service.save(person2); final Listener listener = new Listener(); service.addListener("party.customerperson", listener); template.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { listener.setInTransaction(true); service.remove(person1); assertTrue(listener.getRemoving().contains(person1)); assertFalse(listener.getRemoved().contains(person1)); service.remove(person2); assertTrue(listener.getRemoving().contains(person2)); assertFalse(listener.getRemoved().contains(person2)); listener.setInTransaction(false); return null; } }); Set<IMObject> removed = listener.getRemoved(); Set<IMObject> removing = listener.getRemoving(); assertEquals(2, removed.size()); assertTrue(removing.equals(removed)); }
From source file:ca.uhn.fhir.jpa.dao.FhirSystemDaoDstu2.java
private Bundle batch(final RequestDetails theRequestDetails, Bundle theRequest) { ourLog.info("Beginning batch with {} resources", theRequest.getEntry().size()); long start = System.currentTimeMillis(); TransactionTemplate txTemplate = new TransactionTemplate(myTxManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); Bundle resp = new Bundle(); resp.setType(BundleTypeEnum.BATCH_RESPONSE); OperationOutcome ooResp = new OperationOutcome(); resp.addEntry().setResource(ooResp); /*//from w w w . j av a2 s . co m * For batch, we handle each entry as a mini-transaction in its own database transaction so that if one fails, it doesn't prevent others */ for (final Entry nextRequestEntry : theRequest.getEntry()) { TransactionCallback<Bundle> callback = new TransactionCallback<Bundle>() { @Override public Bundle doInTransaction(TransactionStatus theStatus) { Bundle subRequestBundle = new Bundle(); subRequestBundle.setType(BundleTypeEnum.TRANSACTION); subRequestBundle.addEntry(nextRequestEntry); Bundle subResponseBundle = transaction((ServletRequestDetails) theRequestDetails, subRequestBundle, "Batch sub-request"); return subResponseBundle; } }; BaseServerResponseException caughtEx; try { Bundle nextResponseBundle = txTemplate.execute(callback); caughtEx = null; Entry subResponseEntry = nextResponseBundle.getEntry().get(0); resp.addEntry(subResponseEntry); /* * If the individual entry didn't have a resource in its response, bring the sub-transaction's OperationOutcome across so the client can see it */ if (subResponseEntry.getResource() == null) { subResponseEntry.setResource(nextResponseBundle.getEntry().get(0).getResource()); } } catch (BaseServerResponseException e) { caughtEx = e; } catch (Throwable t) { ourLog.error("Failure during BATCH sub transaction processing", t); caughtEx = new InternalErrorException(t); } if (caughtEx != null) { Entry nextEntry = resp.addEntry(); OperationOutcome oo = new OperationOutcome(); oo.addIssue().setSeverity(IssueSeverityEnum.ERROR).setDiagnostics(caughtEx.getMessage()); nextEntry.setResource(oo); EntryResponse nextEntryResp = nextEntry.getResponse(); nextEntryResp.setStatus(toStatusString(caughtEx.getStatusCode())); } } long delay = System.currentTimeMillis() - start; ourLog.info("Batch completed in {}ms", new Object[] { delay }); ooResp.addIssue().setSeverity(IssueSeverityEnum.INFORMATION) .setDiagnostics("Batch completed in " + delay + "ms"); return resp; }
From source file:org.openremote.beehive.configuration.www.ControllerConfigurationsAPI.java
@PUT @Path("/{configurationId}") public Response updateControllerConfiguration(@PathParam("configurationId") Long configurationId, final ControllerConfigurationDTOIn configurationDTO) { final ControllerConfiguration existingConfiguration = account .getControllerConfigurationById(configurationId); ControllerConfiguration optionalControllerConfigurationWithSameName = account .getControllerConfigurationByName(configurationDTO.getName()); if (optionalControllerConfigurationWithSameName != null && !optionalControllerConfigurationWithSameName.getId().equals(existingConfiguration.getId())) { return Response.status(Response.Status.CONFLICT) .entity(new ErrorDTO(409, "A controller configuration with the same name already exists")) .build();//from w ww . j a v a 2 s .c o m } return Response.ok(new ControllerConfigurationDTOOut(new TransactionTemplate(platformTransactionManager) .execute(new TransactionCallback<ControllerConfiguration>() { @Override public ControllerConfiguration doInTransaction(TransactionStatus transactionStatus) { existingConfiguration.setCategory(configurationDTO.getCategory()); existingConfiguration.setName(configurationDTO.getName()); existingConfiguration.setValue(configurationDTO.getValue()); controllerConfigurationRepository.save(existingConfiguration); return existingConfiguration; } }))).build(); }