Java Code Examples for org.springframework.transaction.support.TransactionCallbackWithoutResult

The following are top voted examples for showing how to use org.springframework.transaction.support.TransactionCallbackWithoutResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: otter-G   File: ChannelServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除Channel
 */
public void remove(final Long channelId) {
    Assert.assertNotNull(channelId);

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                arbitrateManageService.channelEvent().destory(channelId);
                channelDao.delete(channelId);
            } catch (Exception e) {
                logger.error("ERROR ## remove channel has an exception ", e);
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 2
Project: otter-G   File: PipelineServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除
 */
public void remove(final Long pipelineId) {
    Assert.assertNotNull(pipelineId);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                PipelineDO pipelineDO = pipelineDao.findById(pipelineId);
                if (pipelineDO != null) {
                    pipelineDao.delete(pipelineId);
                    pipelineNodeRelationDao.deleteByPipelineId(pipelineId);
                    // 删除历史cursor
                    String destination = pipelineDO.getParameters().getDestinationName();
                    short clientId = pipelineDO.getId().shortValue();
                    arbitrateViewService.removeCanal(destination, clientId);
                    arbitrateManageService.pipelineEvent().destory(pipelineDO.getChannelId(), pipelineId);
                }
            } catch (Exception e) {
                logger.error("ERROR ## remove the pipeline(" + pipelineId + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });
}
 
Example 3
Project: otter-G   File: DataMatrixServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 添加
 */
public void create(final DataMatrix matrix) {
    Assert.assertNotNull(matrix);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                DataMatrixDO matrixlDO = modelToDo(matrix);
                matrixlDO.setId(0L);
                matrixlDO.setGroupKey(matrixlDO.getGroupKey()+TimeUtil.getTime0());
                if (!dataMatrixDao.checkUnique(matrixlDO)) {
                    String exceptionCause = "exist the same repeat canal in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
                dataMatrixDao.insert(matrixlDO);
            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## create canal has an exception!");
                throw new ManagerException(e);
            }
        }
    });
}
 
Example 4
Project: otter-G   File: DataMatrixServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除
 */
public void remove(final Long matrixId) {
    Assert.assertNotNull(matrixId);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                dataMatrixDao.delete(matrixId);
            } catch (Exception e) {
                logger.error("ERROR ## remove canal(" + matrixId + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 5
Project: otter-G   File: DataMatrixServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 修改
 */
public void modify(final DataMatrix matrix) {
    Assert.assertNotNull(matrix);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                DataMatrixDO matrixDo = modelToDo(matrix);
                if (dataMatrixDao.checkUnique(matrixDo)) {
                    dataMatrixDao.update(matrixDo);
                } else {
                    String exceptionCause = "exist the same repeat matrix in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## modify canal(" + matrix.getId() + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 6
Project: otter-G   File: CanalServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除
 */
public void remove(final Long canalId) {
    Assert.assertNotNull(canalId);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                Canal canal = findById(canalId);
                canalDao.delete(canalId);
                arbitrateViewService.removeCanal(canal.getName()); // 删除canal节点信息
            } catch (Exception e) {
                logger.error("ERROR ## remove canal(" + canalId + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 7
Project: otter-G   File: CanalServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 修改
 */
public void modify(final Canal canal) {
    Assert.assertNotNull(canal);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                CanalDO canalDo = modelToDo(canal);
                if (canalDao.checkUnique(canalDo)) {
                    canalDao.update(canalDo);
                } else {
                    String exceptionCause = "exist the same repeat canal in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## modify canal(" + canal.getId() + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 8
Project: otter-G   File: NodeServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 添加
 */
public void create(final Node node) {
    Assert.assertNotNull(node);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                NodeDO nodeDo = modelToDo(node);
                nodeDo.setId(0L);
                if (!nodeDao.checkUnique(nodeDo)) {
                    String exceptionCause = "exist the same repeat node in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
                nodeDao.insert(nodeDo);

            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## create node has an exception!");
                throw new ManagerException(e);
            }
        }
    });
}
 
Example 9
Project: otter-G   File: NodeServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除
 */
public void remove(final Long nodeId) {
    Assert.assertNotNull(nodeId);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                nodeDao.delete(nodeId);
            } catch (Exception e) {
                logger.error("ERROR ## remove node(" + nodeId + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 10
Project: otter-G   File: NodeServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 修改
 */
public void modify(final Node node) {
    Assert.assertNotNull(node);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                NodeDO nodeDo = modelToDo(node);
                if (nodeDao.checkUnique(nodeDo)) {
                    nodeDao.update(nodeDo);
                } else {
                    String exceptionCause = "exist the same repeat node in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## modify node(" + node.getId() + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 11
Project: spring4-understanding   File: JpaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testInvalidIsolation() {
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);

	given(manager.isOpen()).willReturn(true);

	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
			}
		});
		fail("Should have thrown InvalidIsolationLevelException");
	}
	catch (InvalidIsolationLevelException ex) {
		// expected
	}

	verify(manager).close();
}
 
Example 12
Project: spring4-understanding   File: JpaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionFlush() {
	given(manager.getTransaction()).willReturn(tx);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		public void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.hasResource(factory));
			status.flush();
		}
	});

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	verify(tx).commit();
	verify(manager).flush();
	verify(manager).close();
}
 
