org.springframework.transaction.support.TransactionSynchronization Java Examples

The following examples show how to use org.springframework.transaction.support.TransactionSynchronization. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PipelineTimelineTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRemove_NewlyAddedTimelineEntries_fromAllCollections_UponRollback() throws Exception {
    Collection<PipelineTimelineEntry> allEntries;

    stubTransactionSynchronization();
    setupTransactionTemplateStub(TransactionSynchronization.STATUS_COMMITTED, true);
    final PipelineTimeline timeline = new PipelineTimeline(pipelineRepository, transactionTemplate, transactionSynchronizationManager);

    stubPipelineRepository(timeline, true, first, second);
    timeline.update();
    allEntries = timeline.getEntriesFor("pipeline");

    setupTransactionTemplateStub(TransactionSynchronization.STATUS_ROLLED_BACK, false);

    stubPipelineRepository(timeline, false, third, fourth);
    timeline.update();
    allEntries = timeline.getEntriesFor("pipeline");

    assertThat(timeline.maximumId(), is(2L));
    assertThat(timeline.getEntriesFor("pipeline").size(), is(2));
    assertThat(allEntries, hasItems(first, second));
    assertThat(timeline.instanceCount(new CaseInsensitiveString("pipeline")), is(2));
    assertThat(timeline.instanceFor(new CaseInsensitiveString("pipeline"), 0), is(first));
    assertThat(timeline.instanceFor(new CaseInsensitiveString("pipeline"), 1), is(second));
}
 
Example #2
Source File: ApplicationListenerMethodTransactionalAdapter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
		TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
	}
	else if (this.annotation.fallbackExecution()) {
		if (this.annotation.phase() == TransactionPhase.AFTER_ROLLBACK && logger.isWarnEnabled()) {
			logger.warn("Processing " + event + " as a fallback execution on AFTER_ROLLBACK phase");
		}
		processEvent(event);
	}
	else {
		// No transactional event execution at all
		if (logger.isDebugEnabled()) {
			logger.debug("No transaction is active - skipping " + event);
		}
	}
}
 
Example #3
Source File: PipelineLockServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotifyListenersAfterPipelineIsUnlockedUponConfigChange() throws Exception {
    PipelineLockStatusChangeListener lockStatusChangeListener = mock(PipelineLockStatusChangeListener.class);
    CruiseConfig cruiseConfig = mock(BasicCruiseConfig.class);

    when(pipelineStateDao.lockedPipelines()).thenReturn(asList("pipeline1"));
    when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipeline1"))).thenReturn(false);
    when(cruiseConfig.isPipelineLockable("pipeline1")).thenThrow(new RecordNotFoundException(EntityType.Pipeline, "pipeline1"));
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            AfterCompletionCallback callback = (AfterCompletionCallback) invocation.getArguments()[1];
            callback.execute(TransactionSynchronization.STATUS_COMMITTED);
            return null;
        }
    }).when(pipelineStateDao).unlockPipeline(eq("pipeline1"), any(AfterCompletionCallback.class));

    pipelineLockService.registerListener(lockStatusChangeListener);
    pipelineLockService.onConfigChange(cruiseConfig);

    verify(lockStatusChangeListener).lockStatusChanged(Event.unLock("pipeline1"));
}
 
Example #4
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testBlobSerializableTypeWithNull() throws Exception {
	given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(null);

	BlobSerializableType type = new BlobSerializableType(lobHandler, null);
	assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, null, 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setBlobAsBytes(ps, 1, null);
}
 
