List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager isActualTransactionActive
public static boolean isActualTransactionActive()
From source file:org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateTemplate.java
protected boolean isCurrentTransactionReadOnly() { if (TransactionSynchronizationManager.hasResource(sessionFactory)) { if (TransactionSynchronizationManager.isActualTransactionActive()) { return TransactionSynchronizationManager.isCurrentTransactionReadOnly(); } else {/* w w w.j av a 2 s . com*/ return osivReadOnly; } } else { return false; } }
From source file:org.kuali.rice.kcb.service.impl.MessagingServiceImpl.java
private void queueJob(MessageProcessingJob.Mode mode, long messageId, String user, String cause) { // queue up the processing job after the transaction has committed LOG.debug("registering synchronization"); if (!TransactionSynchronizationManager.isSynchronizationActive()) { throw new RiceRuntimeException("transaction syncronization is not active " + "(!TransactionSynchronizationManager.isSynchronizationActive())"); } else if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new RiceRuntimeException("actual transaction is not active " + "(!TransactionSynchronizationManager.isActualTransactionActive())"); }/* ww w . j av a 2s .c o m*/ TransactionSynchronizationManager.registerSynchronization(new QueueProcessingJobSynchronization(jobName, jobGroup, mode, messageId, user, cause, synchronous)); }
From source file:org.kuali.rice.kcb.service.impl.MessagingServiceTest.java
@Test public void testDeliver() throws Exception { Assert.assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); deliver(); }
From source file:org.kuali.rice.kcb.service.impl.MessagingServiceTest.java
@Test public void testDismiss() throws Exception { Assert.assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); long id = deliver(); registerJobListener();//from ww w . j av a 2 s . c om services.getMessagingService().remove(id, "a user", "a cause"); waitForNextJobCompletion(); Collection<MessageDelivery> deliveries = services.getMessageDeliveryService().getAllMessageDeliveries(); assertNotNull(deliveries); // should be all gone except for the 2 bad deliveries assertEquals(2, deliveries.size()); for (MessageDelivery d : deliveries) { assertTrue("broken".equals(d.getDelivererTypeName()) || "bogus".equals(d.getDelivererTypeName())); } }
From source file:org.kuali.rice.kcb.service.impl.MessagingServiceTest.java
@Test public void testDismissByOriginId() throws Exception { Assert.assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); long id = deliver(); registerJobListener();/* w ww . j a v a2 s.c om*/ services.getMessagingService().removeByOriginId("origin id", "a user", "a cause"); waitForNextJobCompletion(); Collection<MessageDelivery> deliveries = services.getMessageDeliveryService().getAllMessageDeliveries(); assertNotNull(deliveries); // should be all gone except for the 2 bad deliveries assertEquals(2, deliveries.size()); // should be all gone except for the 2 bad deliveries assertEquals(2, deliveries.size()); for (MessageDelivery d : deliveries) { assertTrue("broken".equals(d.getDelivererTypeName()) || "bogus".equals(d.getDelivererTypeName())); } }
From source file:org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.java
public static void bindResourceToTransaction(RabbitResourceHolder resourceHolder, ConnectionFactory connectionFactory, boolean synched) { if (TransactionSynchronizationManager.hasResource(connectionFactory) || !TransactionSynchronizationManager.isActualTransactionActive() || !synched) { return;/*from w w w. j av a2s . co m*/ } TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolder); resourceHolder.setSynchronizedWithTransaction(true); if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization( new RabbitResourceSynchronization(resourceHolder, connectionFactory, synched)); } }
From source file:org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.java
/** * Invoke the specified listener as Spring ChannelAwareMessageListener, exposing a new Rabbit Session (potentially * with its own transaction) to the listener if demanded. * @param listener the Spring ChannelAwareMessageListener to invoke * @param channel the Rabbit Channel to operate on * @param message the received Rabbit Message * @throws Exception if thrown by Rabbit API methods or listener itself. * <p>//from ww w . ja v a 2 s . co m * Exception thrown from listener will be wrapped to {@link ListenerExecutionFailedException}. * @see ChannelAwareMessageListener * @see #setExposeListenerChannel(boolean) */ protected void doInvokeListener(ChannelAwareMessageListener listener, Channel channel, Message message) throws Exception { RabbitResourceHolder resourceHolder = null; Channel channelToUse = channel; boolean boundHere = false; try { if (!isExposeListenerChannel()) { // We need to expose a separate Channel. resourceHolder = getTransactionalResourceHolder(); channelToUse = resourceHolder.getChannel(); /* * If there is a real transaction, the resource will have been bound; otherwise * we need to bind it temporarily here. Any work done on this channel * will be committed in the finally block. */ if (isChannelLocallyTransacted() && !TransactionSynchronizationManager.isActualTransactionActive()) { resourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), resourceHolder); boundHere = true; } } else { // if locally transacted, bind the current channel to make it available to RabbitTemplate if (isChannelLocallyTransacted()) { RabbitResourceHolder localResourceHolder = new RabbitResourceHolder(channelToUse, false); localResourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), localResourceHolder); boundHere = true; } } // Actually invoke the message listener... try { listener.onMessage(message, channelToUse); } catch (Exception e) { throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message); } } finally { if (resourceHolder != null && boundHere) { // so the channel exposed (because exposeListenerChannel is false) will be closed resourceHolder.setSynchronizedWithTransaction(false); } ConnectionFactoryUtils.releaseResources(resourceHolder); if (boundHere) { // unbind if we bound TransactionSynchronizationManager.unbindResource(this.getConnectionFactory()); if (!isExposeListenerChannel() && isChannelLocallyTransacted()) { /* * commit the temporary channel we exposed; the consumer's channel * will be committed later. Note that when exposing a different channel * when there's no transaction manager, the exposed channel is committed * on each message, and not based on txSize. */ RabbitUtils.commitIfNecessary(channelToUse); } } } }
From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanRetryTests.java
@SuppressWarnings("unchecked") @Test/*from w w w .j ava 2 s .co m*/ public void testSkipAndRetryWithWriteFailure() throws Exception { factory.setListeners(new StepListener[] { new SkipListenerSupport<String, String>() { @Override public void onSkipInWrite(String item, Throwable t) { recovered.add(item); assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); } } }); factory.setSkipLimit(2); ItemReader<String> provider = new ListItemReader<String>(Arrays.asList("a", "b", "c", "d", "e", "f")) { @Override public String read() { String item = super.read(); logger.debug("Read Called! Item: [" + item + "]"); provided.add(item); count++; return item; } }; ItemWriter<String> itemWriter = new ItemWriter<String>() { @Override public void write(List<? extends String> item) throws Exception { logger.debug("Write Called! Item: [" + item + "]"); processed.addAll(item); written.addAll(item); if (item.contains("b") || item.contains("d")) { throw new RuntimeException("Write error - planned but recoverable."); } } }; factory.setItemReader(provider); factory.setItemWriter(itemWriter); factory.setRetryLimit(5); factory.setRetryableExceptionClasses(getExceptionMap(RuntimeException.class)); AbstractStep step = (AbstractStep) factory.getObject(); step.setName("mytest"); StepExecution stepExecution = new StepExecution(step.getName(), jobExecution); repository.add(stepExecution); step.execute(stepExecution); assertEquals(2, recovered.size()); assertEquals(2, stepExecution.getSkipCount()); assertEquals(2, stepExecution.getWriteSkipCount()); List<String> expectedOutput = Arrays.asList(StringUtils.commaDelimitedListToStringArray("a,c,e,f")); assertEquals(expectedOutput, written); assertEquals("[a, b, c, d, e, f, null]", provided.toString()); assertEquals("[a, b, b, b, b, b, b, c, d, d, d, d, d, d, e, f]", processed.toString()); assertEquals("[b, d]", recovered.toString()); }
From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanRetryTests.java
@SuppressWarnings("unchecked") @Test/* w w w . j ava2 s . c o m*/ public void testSkipAndRetryWithWriteFailureAndNonTrivialCommitInterval() throws Exception { factory.setCommitInterval(3); factory.setListeners(new StepListener[] { new SkipListenerSupport<String, String>() { @Override public void onSkipInWrite(String item, Throwable t) { recovered.add(item); assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); } } }); factory.setSkipLimit(2); ItemReader<String> provider = new ListItemReader<String>(Arrays.asList("a", "b", "c", "d", "e", "f")) { @Override public String read() { String item = super.read(); logger.debug("Read Called! Item: [" + item + "]"); provided.add(item); count++; return item; } }; ItemWriter<String> itemWriter = new ItemWriter<String>() { @Override public void write(List<? extends String> item) throws Exception { logger.debug("Write Called! Item: [" + item + "]"); processed.addAll(item); written.addAll(item); if (item.contains("b") || item.contains("d")) { throw new RuntimeException("Write error - planned but recoverable."); } } }; factory.setItemReader(provider); factory.setItemWriter(itemWriter); factory.setRetryLimit(5); factory.setRetryableExceptionClasses(getExceptionMap(RuntimeException.class)); AbstractStep step = (AbstractStep) factory.getObject(); step.setName("mytest"); StepExecution stepExecution = new StepExecution(step.getName(), jobExecution); repository.add(stepExecution); step.execute(stepExecution); assertEquals(2, recovered.size()); assertEquals(2, stepExecution.getSkipCount()); assertEquals(2, stepExecution.getWriteSkipCount()); List<String> expectedOutput = Arrays.asList(StringUtils.commaDelimitedListToStringArray("a,c,e,f")); assertEquals(expectedOutput, written); // [a, b, c, d, e, f, null] assertEquals(7, provided.size()); // [a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, d, e, f, d, // e, f, d, e, f, d, e, f, d, e, f, d, e, f] // System.err.println(processed); assertEquals(36, processed.size()); // [b, d] assertEquals(2, recovered.size()); }
From source file:org.springframework.batch.item.database.AbstractCursorItemReader.java
/** * Close the cursor and database connection. Make call to cleanupOnClose so sub classes can cleanup * any resources they have allocated./*from w w w . ja va 2 s .co m*/ */ @Override protected void doClose() throws Exception { initialized = false; JdbcUtils.closeResultSet(this.rs); rs = null; cleanupOnClose(); if (useSharedExtendedConnection && dataSource instanceof ExtendedConnectionDataSourceProxy) { ((ExtendedConnectionDataSourceProxy) dataSource).stopCloseSuppression(this.con); if (!TransactionSynchronizationManager.isActualTransactionActive()) { DataSourceUtils.releaseConnection(con, dataSource); } } else { JdbcUtils.closeConnection(this.con); } }