List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:com.vladmihalcea.HibernateEagerSetTest.java
@Test public void testFixByPersistingChild() { final Long parentId = cleanAndSaveParent(); SetParent parent = transactionTemplate.execute(new TransactionCallback<SetParent>() { @Override/*from ww w.j a v a 2 s .c o m*/ public SetParent doInTransaction(TransactionStatus transactionStatus) { SetParent parent = loadParent(parentId); SetChild child1 = new SetChild(); child1.setName("child1"); SetChild child2 = new SetChild(); child2.setName("child2"); entityManager.persist(child1); entityManager.persist(child2); parent.addChild(child1); parent.addChild(child2); entityManager.merge(parent); parent.getChildren().size(); return parent; } }); assertEquals(2, parent.getChildren().size()); }
From source file:org.cleverbus.core.common.asynch.repair.RepairMessageServiceDbImpl.java
private List<Message> findProcessingMessages() { return transactionTemplate.execute(new TransactionCallback<List<Message>>() { @Override/*from w w w .ja v a2s . c o m*/ @SuppressWarnings("unchecked") public List<Message> doInTransaction(TransactionStatus status) { return messageDao.findProcessingMessages(repeatInterval); } }); }
From source file:se.inera.intyg.intygstjanst.web.integration.test.SjukfallCertResource.java
@DELETE @Path("/") @Produces(MediaType.APPLICATION_JSON)/*from ww w . ja v a 2s . c om*/ public Response deleteAllSjukfallCertificates() { return transactionTemplate.execute(new TransactionCallback<Response>() { public Response doInTransaction(TransactionStatus status) { try { @SuppressWarnings("unchecked") List<SjukfallCertificate> certificates = entityManager .createQuery("SELECT sc FROM SjukfallCertificate sc").getResultList(); for (SjukfallCertificate sjukfallCert : certificates) { entityManager.remove(sjukfallCert); } return Response.ok().build(); } catch (Throwable t) { status.setRollbackOnly(); LOGGER.warn("delete all sjukfall certificates failed: " + t.getMessage()); return Response.serverError().build(); } } }); }
From source file:com.activiti.conf.custom.CustomBootstrap.java
public void applicationContextInitialized(ApplicationContext applicationContext) { // Need to be done in a separate TX, otherwise the LDAP sync won't see the created app // Can't use @Transactional here, cause it seems not to be applied as wanted transactionTemplate.execute(new TransactionCallback<Void>() { public Void doInTransaction(TransactionStatus status) { if (findAppWithName(APP_NAME) != null) { log.info(//w w w .ja va 2 s .c om "The database already contains an app of the same name so skipping Custom App initialization"); return null; } User adminUser = findAdminUser(); if (adminUser == null) { log.error("Could not find admin user so skipping Custom App initialization"); return null; } AppDefinition appDefinition = new AppDefinition(); appDefinition.setIcon(APP_ICON); appDefinition.setTheme(APP_THEME); List<AppModelDefinition> appModels = new ArrayList<AppModelDefinition>(); List<ModelJsonAndStepIdRelation> modelRelationList = new ArrayList<ModelJsonAndStepIdRelation>(); modelRelationList .add(new ModelJsonAndStepIdRelation(FORM_NAME, "form-models/begin-order-5001.json")); Model adhocModel = createProcessModelAndUpdateIds(modelRelationList, PROCESS_NAME, "process-models/order-process-5000.json", adminUser); appModels.add(createAppModelDefinition(adhocModel)); appDefinition.setModels(appModels); try { Model appModel = createAndSaveModelArtifactWithJson(APP_NAME, APP_DESCRIPTION, appDefinition, null, Model.MODEL_TYPE_APP, adminUser); modelService.createNewModelVersion(appModel, "Initial setup", adminUser); deploymentService.deployAppDefinitions(Collections.singletonList(appModel.getId()), adminUser); } catch (JsonProcessingException e) { log.error("Error creating app definition", e); } return null; } }); }
From source file:org.zlogic.vogon.web.security.UserService.java
/** * Returns true if the username is already in use * * @param username the username to check * @return true if the username is already in use *//*from ww w . ja v a2s .c om*/ private boolean isUsernameExists(final String username) { TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setReadOnly(true); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); return transactionTemplate.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus ts) { return userRepository.findByUsernameIgnoreCase(username) != null; } }); }
From source file:com.github.rholder.spring.transaction.TransactionBindingSupportTest.java
@Test public void testTransactionId() throws Exception { // turn on nested transactions for this one transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW); Assert.assertNull("Thread shouldn't have a txn ID", TransactionBindingSupport.getTransactionId()); Assert.assertEquals("No transaction start time expected", -1, TransactionBindingSupport.getTransactionStartTime()); transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { // begin the txn txnId = TransactionBindingSupport.getTransactionId(); Assert.assertNotNull("Expected thread to have a txn id", txnId); final long txnStartTime = TransactionBindingSupport.getTransactionStartTime(); Assert.assertTrue("Expected a transaction start time", txnStartTime > 0); // check that the txn id and time doesn't change txnIdCheck = TransactionBindingSupport.getTransactionId(); Assert.assertEquals("Transaction ID changed on same thread", txnId, txnIdCheck); long txnStartTimeCheck = TransactionBindingSupport.getTransactionStartTime(); Assert.assertEquals("Transaction start time changed on same thread", txnStartTime, txnStartTimeCheck);//from w ww .j a v a 2 s.c om // begin a new, inner transaction { transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { // check the ID for the outer transaction String txnIdInner = TransactionBindingSupport.getTransactionId(); Assert.assertNotSame("Inner txn ID must be different from outer txn ID", txnIdInner, txnId); // Check the time against the outer transaction long txnStartTimeInner = TransactionBindingSupport.getTransactionStartTime(); Assert.assertTrue( "Inner transaction start time should be greater or equal (accuracy) to the outer's", txnStartTime <= txnStartTimeInner); // rollback the nested txn status.setRollbackOnly(); return null; } }); txnIdCheck = TransactionBindingSupport.getTransactionId(); Assert.assertEquals("Txn ID not popped inner txn completion", txnId, txnIdCheck); } // rollback the outer transaction status.setRollbackOnly(); return null; } }); Assert.assertNull("Thread shouldn't have a txn ID after rollback", TransactionBindingSupport.getTransactionId()); // start a new transaction transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { txnIdCheck = TransactionBindingSupport.getTransactionId(); Assert.assertNotSame("New transaction has same ID", txnId, txnIdCheck); // rollback status.setRollbackOnly(); return null; } }); Assert.assertNull("Thread shouldn't have a txn ID after rollback", TransactionBindingSupport.getTransactionId()); }
From source file:org.nebula.service.processor.RegisterProcessor.java
private PersistenceResult persistInTransaction(final RegisterRequest request, final Registration registration) { TransactionTemplate template = new TransactionTemplate(transactionManager); Object o = template.execute(new TransactionCallback() { @Override//from ww w . j a va 2 s.c o m public Object doInTransaction(TransactionStatus status) { PersistenceResult result = null; try { boolean inserted = false; try { registrationMapper.insertRegistration(registration); getLogger().info("inserted Registration id:" + registration.getId()); inserted = true; result = new PersistenceResult(true, registration); } catch (DuplicateKeyException e) { getLogger().info("Duplicated registration: " + toJson(registration)); Registration old = registrationMapper.find(registration); registration.setId(old.getId()); registrationMapper.update(registration); result = new PersistenceResult(false, registration); } // workflow registration?timer if (request.getNodeType() == RegisterRequest.NodeType.WORKFLOW) { persistTimer(request, registration); } } catch (Exception e) { status.setRollbackOnly(); throw new RuntimeException("Persisted registration failure." + toJson(registration), e); } return result; } }); return (PersistenceResult) o; }
From source file:org.motechproject.server.omod.sdsched.TxSyncManWrapperImplTest.java
public void testGetResource() { final String resourceName = "A Resource"; final String resourceValue = "A Resource value"; Object retVal = txTempl.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { TransactionSynchronizationManager.bindResource(resourceName, resourceValue); return txSyncManWrapper.getResource(resourceName); } finally { TransactionSynchronizationManager.unbindResourceIfPossible(resourceName); }//from w w w .j av a2 s . c o m } }); assertEquals(resourceValue, retVal); }
From source file:org.opennms.sample.provisioning.SampleProvisioningAdapter.java
private InetAddress getIpAddress(final int nodeId) { return m_template.execute(new TransactionCallback<InetAddress>() { public InetAddress doInTransaction(TransactionStatus arg0) { // Load thenode from the database final OnmsNode node = m_nodeDao.get(nodeId); Assert.notNull(node, "failed to return node for given nodeId:" + nodeId); info("getIpAddress: node: {} Foreign Source: {}", node.getNodeId(), node.getForeignSource()); // find the primary interface for the node final OnmsIpInterface primaryInterface = node.getPrimaryInterface(); if (primaryInterface != null && primaryInterface.getIpAddress() != null) { return primaryInterface.getIpAddress(); }//from ww w. ja v a2 s . com // unable to find the primary interface look thru the interfaces on the node for an ip info("getIpAddress: found null SNMP Primary Interface, getting interfaces"); final Set<OnmsIpInterface> ipInterfaces = node.getIpInterfaces(); for (final OnmsIpInterface onmsIpInterface : ipInterfaces) { info("getIpAddress: trying Interface with id: {}", onmsIpInterface.getId()); if (onmsIpInterface.getIpAddress() != null) { return onmsIpInterface.getIpAddress(); } } // No interface with valid ip found info("getIpAddress: Unable to find interface with ipaddress for node: {}", node.getNodeId()); return null; } }); }
From source file:org.activiti.engine.impl.cfg.spring.ProcessEngineFactoryBean.java
public ProcessEngine getObject() throws Exception { processEngineConfiguration.setLocalTransactions(transactionManager == null); if (transactionManager != null) { DefaultCommandExecutor commandExecutor = (DefaultCommandExecutor) processEngineConfiguration .getCommandExecutor();/* w w w . ja v a2 s . c o m*/ commandExecutor.addCommandInterceptor(new CommandInterceptor() { public <T> T invoke(final CommandExecutor next, final Command<T> command) { // TODO: Add transaction attributes @SuppressWarnings("unchecked") T result = (T) new TransactionTemplate(transactionManager).execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { return next.execute(command); } }); return result; } }); processEngineConfiguration.setCommandExecutor(commandExecutor); } processEngine = (ProcessEngineImpl) processEngineConfiguration.buildProcessEngine(); refreshProcessResources(processEngine.getRepositoryService(), processResources); return processEngine; }