Example #5
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 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 #6
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT 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 #7
Source File: JtaAfterCompletionSynchronization.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void afterCompletion(int status) {
	switch (status) {
		case Status.STATUS_COMMITTED:
			try {
				TransactionSynchronizationUtils.invokeAfterCommit(this.synchronizations);
			}
			finally {
				TransactionSynchronizationUtils.invokeAfterCompletion(
						this.synchronizations, TransactionSynchronization.STATUS_COMMITTED);
			}
			break;
		case Status.STATUS_ROLLEDBACK:
			TransactionSynchronizationUtils.invokeAfterCompletion(
					this.synchronizations, TransactionSynchronization.STATUS_ROLLED_BACK);
			break;
		default:
			TransactionSynchronizationUtils.invokeAfterCompletion(
					this.synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example #8
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testClobStringTypeWithFlushOnCommit() throws Exception {
	given(lobHandler.getClobAsString(rs, "column")).willReturn("content");

	ClobStringType type = new ClobStringType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.CLOB, type.sqlTypes()[0]);
	assertEquals(String.class, type.returnedClass());
	assertTrue(type.equals("content", "content"));
	assertEquals("content", type.deepCopy("content"));
	assertFalse(type.isMutable());

	assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, "content", 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setClobAsString(ps, 1, "content");
}
 
Example #9
Source File: SpringJtaSynchronizationAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * JTA {@code afterCompletion} callback: invoked after commit/rollback.
 * <p>Needs to invoke the Spring synchronization's {@code beforeCompletion}
 * at this late stage in case of a rollback, since there is no corresponding
 * callback with JTA.
 * @see org.springframework.transaction.support.TransactionSynchronization#beforeCompletion
 * @see org.springframework.transaction.support.TransactionSynchronization#afterCompletion
 */
@Override
public void afterCompletion(int status) {
	if (!this.beforeCompletionCalled) {
		// beforeCompletion not called before (probably because of JTA rollback).
		// Perform the cleanup here.
		this.springSynchronization.beforeCompletion();
	}
	// Call afterCompletion with the appropriate status indication.
	switch (status) {
		case Status.STATUS_COMMITTED:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
			break;
		case Status.STATUS_ROLLEDBACK:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
			break;
		default:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example #10
Source File: JtaAfterCompletionSynchronization.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void afterCompletion(int status) {
	switch (status) {
		case Status.STATUS_COMMITTED:
			try {
				TransactionSynchronizationUtils.invokeAfterCommit(this.synchronizations);
			}
			finally {
				TransactionSynchronizationUtils.invokeAfterCompletion(
						this.synchronizations, TransactionSynchronization.STATUS_COMMITTED);
			}
			break;
		case Status.STATUS_ROLLEDBACK:
			TransactionSynchronizationUtils.invokeAfterCompletion(
					this.synchronizations, TransactionSynchronization.STATUS_ROLLED_BACK);
			break;
		default:
			TransactionSynchronizationUtils.invokeAfterCompletion(
					this.synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example #11
Source File: SpringJtaSynchronizationAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * JTA {@code afterCompletion} callback: invoked after commit/rollback.
 * <p>Needs to invoke the Spring synchronization's {@code beforeCompletion}
 * at this late stage in case of a rollback, since there is no corresponding
 * callback with JTA.
 * @see org.springframework.transaction.support.TransactionSynchronization#beforeCompletion
 * @see org.springframework.transaction.support.TransactionSynchronization#afterCompletion
 */
@Override
public void afterCompletion(int status) {
	if (!this.beforeCompletionCalled) {
		// beforeCompletion not called before (probably because of JTA rollback).
		// Perform the cleanup here.
		this.springSynchronization.beforeCompletion();
	}
	// Call afterCompletion with the appropriate status indication.
	switch (status) {
		case Status.STATUS_COMMITTED:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
			break;
		case Status.STATUS_ROLLEDBACK:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
			break;
		default:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example #12
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT 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 #13
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 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 #14
Source File: TransactionUtil.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T extends Runnable> T getOnCommit(Class<T> clazz,
		boolean before) {
	if (!TransactionSynchronizationManager.isSynchronizationActive()) {
		return null;
	}
	for (TransactionSynchronization synchronization : TransactionSynchronizationManager
			.getSynchronizations()) {
		if (synchronization instanceof OnCommitSynchronization) {
			OnCommitSynchronization onCommit = (OnCommitSynchronization) synchronization;
			if (before == onCommit.before
					&& onCommit.runner.getClass() == clazz) {
				return (T) onCommit.runner;
			}
		}
	}
	return null;
}
 
Example #15
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT 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 #16
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT 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 #17
Source File: TransactionSynchronizationManagerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterSynchronization_andNotCallItOnTransactionFailure() {
    final TransactionSynchronizationManager synchronizationManager = new TransactionSynchronizationManager();

    final TransactionSynchronization synchronization = mock(TransactionSynchronization.class);
    try {
        transactionTemplate.execute(new org.springframework.transaction.support.TransactionCallbackWithoutResult() {
            @Override protected void doInTransactionWithoutResult(TransactionStatus status) {
                synchronizationManager.registerSynchronization(synchronization);
                throw new RuntimeException();
            }
        });
    } catch (Exception e) {
        //ignore
    }
    verify(synchronization, never()).afterCommit();
}
 
Example #18
Source File: ApplicationListenerMethodTransactionalAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
		TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
	}
	else if (this.annotation.fallbackExecution()) {
		if (this.annotation.phase() == TransactionPhase.AFTER_ROLLBACK && logger.isWarnEnabled()) {
			logger.warn("Processing " + event + " as a fallback execution on AFTER_ROLLBACK phase");
		}
		processEvent(event);
	}
	else {
		// No transactional event execution at all
		if (logger.isDebugEnabled()) {
			logger.debug("No transaction is active - skipping " + event);
		}
	}
}
 
Example #19
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 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 #20
Source File: JtaAfterCompletionSynchronization.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterCompletion(int status) {
	switch (status) {
		case Status.STATUS_COMMITTED:
			try {
				TransactionSynchronizationUtils.invokeAfterCommit(this.synchronizations);
			}
			finally {
				TransactionSynchronizationUtils.invokeAfterCompletion(
						this.synchronizations, TransactionSynchronization.STATUS_COMMITTED);
			}
			break;
		case Status.STATUS_ROLLEDBACK:
			TransactionSynchronizationUtils.invokeAfterCompletion(
					this.synchronizations, TransactionSynchronization.STATUS_ROLLED_BACK);
			break;
		default:
			TransactionSynchronizationUtils.invokeAfterCompletion(
					this.synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example #21
Source File: PipelineTimelineTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void setupTransactionTemplateStub(final int status, final boolean restub) throws Exception {
    this.txnStatus = status;
    if (restub) {
        when(transactionTemplate.execute(Mockito.any(TransactionCallback.class))).thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                TransactionCallback callback = (TransactionCallback) invocationOnMock.getArguments()[0];
                callback.doInTransaction(null);
                if (txnStatus == TransactionSynchronization.STATUS_COMMITTED) {
                    transactionSynchronization.afterCommit();
                }
                transactionSynchronization.afterCompletion(txnStatus);
                return null;
            }
        });
    }
}
 
Example #22
Source File: SpringJtaSynchronizationAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * JTA {@code afterCompletion} callback: invoked after commit/rollback.
 * <p>Needs to invoke the Spring synchronization's {@code beforeCompletion}
 * at this late stage in case of a rollback, since there is no corresponding
 * callback with JTA.
 * @see org.springframework.transaction.support.TransactionSynchronization#beforeCompletion
 * @see org.springframework.transaction.support.TransactionSynchronization#afterCompletion
 */
@Override
public void afterCompletion(int status) {
	if (!this.beforeCompletionCalled) {
		// beforeCompletion not called before (probably because of JTA rollback).
		// Perform the cleanup here.
		this.springSynchronization.beforeCompletion();
	}
	// Call afterCompletion with the appropriate status indication.
	switch (status) {
		case Status.STATUS_COMMITTED:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
			break;
		case Status.STATUS_ROLLEDBACK:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
			break;
		default:
			this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example #23
Source File: PipelineLockServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotifyListenersAfterPipelineIsLocked() throws Exception {
    when(goConfigService.isLockable("pipeline1")).thenReturn(true);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            AfterCompletionCallback callback = (AfterCompletionCallback) invocation.getArguments()[1];
            callback.execute(TransactionSynchronization.STATUS_COMMITTED);
            return null;
        }
    }).when(pipelineStateDao).lockPipeline(any(Pipeline.class), any(AfterCompletionCallback.class));

    PipelineLockStatusChangeListener lockStatusChangeListener = mock(PipelineLockStatusChangeListener.class);

    Pipeline pipeline = PipelineMother.firstStageBuildingAndSecondStageScheduled("pipeline1", asList("stage1", "stage2"), asList("job1"));
    pipelineLockService.registerListener(lockStatusChangeListener);
    pipelineLockService.lockIfNeeded(pipeline);

    verify(lockStatusChangeListener).lockStatusChanged(Event.lock("pipeline1"));
}
 
Example #24
Source File: TransactionUtil.java    From mPass with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T extends Runnable> T getOnCommit(Class<T> clazz,
		boolean before) {
	if (!TransactionSynchronizationManager.isSynchronizationActive()) {
		return null;
	}
	for (TransactionSynchronization synchronization : TransactionSynchronizationManager
			.getSynchronizations()) {
		if (synchronization instanceof OnCommitSynchronization) {
			OnCommitSynchronization onCommit = (OnCommitSynchronization) synchronization;
			if (before == onCommit.before
					&& onCommit.runner.getClass() == clazz) {
				return (T) onCommit.runner;
			}
		}
	}
	return null;
}
 
Example #25
Source File: TransactionContext.java    From gocd with Apache License 2.0 6 votes vote down vote up
public void transactionPushed() {
    if (! isTransactionBodyExecuting()) {
        if (isInTransactionSurrounding() && txnFinished) {
            throw new RuntimeException(TOO_MANY_TXNS_IN_SURROUNDING);
        }
        txnFinished = false;
    }

    ensureCanPush(txnActive);
    txnActive--;

    if (! futureSynchronizations.isEmpty()) {
        for (TransactionSynchronization futureSynchronization : futureSynchronizations) {
            doRegisterSynchronization(futureSynchronization);
        }
        clearFutureSynchronizations();
    }
}
 
Example #26
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void beforeCommit(boolean readOnly) {
	if (this.status != TransactionSynchronization.STATUS_COMMITTED) {
		fail("Should never be called");
	}
	assertFalse(this.beforeCommitCalled);
	this.beforeCommitCalled = true;
}
 
Example #27
Source File: SolrTransactionSynchronizationAdapterBuilder.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link SolrTransactionSynchronizationAdapter} reacting on
 * {@link org.springframework.transaction.support.TransactionSynchronization#STATUS_COMMITTED}
 * and
 * {@link org.springframework.transaction.support.TransactionSynchronization#STATUS_ROLLED_BACK}
 * .
 * 
 * @return
 */
public SolrTransactionSynchronizationAdapter withDefaultBehaviour() {

	this.adapter.registerCompletionDelegate(TransactionSynchronization.STATUS_COMMITTED,
			new SolrTransactionSynchronizationAdapter.CommitTransaction());
	this.adapter.registerCompletionDelegate(TransactionSynchronization.STATUS_ROLLED_BACK,
			new SolrTransactionSynchronizationAdapter.RollbackTransaction());

	return this.adapter;
}
 
Example #28
Source File: PersistenceImplSupport.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void afterCompletion(int status) {
    try {
        Collection<Entity> instances = container.getAllInstances();
        if (log.isTraceEnabled())
            log.trace("ContainerResourceSynchronization.afterCompletion: instances = " + instances);
        for (Object instance : instances) {
            if (instance instanceof BaseGenericIdEntity) {
                if (status == TransactionSynchronization.STATUS_COMMITTED) {
                    if (BaseEntityInternalAccess.isNew((BaseGenericIdEntity) instance)) {
                        // new instances become not new and detached only if the transaction was committed
                        BaseEntityInternalAccess.setNew((BaseGenericIdEntity) instance, false);
                    }
                } else { // commit failed or the transaction was rolled back
                    makeDetached(instance);
                    for (Entity entity : container.getNewDetachedInstances()) {
                        BaseEntityInternalAccess.setNew((BaseGenericIdEntity) entity, true);
                        BaseEntityInternalAccess.setDetached((BaseGenericIdEntity) entity, false);
                    }
                }
            }
        }
        for (AfterCompleteTransactionListener listener : afterCompleteTxListeners) {
            listener.afterComplete(status == TransactionSynchronization.STATUS_COMMITTED, instances);
        }
    } finally {
        super.afterCompletion(status);
    }
}
 
Example #29
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 5 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 #30
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobStringType() throws Exception {
	String content = "content";
	byte[] contentBytes = content.getBytes();
	given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(contentBytes);

	BlobStringType type = new BlobStringType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.BLOB, type.sqlTypes()[0]);
	assertEquals(String.class, type.returnedClass());
	assertTrue(type.equals("content", "content"));
	assertEquals("content", type.deepCopy("content"));
	assertFalse(type.isMutable());

	assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, content, 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setBlobAsBytes(ps, 1, contentBytes);
}