Example 13
Project: spring4-understanding   File: JdoTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testIsolationLevel() {
	given(pmf.getPersistenceManager()).willReturn(pm);
	given(pm.currentTransaction()).willReturn(tx);

	PlatformTransactionManager tm = new JdoTransactionManager(pmf);
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
		}
	});
	verify(tx).setIsolationLevel(Constants.TX_SERIALIZABLE);
	verify(pm).close();
}
 
Example 14
Project: spring4-understanding   File: JdoTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionFlush() {
	given(pmf.getPersistenceManager()).willReturn(pm);
	given(pm.currentTransaction()).willReturn(tx);

	PlatformTransactionManager tm = new JdoTransactionManager(pmf);
	TransactionTemplate tt = new TransactionTemplate(tm);
	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		public void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf));
			status.flush();
		}
	});

	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
	verify(pm).flush();
	verify(pm).close();
	verify(tx).begin();
	verify(tx).commit();
}
 
Example 15
Project: spring4-understanding   File: TransactionSupportTests.java   Source Code and License 6 votes vote down vote up
@Test
public void transactionTemplateWithException() {
	TestTransactionManager tm = new TestTransactionManager(false, true);
	TransactionTemplate template = new TransactionTemplate(tm);
	final RuntimeException ex = new RuntimeException("Some application exception");
	try {
		template.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				throw ex;
			}
		});
		fail("Should have propagated RuntimeException");
	}
	catch (RuntimeException caught) {
		// expected
		assertTrue("Correct exception", caught == ex);
		assertTrue("triggered begin", tm.begin);
		assertTrue("no commit", !tm.commit);
		assertTrue("triggered rollback", tm.rollback);
		assertTrue("no rollbackOnly", !tm.rollbackOnly);
	}
}
 
Example 16
Project: spring4-understanding   File: TransactionSupportTests.java   Source Code and License 6 votes vote down vote up
@Test
public void transactionTemplateWithError() {
	TestTransactionManager tm = new TestTransactionManager(false, true);
	TransactionTemplate template = new TransactionTemplate(tm);
	try {
		template.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				throw new Error("Some application error");
			}
		});
		fail("Should have propagated Error");
	}
	catch (Error err) {
		// expected
		assertTrue("triggered begin", tm.begin);
		assertTrue("no commit", !tm.commit);
		assertTrue("triggered rollback", tm.rollback);
		assertTrue("no rollbackOnly", !tm.rollbackOnly);
	}
}
 
Example 17
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithCommitAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(
	Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).begin();
	verify(ut).commit();
}
 
