Example usage for org.springframework.transaction.support TransactionCallback TransactionCallback

List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionCallback TransactionCallback.

Prototype

TransactionCallback

Source Link

Usage

From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.java

private boolean receiveAndExecute(final BlockingQueueConsumer consumer) throws Throwable {

    if (this.transactionManager != null) {
        try {//  w w w . java2s .c  o  m
            return new TransactionTemplate(this.transactionManager, this.transactionAttribute)
                    .execute(new TransactionCallback<Boolean>() {
                        @Override
                        public Boolean doInTransaction(TransactionStatus status) {
                            ConnectionFactoryUtils.bindResourceToTransaction(
                                    new RabbitResourceHolder(consumer.getChannel(), false),
                                    getConnectionFactory(), true);
                            try {
                                return doReceiveAndExecute(consumer);
                            } catch (RuntimeException e) {
                                throw e;
                            } catch (Throwable e) { //NOSONAR
                                // ok to catch Throwable here because we re-throw it below
                                throw new WrappedTransactionException(e);
                            }
                        }
                    });
        } catch (WrappedTransactionException e) {
            throw e.getCause();
        }
    }

    return doReceiveAndExecute(consumer);

}

From source file:org.springframework.batch.core.step.tasklet.AsyncChunkOrientedStepIntegrationTests.java

@Test
@Ignore/* www .j  a  v a 2 s  . c o m*/
public void testStatus() throws Exception {

    step.setTasklet(new TestingChunkOrientedTasklet<String>(
            getReader(new String[] { "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c" }),
            new ItemWriter<String>() {
                @Override
                public void write(List<? extends String> data) throws Exception {
                    written.addAll(data);
                }
            }, chunkOperations));

    final JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters(
            Collections.singletonMap("run.id", new JobParameter(getClass().getName() + ".1"))));
    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);

    jobRepository.add(stepExecution);
    step.execute(stepExecution);
    assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
    // Need a transaction so one connection is enough to get job execution and its parameters
    StepExecution lastStepExecution = new TransactionTemplate(transactionManager)
            .execute(new TransactionCallback<StepExecution>() {
                @Override
                public StepExecution doInTransaction(TransactionStatus status) {
                    return jobRepository.getLastStepExecution(jobExecution.getJobInstance(), step.getName());
                }
            });
    assertEquals(lastStepExecution, stepExecution);
    assertFalse(lastStepExecution == stepExecution);
}

From source file:org.springframework.batch.item.xml.AbstractStaxEventWriterItemWriterTests.java

/**
 * Write list of domain objects and check the output file.
 *///ww  w  .  ja  v  a 2  s.co m
@SuppressWarnings("resource")
@Test
public void testWrite() throws Exception {
    StopWatch stopWatch = new StopWatch(getClass().getSimpleName());
    stopWatch.start();
    for (int i = 0; i < MAX_WRITE; i++) {
        new TransactionTemplate(new ResourcelessTransactionManager()).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                try {
                    writer.write(objects);
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    throw new IllegalStateException("Exception encountered on write", e);
                }
                return null;
            }
        });
    }
    writer.close();
    stopWatch.stop();
    logger.info("Timing for XML writer: " + stopWatch);
    XMLUnit.setIgnoreWhitespace(true);
    // String content = FileUtils.readFileToString(resource.getFile());
    // System.err.println(content);
    XMLAssert.assertXMLEqual(new FileReader(expected.getFile()), new FileReader(resource.getFile()));

}

From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java

@Test
public void testTransactionalRestart() throws Exception {
    writer.open(executionContext);/*from  www  .ja va 2 s  .co  m*/

    PlatformTransactionManager transactionManager = new ResourcelessTransactionManager();

    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                // write item
                writer.write(items);
            } catch (Exception e) {
                throw new UnexpectedInputException("Could not write data", e);
            }
            // get restart data
            writer.update(executionContext);
            return null;
        }
    });
    writer.close();

    // create new writer from saved restart data and continue writing
    writer = createItemWriter();
    writer.open(executionContext);
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                writer.write(items);
            } catch (Exception e) {
                throw new UnexpectedInputException("Could not write data", e);
            }
            // get restart data
            writer.update(executionContext);
            return null;
        }
    });
    writer.close();

    // check the output is concatenation of 'before restart' and 'after
    // restart' writes.
    String outputFile = getOutputFileContent();
    assertEquals(2, StringUtils.countOccurrencesOf(outputFile, TEST_STRING));
    assertTrue(outputFile.contains("<root>" + TEST_STRING + TEST_STRING + "</root>"));
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java

