Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationManager#getSynchronizations()

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager#getSynchronizations() . 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: 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 2
Source File: PersistenceImplSupport.java    From cuba with Apache License 2.0 6 votes vote down vote up
private void publishEntityChangedEvents(List<EntityChangedEvent> collectedEvents) {
    if (collectedEvents.isEmpty())
        return;

    List<TransactionSynchronization> synchronizationsBefore = new ArrayList<>(
            TransactionSynchronizationManager.getSynchronizations());

    entityChangedEventManager.publish(collectedEvents);

    List<TransactionSynchronization> synchronizations = new ArrayList<>(
            TransactionSynchronizationManager.getSynchronizations());

    if (synchronizations.size() > synchronizationsBefore.size()) {
        synchronizations.removeAll(synchronizationsBefore);
        for (TransactionSynchronization synchronization : synchronizations) {
            synchronization.beforeCommit(false);
        }
    }
}
 
Example 3
Source File: PersistenceImpl.java    From cuba with Apache License 2.0 6 votes vote down vote up
/**
 * INTERNAL.
 * Register synchronizations with a just started transaction.
 */
public void registerSynchronizationsIfAbsent(String store) {
    log.trace("registerSynchronizations for store '{}'", store);

    List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();

    boolean absent = synchronizations.stream()
            .noneMatch(s -> s instanceof EntityManagerContextSynchronization
                    && Objects.equals(store, ((EntityManagerContextSynchronization)s).getStore()));
    if (absent) {
        TransactionSynchronizationManager.registerSynchronization(createSynchronization(store));
        support.getInstanceContainerResourceHolder(store);

        statisticsAccumulator.incStartedTransactionsCount();
        TransactionSynchronizationManager.registerSynchronization(new StatisticsTransactionSynchronization());
    }
}
 
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: LobTypeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testBlobStringTypeWithNull() throws Exception {
	given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(null);

	BlobStringType type = new BlobStringType(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 6
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 7
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 8
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testClobStringTypeWithSynchronizedSession() throws Exception {
	SessionFactory sf = mock(SessionFactory.class);
	Session session = mock(Session.class);
	given(sf.openSession()).willReturn(session);
	given(session.getSessionFactory()).willReturn(sf);
	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 {
		SessionFactoryUtils.getSession(sf, true);
		type.nullSafeSet(ps, "content", 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(2, synchs.size());
		assertTrue(synchs.get(0).getClass().getName().endsWith("SpringLobCreatorSynchronization"));
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
		((TransactionSynchronization) synchs.get(1)).beforeCompletion();
		((TransactionSynchronization) synchs.get(1)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}

	verify(session).close();
	verify(lobCreator).setClobAsString(ps, 1, "content");
}
 
Example 9
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testClobStringType() 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());
		assertTrue(synchs.get(0).getClass().getName().endsWith("SpringLobCreatorSynchronization"));
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setClobAsString(ps, 1, "content");
}
 
Example 10
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);
}
 
Example 11
Source File: WebSphereUowTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
	DefaultTransactionStatus status = prepareTransactionStatus(
			this.definition, (this.actualTransaction ? this : null),
			this.newTransaction, this.newSynchronization, this.debug, null);
	try {
		this.result = this.callback.doInTransaction(status);
		triggerBeforeCommit(status);
	}
	catch (Throwable ex) {
		this.exception = ex;
		uowManager.setRollbackOnly();
	}
	finally {
		if (status.isLocalRollbackOnly()) {
			if (status.isDebug()) {
				logger.debug("Transactional code has requested rollback");
			}
			uowManager.setRollbackOnly();
		}
		triggerBeforeCompletion(status);
		if (status.isNewSynchronization()) {
			List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
			TransactionSynchronizationManager.clear();
			if (!synchronizations.isEmpty()) {
				uowManager.registerInterposedSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
			}
		}
	}
}
 
Example 12
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobByteArrayType() throws Exception {
	byte[] content = "content".getBytes();
	given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(content);

	BlobByteArrayType type = new BlobByteArrayType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.BLOB, type.sqlTypes()[0]);
	assertEquals(byte[].class, type.returnedClass());
	assertTrue(type.equals(new byte[] {(byte) 255}, new byte[] {(byte) 255}));
	assertTrue(Arrays.equals(new byte[] {(byte) 255}, (byte[]) type.deepCopy(new byte[] {(byte) 255})));
	assertTrue(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, content);
}
 
Example 13
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobSerializableType() throws Exception {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(baos);
	oos.writeObject("content");
	oos.close();

	given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(new ByteArrayInputStream(baos.toByteArray()));

	BlobSerializableType type = new BlobSerializableType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.BLOB, type.sqlTypes()[0]);
	assertEquals(Serializable.class, type.returnedClass());
	assertTrue(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, baos.toByteArray());
}
 