Example 18
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithRollbackAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronizationName("SYNCHRONIZATION_NEVER");
	tt.setTimeout(10);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setTransactionTimeout(10);
	verify(ut).begin();
	verify(ut, atLeastOnce()).getStatus();
	verify(ut).rollback();
}
 
Example 19
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndRollbackOnly() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example 20
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndCommitException() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);
	willThrow(new OptimisticLockingFailureException("")).given(synch).beforeCommit(false);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
				TransactionSynchronizationManager.registerSynchronization(synch);
			}
		});
		fail("Should have thrown OptimisticLockingFailureException");
	}
	catch (OptimisticLockingFailureException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example 21
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndRollbackOnlyAndNoGlobalRollback() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	ptm.setGlobalRollbackOnParticipationFailure(false);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example 22
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example 23
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
}
 
Example 24
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingAndPropagationSupports() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example 25
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupports() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
}
 
Example 26
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example 27
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example 28
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationNotSupported() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);

	JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(tm).resume(tx);
}
 
Example 29
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndExisting() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);

	JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).begin();
	verify(ut).commit();
	verify(tm).resume(tx);
}
 
Example 30
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndExistingWithSuspendException() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new SystemException()).given(tm).suspend();

	JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example 31
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndAdapter() throws Exception {
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);

	JtaTransactionManager ptm = newJtaTransactionManager(tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(tm).begin();
	verify(tm).commit();
	verify(tm).resume(tx);
}
 
Example 32
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndSuspensionNotSupported() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
			}
		});
		fail("Should have thrown TransactionSuspensionNotSupportedException");
	}
	catch (TransactionSuspensionNotSupportedException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example 33
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithIsolationLevel() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown InvalidIsolationLevelException");
	}
	catch (InvalidIsolationLevelException ex) {
		// expected
	}
}
 
Example 34
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithSystemExceptionOnIsExisting() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willThrow(new SystemException("system exception"));

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
}
 
Example 35
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithNestedBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			// something transactional
		}
	});

	verify(ut).begin();
	verify(ut).commit();
}
 
Example 36
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithNotSupportedExceptionOnNestedBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new NotSupportedException("not supported")).given(ut).begin();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown NestedTransactionNotSupportedException");
	}
	catch (NestedTransactionNotSupportedException ex) {
		// expected
	}
}
 
Example 37
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithUnsupportedOperationExceptionOnNestedBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new UnsupportedOperationException("not supported")).given(ut).begin();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown NestedTransactionNotSupportedException");
	}
	catch (NestedTransactionNotSupportedException ex) {
		// expected
	}
}
 
Example 38
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithSystemExceptionOnBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);
	willThrow(new SystemException("system exception")).given(ut).begin();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}
}
 
Example 39
Project: spring4-understanding   File: JtaTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new IllegalStateException("no existing transaction")).given(ut).setRollbackOnly();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				status.setRollbackOnly();
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
}
 
Example 40
Project: spring4-understanding   File: DataSourceTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
	willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
Example 41
Project: spring4-understanding   File: DataSourceTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionWithExceptionOnCommit() throws Exception {
	willThrow(new SQLException("Cannot commit")).given(con).commit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
Example 42
Project: spring4-understanding   File: DataSourceTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionWithExceptionOnCommitAndRollbackOnCommitFailure() throws Exception {
	willThrow(new SQLException("Cannot commit")).given(con).commit();

	tm.setRollbackOnCommitFailure(true);
	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).rollback();
	verify(con).close();
}
 
Example 43
Project: spring4-understanding   File: DataSourceTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionWithExceptionOnRollback() throws Exception {
	given(con.getAutoCommit()).willReturn(true);
	willThrow(new SQLException("Cannot rollback")).given(con).rollback();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
				status.setRollbackOnly();
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).rollback();
	ordered.verify(con).setAutoCommit(true);
	verify(con).close();
}
 