private void testTransactionalRestartWithMultiByteCharacter(String encoding) throws Exception {
    writer.setEncoding(encoding);/*  ww w .  ja va2 s. c o m*/
    writer.open(executionContext);

    PlatformTransactionManager transactionManager = new ResourcelessTransactionManager();

    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                // write item
                writer.write(itemsMultiByte);
            } catch (Exception e) {
                throw new UnexpectedInputException("Could not write data", e);
            }
            // get restart data
            writer.update(executionContext);
            return null;
        }
    });
    writer.close();

    // create new writer from saved restart data and continue writing
    writer = createItemWriter();
    writer.setEncoding(encoding);
    writer.open(executionContext);
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                writer.write(itemsMultiByte);
            } catch (Exception e) {
                throw new UnexpectedInputException("Could not write data", e);
            }
            // get restart data
            writer.update(executionContext);
            return null;
        }
    });
    writer.close();

    // check the output is concatenation of 'before restart' and 'after
    // restart' writes.
    String outputFile = getOutputFileContent(encoding);
    assertEquals(2, StringUtils.countOccurrencesOf(outputFile, TEST_STRING_MULTI_BYTE));
    assertTrue(outputFile.contains("<root>" + TEST_STRING_MULTI_BYTE + TEST_STRING_MULTI_BYTE + "</root>"));
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java

@Test
public void testTransactionalRestartFailOnFirstWrite() throws Exception {

    PlatformTransactionManager transactionManager = new ResourcelessTransactionManager();

    writer.open(executionContext);//www  . j av  a  2s  . c  o m
    try {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                try {
                    writer.write(items);
                } catch (Exception e) {
                    throw new IllegalStateException("Could not write data", e);
                }
                throw new UnexpectedInputException("Could not write data");
            }
        });
    } catch (UnexpectedInputException e) {
        // expected
    }
    writer.close();
    String outputFile = getOutputFileContent();
    assertEquals("<root></root>", outputFile);

    // create new writer from saved restart data and continue writing
    writer = createItemWriter();
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            writer.open(executionContext);
            try {
                writer.write(items);
            } catch (Exception e) {
                throw new UnexpectedInputException("Could not write data", e);
            }
            // get restart data
            writer.update(executionContext);
            return null;
        }
    });
    writer.close();

    // check the output is concatenation of 'before restart' and 'after
    // restart' writes.
    outputFile = getOutputFileContent();
    assertEquals(1, StringUtils.countOccurrencesOf(outputFile, TEST_STRING));
    assertTrue(outputFile.contains("<root>" + TEST_STRING + "</root>"));
    assertEquals("<root><StaxEventItemWriter-testString/></root>", outputFile);
}

From source file:org.springframework.batch.item.xml.TransactionalStaxEventItemWriterTests.java

/**
 * Item is written to the output file only after flush.
 *///from ww w . j a  v a2 s. c  o  m
@Test
public void testWriteAndFlush() throws Exception {
    writer.open(executionContext);
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                writer.write(items);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    });
    writer.close();
    String content = outputFileContent();
    assertTrue("Wrong content: " + content, content.contains(TEST_STRING));
}

From source file:org.springframework.batch.item.xml.TransactionalStaxEventItemWriterTests.java

/**
 * Item is written to the output file only after flush.
 *//* w  ww  .j ava  2s .co  m*/
@Test
public void testWriteWithHeaderAfterRollback() throws Exception {
    writer.setHeaderCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "header"));
                writer.add(factory.createEndElement("", "", "header"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.open(executionContext);
    try {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                try {
                    writer.write(items);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                throw new RuntimeException("Planned");
            }
        });
        fail("Expected RuntimeException");
    } catch (RuntimeException e) {
        // expected
    }
    writer.close();
    writer.open(executionContext);
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                writer.write(items);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    });
    writer.close();
    String content = outputFileContent();
    assertEquals("Wrong content: " + content, 1, StringUtils.countOccurrencesOf(content, ("<header/>")));
    assertEquals("Wrong content: " + content, 1, StringUtils.countOccurrencesOf(content, TEST_STRING));
}

From source file:org.springframework.batch.item.xml.TransactionalStaxEventItemWriterTests.java

/**
 * Item is written to the output file only after flush.
 *///from   ww  w.  ja  v  a  2s.  co  m
@Test
public void testWriteWithHeaderAfterFlushAndRollback() throws Exception {
    writer.setHeaderCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "header"));
                writer.add(factory.createEndElement("", "", "header"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.open(executionContext);
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                writer.write(items);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    });
    writer.update(executionContext);
    writer.close();
    writer.open(executionContext);
    try {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                try {
                    writer.write(items);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                throw new RuntimeException("Planned");
            }
        });
        fail("Expected RuntimeException");
    } catch (RuntimeException e) {
        // expected
    }
    writer.close();
    String content = outputFileContent();
    assertEquals("Wrong content: " + content, 1, StringUtils.countOccurrencesOf(content, ("<header/>")));
    assertEquals("Wrong content: " + content, 1, StringUtils.countOccurrencesOf(content, TEST_STRING));
}