List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:org.jspresso.hrsample.backend.ApplicationSessionTest.java
/** * Tests bug #1244. findById should return null for transient instances. *///from ww w. j av a2 s . c om @Test public void testTransientGetReturnsNull() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); final City city = hbc.getEntityFactory().createEntityInstance(City.class); City c1 = hbc.findById(city.getId(), EMergeMode.MERGE_KEEP, City.class); assertNull("findById should never return transient instances", c1); City c2 = hbc.getTransactionTemplate().execute(new TransactionCallback<City>() { @Override public City doInTransaction(TransactionStatus status) { hbc.cloneInUnitOfWork(city); return hbc.findById(city.getId(), EMergeMode.MERGE_KEEP, City.class); } }); assertNull("findById should never return transient instances", c2); }
From source file:com.javaetmoi.core.persistence.hibernate.TestLazyLoadingUtil.java
/** * Verify the {@link LazyInitializationException} is thrown when accessing entity relations * outside a transaction, a {@link ManyToOne} relationship in this test. *//*from w w w . j a v a 2 s .c om*/ @Test(expected = LazyInitializationException.class) public void lazyInitializationExceptionWithManyToOne() { // Load each entity in a transaction Address dbLyon = transactionTemplate.execute(new TransactionCallback<Address>() { public Address doInTransaction(TransactionStatus status) { Address address = (Address) sessionFactory.getCurrentSession().get(Address.class, 200); return address; } }); // At this step, transaction and session are closed dbLyon.getEmployee().getName(); }
From source file:org.drools.container.spring.beans.persistence.VariablePersistenceStrategyTest.java
@Test public void testTransactionsRollback() throws Exception { final List<?> list = new ArrayList<Object>(); PlatformTransactionManager txManager = (PlatformTransactionManager) ctx.getBean("txManager"); final Environment env = KnowledgeBaseFactory.newEnvironment(); env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, ctx.getBean("myEmf")); env.set(EnvironmentName.TRANSACTION_MANAGER, txManager); env.set(EnvironmentName.GLOBALS, new MapGlobalResolver()); env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[] { new JPAPlaceholderResolverStrategy(env), new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT) }); final KnowledgeStoreService kstore = (KnowledgeStoreService) ctx.getBean("kstore1"); final KnowledgeBase kbRollback = (KnowledgeBase) ctx.getBean("kbRollback"); TransactionTemplate txTemplate = new TransactionTemplate(txManager); final StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) txTemplate .execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { StatefulKnowledgeSession kNewSession = kstore.newStatefulKnowledgeSession(kbRollback, null, env);/*from w ww. java 2 s.com*/ kNewSession.setGlobal("list", list); kNewSession.insert(1); kNewSession.insert(2); return kNewSession; } }); final int sessionId = ksession.getId(); txTemplate = new TransactionTemplate(txManager); txTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ksession.insert(3); status.setRollbackOnly(); return null; } }); txTemplate = new TransactionTemplate(txManager); txTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ksession.fireAllRules(); return null; } }); assertEquals(2, list.size()); txTemplate = new TransactionTemplate(txManager); txTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ksession.insert(3); ksession.insert(4); return null; } }); txTemplate = new TransactionTemplate(txManager); txTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ksession.insert(5); ksession.insert(6); status.setRollbackOnly(); return null; } }); txTemplate = new TransactionTemplate(txManager); txTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ksession.fireAllRules(); return null; } }); assertEquals(4, list.size()); ksession.dispose(); // now load the ksession final StatefulKnowledgeSession ksession2 = JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId, kbRollback, null, env); txTemplate = new TransactionTemplate(txManager); txTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ksession2.setGlobal("list", list); ksession2.insert(7); ksession2.insert(8); return null; } }); txTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ksession2.fireAllRules(); return null; } }); assertEquals(6, list.size()); }
From source file:ca.uhn.fhir.jpa.dao.dstu3.FhirSystemDaoDstu3.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(BundleType.BATCHRESPONSE); OperationOutcome ooResp = new OperationOutcome(); resp.addEntry().setResource(ooResp); /*/*ww w . j a v a 2 s . c o 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 BundleEntryComponent nextRequestEntry : theRequest.getEntry()) { TransactionCallback<Bundle> callback = new TransactionCallback<Bundle>() { @Override public Bundle doInTransaction(TransactionStatus theStatus) { Bundle subRequestBundle = new Bundle(); subRequestBundle.setType(BundleType.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; BundleEntryComponent 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) { BundleEntryComponent nextEntry = resp.addEntry(); OperationOutcome oo = new OperationOutcome(); oo.addIssue().setSeverity(IssueSeverity.ERROR).setDiagnostics(caughtEx.getMessage()); nextEntry.setResource(oo); BundleEntryResponseComponent 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(IssueSeverity.INFORMATION) .setDiagnostics("Batch completed in " + delay + "ms"); return resp; }
From source file:org.motechproject.server.omod.sdsched.TxSyncManWrapperImplTest.java
public void testRegisterSynchronization() { // Create a synchronization to register, and call if successful final TrialTransactionSync txSync = new TrialTransactionSync(); Object retVal = txTempl.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { txSyncManWrapper.registerSynchronization(txSync); return TransactionSynchronizationManager.getSynchronizations().contains(txSync); }// www.j av a 2 s .c o m }); assertEquals(true, retVal); assertTrue(txSync.wasCalled()); }
From source file:org.openvpms.component.business.service.archetype.rule.ArchetypeRuleService.java
/** * Executes an operation in a transaction, as follows: * <ol>/* w w w .j av a2 s.co m*/ * <li>begin transaction * <li>execute <em>before</em> rules for {@code object} * <li>execute {@code operation} * <li>execute <em>after</em> rules for {@code object} * <li>commit on success/rollback on failure * </ol> * * @param name the name of the operation * @param object the object that will be supplied to before and after rules * @param operation the operation to execute */ private void execute(final String name, final IMObject object, final Runnable operation) { template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { executeRules(name, object, true); operation.run(); executeRules(name, object, false); return null; } }); }
From source file:jp.go.aist.six.util.core.persist.castor.CastorDatastore.java
public <K, T extends Persistable<K>> T load(final Class<T> type, final K identity) { T p_object = _executeTx("load", type, identity, new TransactionCallback<T>() { public T doInTransaction(final TransactionStatus status) { return getDao(type).load(identity); }/*ww w. j av a 2 s.c o m*/ }); return p_object; }
From source file:org.openremote.beehive.configuration.www.CommandsAPI.java
@PUT @Path("/{commandId}") public Response udpateCommand(@PathParam("commandId") Long commandId, final CommandDTOIn commandDTO) { final Command existingCommand = device.getCommandById(commandId); Command optionalCommandWithSameName = device.getCommandByName(commandDTO.getName()); if (optionalCommandWithSameName != null && !optionalCommandWithSameName.getId().equals(existingCommand.getId())) { return Response.status(Response.Status.CONFLICT) .entity(new ErrorDTO(409, "A command with the same name already exists")).build(); }//from w w w. jav a2s . co m return Response.ok(new CommandDTOOut( new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Command>() { @Override public Command doInTransaction(TransactionStatus transactionStatus) { // TODO: check for more optimal solution, e.g. go over existing attributes and update individually // and add/delete as required // -> currently delete and re-creates protocol / protocol_attr records protocolRepository.delete(existingCommand.getProtocol()); populateCommandFromDTO(existingCommand, commandDTO); commandRepository.save(existingCommand); return existingCommand; } }))).build(); }
From source file:se.inera.intyg.intygstjanst.web.integration.test.CertificateResource.java
@POST @Consumes(MediaType.APPLICATION_JSON)//from w ww . ja v a2 s . c om @Path("/") public Response insertCertificate(final CertificateHolder certificateHolder) { return transactionTemplate.execute(new TransactionCallback<Response>() { public Response doInTransaction(TransactionStatus status) { Certificate certificate = ConverterUtil.toCertificate(certificateHolder); try { OriginalCertificate originalCertificate = new OriginalCertificate(); originalCertificate.setReceived(new LocalDateTime()); // Call marshall from the modules ModuleApi to create XML for originalCertificate ModuleApi moduleApi = null; try { moduleApi = moduleRegistry.getModuleApi(certificateHolder.getType()); } catch (ModuleNotFoundException e) { LOGGER.error("Module {} not found ", certificateHolder.getType()); } if (moduleApi != null && moduleApi.marshall(certificate.getDocument()) != null) { originalCertificate.setDocument(moduleApi.marshall(certificate.getDocument())); } else { LOGGER.debug("Got null while populating with original_certificate"); originalCertificate.setDocument(certificate.getDocument()); } originalCertificate.setCertificate(certificate); entityManager.persist(certificate); entityManager.persist(originalCertificate); return Response.ok().build(); } catch (Throwable t) { status.setRollbackOnly(); LOGGER.warn("insert certificate with id " + certificate.getId() + " failed: " + t.getMessage()); return Response.serverError().build(); } } }); }