Example 44
Project: spring4-understanding   File: DataSourceTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationSupports() throws Exception {
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
			assertTrue("Is not new transaction", !status.isNewTransaction());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example 45
Project: spring4-understanding   File: DataSourceTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNever() throws Exception {
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
			assertTrue("Is not new transaction", !status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example 46
Project: spring4-understanding   File: DataSourceTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNested() throws Exception {
	final TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Is new transaction", status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).commit();
	verify(con).close();
}
 
Example 47
Project: spring4-understanding   File: DataSourceTransactionManagerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNestedAndRollback() throws Exception {
	final TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Is new transaction", status.isNewTransaction());
			status.setRollbackOnly();
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).rollback();
	verify(con).close();
}
 
Example 48
Project: JavaWeb20160124-Team1   File: DeleteDataTable.java   Source Code and License 6 votes vote down vote up
public int deleteAllExceptLastNRecords(final int recordsAmountToKeepAlive) throws DataAccessException {
    Integer logRecordsCountTotal = logRepository.countAll();
    if (recordsAmountToKeepAlive >= logRecordsCountTotal) {
        return 0;
    }
    final String temporaryTableNameNew = tableName + "_" + UUID.randomUUID().toString().replace("-", "");
    final String temporaryTableNameOld = tableName + "_" + UUID.randomUUID().toString().replace("-", "");
    sharedTransactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            Integer limit = recordsAmountToKeepAlive;
            String[] sql = {
                    "CREATE TABLE IF NOT EXISTS " + temporaryTableNameNew + " LIKE " + tableName,
                    "INSERT INTO " + temporaryTableNameNew + " SELECT * FROM " + tableName + " ORDER BY occurred_at DESC LIMIT " + limit,
                    "RENAME TABLE " + tableName + " TO " + temporaryTableNameOld + ", " + temporaryTableNameNew + " TO " + tableName,
                    "DROP TABLE " + temporaryTableNameOld
            };
            jdbcTemplate.batchUpdate(sql);
        }
    });
    return logRecordsCountTotal - recordsAmountToKeepAlive;
}
 
Example 49
Project: dtsopensource   File: LocalDTSSchedule.java   Source Code and License 6 votes vote down vote up
@Override
public void closeActivity(final String activityId, final Status orignStatus, final Status targetStatus) {
    log.info("--->start to closeActivity:{},turn status from:{} to:{}", activityId, orignStatus, targetStatus);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            jdbcTemplate.update(ActivitySqlConstance.commit_rollback_activity_by_activity_id,
                    new PreparedStatementSetter() {

                        @Override
                        public void setValues(PreparedStatement ps) throws SQLException {
                            ps.setString(1, targetStatus.name());
                            ps.setTimestamp(2, new Timestamp(new Date().getTime()));
                            ps.setString(3, activityId);
                            ps.setString(4, orignStatus.name());
                        }
                    });
        }
    });
}
 
Example 50
Project: Camel   File: JdbcAggregationRepository.java   Source Code and License 6 votes vote down vote up
@Override
public void remove(final CamelContext camelContext, final String correlationId, final Exchange exchange) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            final String key = correlationId;
            final String confirmKey = exchange.getExchangeId();
            try {
                LOG.debug("Removing key [{}]", key);

                jdbcTemplate.update("DELETE FROM " + getRepositoryName() + " WHERE " + ID + " = ?", key);

                insert(camelContext, confirmKey, exchange, getRepositoryNameCompleted());

            } catch (Exception e) {
                throw new RuntimeException("Error removing key " + key + " from repository " + repositoryName, e);
            }
        }
    });
}
 
Example 51
Project: OpenCyclos   File: AccountActivationPollingTask.java   Source Code and License 6 votes vote down vote up
/**
 * Handles a failure in initial credit processing, by generating a member alert and deleting the {@link PendingInitialCredit} instance.
 */