Example 14
Source File: WebSphereUowTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void run() {
	UOWManager uowManager = obtainUOWManager();
	DefaultTransactionStatus status = prepareTransactionStatus(
			this.definition, (this.actualTransaction ? this : null),
			this.newTransaction, this.newSynchronization, this.debug, null);
	try {
		this.result = this.callback.doInTransaction(status);
		triggerBeforeCommit(status);
	}
	catch (Throwable ex) {
		this.exception = ex;
		if (status.isDebug()) {
			logger.debug("Rolling back on application exception from transaction callback", ex);
		}
		uowManager.setRollbackOnly();
	}
	finally {
		if (status.isLocalRollbackOnly()) {
			if (status.isDebug()) {
				logger.debug("Transaction callback has explicitly requested rollback");
			}
			uowManager.setRollbackOnly();
		}
		triggerBeforeCompletion(status);
		if (status.isNewSynchronization()) {
			List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
			TransactionSynchronizationManager.clear();
			if (!synchronizations.isEmpty()) {
				uowManager.registerInterposedSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
			}
		}
	}
}
 
Example 15
Source File: WebSphereUowTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	DefaultTransactionStatus status = prepareTransactionStatus(
			this.definition, (this.actualTransaction ? this : null),
			this.newTransaction, this.newSynchronization, this.debug, null);
	try {
		this.result = this.callback.doInTransaction(status);
		triggerBeforeCommit(status);
	}
	catch (Throwable ex) {
		this.exception = ex;
		uowManager.setRollbackOnly();
	}
	finally {
		if (status.isLocalRollbackOnly()) {
			if (status.isDebug()) {
				logger.debug("Transactional code has requested rollback");
			}
			uowManager.setRollbackOnly();
		}
		triggerBeforeCompletion(status);
		if (status.isNewSynchronization()) {
			List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
			TransactionSynchronizationManager.clear();
			if (!synchronizations.isEmpty()) {
				uowManager.registerInterposedSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
			}
		}
	}
}
 
Example 16
Source File: WebSphereUowTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void run() {
	UOWManager uowManager = obtainUOWManager();
	DefaultTransactionStatus status = prepareTransactionStatus(
			this.definition, (this.actualTransaction ? this : null),
			this.newTransaction, this.newSynchronization, this.debug, null);
	try {
		this.result = this.callback.doInTransaction(status);
		triggerBeforeCommit(status);
	}
	catch (Throwable ex) {
		this.exception = ex;
		if (status.isDebug()) {
			logger.debug("Rolling back on application exception from transaction callback", ex);
		}
		uowManager.setRollbackOnly();
	}
	finally {
		if (status.isLocalRollbackOnly()) {
			if (status.isDebug()) {
				logger.debug("Transaction callback has explicitly requested rollback");
			}
			uowManager.setRollbackOnly();
		}
		triggerBeforeCompletion(status);
		if (status.isNewSynchronization()) {
			List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
			TransactionSynchronizationManager.clear();
			if (!synchronizations.isEmpty()) {
				uowManager.registerInterposedSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
			}
		}
	}
}
 
Example 17
Source File: RoutingSynchronizationManager.java    From easyooo-framework with Apache License 2.0 4 votes vote down vote up
public static void invokeAfterCompletion(int completionStatus) {
	List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager
			.getSynchronizations();
	TransactionSynchronizationUtils.invokeAfterCompletion(synchronizations, completionStatus);
}
 
Example 18
Source File: JtaUtil.java    From iaf with Apache License 2.0 4 votes vote down vote up
public static String displayTransactionStatus(TransactionStatus txStatus) {
	String result;
	result="txName ["+TransactionSynchronizationManager.getCurrentTransactionName()+"]";
	if (txStatus!=null) {
		result+=" status new ["+txStatus.isNewTransaction()+"]";
		result+=" status completeted ["+txStatus.isCompleted()+"]";
		result+=" status rollbackOnly ["+txStatus.isRollbackOnly()+"]";
		result+=" status hasSavepoint ["+txStatus.hasSavepoint()+"]";
	} else {
		result+=" currently not in a transaction";
	}
	result+=" isolation ["+TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()+"]";
	result+=" active ["+TransactionSynchronizationManager.isActualTransactionActive()+"]";
	boolean syncActive=TransactionSynchronizationManager.isSynchronizationActive();
	result+=" synchronization active ["+syncActive+"]";
	result+="\n";
	Map<Object, Object> resources = TransactionSynchronizationManager.getResourceMap();
	result += "resources:\n";
	if (resources==null) {
		result+="  map is null\n";
	} else {
		for (Iterator<Object> it=resources.keySet().iterator(); it.hasNext();) {
			Object key = it.next();
			Object resource = resources.get(key);
			result += ClassUtils.nameOf(key)+"("+key+"): "+ClassUtils.nameOf(resource)+"("+resource+")\n";
			if (resource instanceof JmsResourceHolder) {
				JmsResourceHolder jrh = (JmsResourceHolder)resource; 
				result+="  connection: "+jrh.getConnection()+", session: "+jrh.getSession()+"\n";
			}
		}
	}
	if (syncActive) {
		List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
		result += "synchronizations:\n";
		for (int i=0; i<synchronizations.size(); i++) {
			TransactionSynchronization synchronization = synchronizations.get(i);
			result += ClassUtils.nameOf(synchronization)+"("+synchronization+")\n"; 
		}
	}
	return result;
}