private void handleFailure(final MemberAccount account) {
    // Create the alert in a new transaction, and remove the marker for activation, otherwise cyclos will be trying and retrying infinitely
    transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            // Create the alert
            MemberAccount fetchedAccount = fetchService.fetch(account, MemberAccount.Relationships.MEMBER, Account.Relationships.TYPE);
            Member member = fetchedAccount.getMember();
            alertService.create(member, MemberAlert.Alerts.ACCOUNT_ACTIVATION_FAILED, fetchedAccount.getType().getName());

            // Remove the activation marker
            fetchedAccount.setAction(null);
            accountDao.update(fetchedAccount);
        }
    });
}
 
Example 52
Project: OpenCyclos   File: TaskRunnerImpl.java   Source Code and License 6 votes vote down vote up
protected void doRunInitialization(final String beanName) {
    final InitializingService service = applicationContext.getBean(beanName, InitializingService.class);
    getTransactionHelper().runInCurrentThread(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Running initialization for bean " + beanName);
                }
                LoggedUser.runAsSystem(Executors.callable(new Runnable() {
                    @Override
                    public void run() {
                        service.initializeService();
                    }
                }));
            } catch (RuntimeException e) {
                LOG.error("Error running initialization for bean " + beanName, e);
                throw e;
            }
        }
    });
}
 
Example 53
Project: OpenCyclos   File: TaskRunnerImpl.java   Source Code and License 6 votes vote down vote up
protected void doRunScheduledTask(final String taskName, final Calendar time) {
    final ScheduledTask task = getSchedulingHandler().getTask(taskName);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Running scheduled task " + taskName + " with base time " + FormatObject.formatObject(time));
    }
    if (task.shouldRunInTransaction()) {
        getTransactionHelper().runInCurrentThread(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(final TransactionStatus status) {
                if (!doRunScheduledTask(task, time)) {
                    status.setRollbackOnly();
                }
            }
        });
    } else {
        doRunScheduledTask(task, time);
    }
}
 
Example 54
Project: OpenCyclos   File: PaymentRequestHandlerImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected void process(final PaymentRequestTicket t) {
    transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            final PaymentRequestTicket ticket = ticketService.load(t.getTicket(), Ticket.Relationships.FROM, Ticket.Relationships.TO);
            final LocalSettings localSettings = settingsService.getLocalSettings();
            final Channel channel = channelService.load(ticket.getToChannel().getId());

            try {
                final PaymentRequestWebService ws = proxyFor(channel);
                final boolean result = ws.requestPayment(localSettings.getCyclosId(), ticketHelper.toVO(ticket, channel.getPrincipalCustomFields()));
                if (!result) {
                    throw new Exception("The PaymentRequestWebService returned an error status");
                }
            } catch (final Exception e) {
                ticketService.markAsFailedtoSend(ticket);
                final Map<String, String> params = new HashMap<String, String>();
                params.put("ticket", ticket.getTicket());
                params.put("payer username", ticket.getFrom().getUsername());
                params.put("receiver username", ticket.getTo().getUsername());
                errorLogService.insert(e, channel.getPaymentRequestWebServiceUrl(), params);
            }
        }
    });
}
 
Example 55
Project: OpenCyclos   File: AlertServiceImpl.java   Source Code and License 6 votes vote down vote up
private void save(final Alert alert, final AlertType type) {
    if (alert.getDate() == null) {
        alert.setDate(Calendar.getInstance());
    }

    // Only the application shutdown should be saved right away, as the database connection might be disposed right away
    if (SystemAlert.Alerts.APPLICATION_SHUTDOWN.equals(type)) {
        doSave(alert);
    } else {
        // The others are safe to run in the background
        CurrentTransactionData.addTransactionCommitListener(new TransactionEndListener() {
            @Override
            protected void onTransactionEnd(final boolean commit) {
                transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(final TransactionStatus status) {
                        doSave(alert);
                    }
                });
            }
        });
    }
}
 
Example 56
Project: xap-openspaces   File: AbstractTwoSpaceJtaTransactionTests.java   Source Code and License 6 votes vote down vote up
@Test public void testSimpleCommitTwoSpaces() {
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
    assertNull(gigaSpace1.read(new EmptySpaceDataObject()));
    assertNull(gigaSpace2.read(new EmptySpaceDataObject()));
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
            assertNull(gigaSpace1.read(new EmptySpaceDataObject()));
            assertNull(gigaSpace2.read(new EmptySpaceDataObject()));
            gigaSpace1.write(new EmptySpaceDataObject());
            gigaSpace2.write(new EmptySpaceDataObject());
            assertNotNull(gigaSpace1.read(new EmptySpaceDataObject()));
            assertNotNull(gigaSpace2.read(new EmptySpaceDataObject()));
        }
    });
    assertNotNull(gigaSpace1.read(new EmptySpaceDataObject()));
    assertNotNull(gigaSpace2.read(new EmptySpaceDataObject()));
}
 
Example 57
Project: xap-openspaces   File: AbstractTwoSpaceJtaTransactionTests.java   Source Code and License 6 votes vote down vote up
@Test public void testTakeRollbackTwoSpaces() {
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
    assertNull(gigaSpace1.read(new EmptySpaceDataObject()));
    assertNull(gigaSpace2.read(new EmptySpaceDataObject()));
    gigaSpace1.write(new EmptySpaceDataObject());
    gigaSpace2.write(new EmptySpaceDataObject());
    assertNotNull(gigaSpace1.read(new EmptySpaceDataObject()));
    assertNotNull(gigaSpace2.read(new EmptySpaceDataObject()));
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
            assertNotNull(gigaSpace1.take(new EmptySpaceDataObject()));
            assertNotNull(gigaSpace2.take(new EmptySpaceDataObject()));
            transactionStatus.setRollbackOnly();
        }
    });
    assertNotNull(gigaSpace1.take(new EmptySpaceDataObject()));
    assertNotNull(gigaSpace2.take(new EmptySpaceDataObject()));
}
 
Example 58
Project: xap-openspaces   File: TransactionalExecutorTests.java   Source Code and License 6 votes vote down vote up
@Test public void testSimpleTransactionRollback1() {
    TransactionTemplate txTemplate = new TransactionTemplate(localTxManager1);
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            AsyncFuture<Integer> value = localGigaSpace1.execute(new SimpleTask1(), 0);
            try {
                assertEquals(1, (int) value.get(1000, TimeUnit.MILLISECONDS));
            } catch (Exception e) {
                e.printStackTrace();
                fail();
            }
            status.setRollbackOnly();
        }
    });
    assertEquals(0, localGigaSpace1.count(null));
}
 
Example 59
Project: xap-openspaces   File: TransactionalExecutorTests.java   Source Code and License 6 votes vote down vote up
@Test public void testSimpleTransactionRollback2() {
    TransactionTemplate txTemplate = new TransactionTemplate(localTxManager1);
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            AsyncFuture<Integer> value = localGigaSpace1.execute(new SimpleTask2(), 0);
            try {
                assertEquals(1, (int) value.get(1000, TimeUnit.MILLISECONDS));
            } catch (Exception e) {
                e.printStackTrace();
                fail();
            }
            status.setRollbackOnly();
        }
    });
    assertEquals(0, localGigaSpace1.count(null));
}
 
Example 60
Project: xap-openspaces   File: TransactionalExecutorTests.java   Source Code and License 6 votes vote down vote up
@Test public void testListenerTransactionCommit() throws Exception {
    TransactionTemplate txTemplate = new TransactionTemplate(localTxManager1);
    final Listener listener = new Listener();
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            AsyncFuture<Integer> value = localGigaSpace1.execute(new DelayedSimpleTask1(), 0);
            value.setListener(listener);
        }
    });
    assertEquals(0, localGigaSpace1.count(null));
    while (listener.getResult() == null) {
        Thread.sleep(100);
    }
    // let it commit
    Thread.sleep(100);
    assertEquals(1, localGigaSpace1.count(null));
}