diff --git a/build.gradle b/build.gradle index 82ecd4c76..9a1f1095e 100644 --- a/build.gradle +++ b/build.gradle @@ -8,11 +8,12 @@ buildscript { maven { url 'https://plugins.gradle.org/m2/' } } dependencies { - classpath 'io.spring.gradle:docbook-reference-plugin:0.3.1' classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7' classpath 'io.spring.gradle:spring-io-plugin:0.0.5.RELEASE' classpath "io.spring.gradle:dependency-management-plugin:0.6.0.RELEASE" classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.1" + classpath "org.asciidoctor:asciidoctor-gradle-plugin:1.5.3" + classpath "org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.14" } } @@ -381,6 +382,10 @@ project('spring-batch-infrastructure') { } } +project('spring-batch-docs') { + +} + project('spring-batch-core-tests') { description = 'Spring Batch Core Tests' project.tasks.findByPath("artifactoryPublish")?.enabled = false @@ -613,10 +618,28 @@ project('spring-batch-samples') { } } -apply plugin: 'docbook-reference' +apply plugin: "org.asciidoctor.convert" +asciidoctor { + sourceDir = file('spring-batch-docs/asciidoc') + sources { + include '*.adoc' + } + logDocuments = true + backends = ["html", "pdf"] + options doctype: 'book', eruby: 'erubis' + attributes 'icons': 'font', + 'idprefix': '', + 'idseparator': '-', + docinfo: '', + revnumber: project.version, + sectanchors: '', + sectnums: '', + 'source-highlighter': 'coderay@', // TODO switch to 'rouge' once supported by the html5 backend + stylesdir: 'stylesheets/', + stylesheet: 'spring.css', + 'spring-version': project.version, + 'allow-uri-read': '' -reference { - sourceDir = file('src/site/docbook/reference') } apply plugin: 'org.sonarqube' @@ -698,7 +721,32 @@ task docsZip(type: Zip) { into 'api' } - from (reference) { + from (asciidoctor) { + exclude '*.pdf' + exclude '*.html' + exclude 'images' + exclude 'html/index-pdf.html' + exclude 'pdf/images' + exclude 'pdf/appendix.pdf' + exclude 'pdf/common-patterns.pdf' + exclude 'pdf/domain.pdf' + exclude 'pdf/index.pdf' + exclude 'pdf/index-single.pdf' + exclude 'pdf/job.pdf' + exclude 'pdf/jsr-352.pdf' + exclude 'pdf/readersAndWriters.pdf' + exclude 'pdf/repeat.pdf' + exclude 'pdf/retry.pdf' + exclude 'pdf/scalability.pdf' + exclude 'pdf/schema-appendix.pdf' + exclude 'pdf/spring-batch-integration.pdf' + exclude 'pdf/spring-batch-intro.pdf' + exclude 'pdf/step.pdf' + exclude 'pdf/testing.pdf' + exclude 'pdf/transaction-appendix.pdf' + exclude 'pdf/whatsnew.pdf' + exclude 'pdf/glossary.pdf' + into 'reference' } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9abb2caa9..813789588 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Sat May 06 15:13:08 CEST 2017 +#Wed May 24 14:01:03 EDT 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-all.zip diff --git a/settings.gradle b/settings.gradle index 6ff4908be..8cf9aadd3 100644 --- a/settings.gradle +++ b/settings.gradle @@ -2,6 +2,7 @@ rootProject.name = 'spring-batch' include 'spring-batch-core' include 'spring-batch-core-tests' +include 'spring-batch-docs' include 'spring-batch-infrastructure' include 'spring-batch-infrastructure-tests' include 'spring-batch-test' diff --git a/spring-batch-docs/asciidoc/appendix.adoc b/spring-batch-docs/asciidoc/appendix.adoc new file mode 100644 index 000000000..70763e602 --- /dev/null +++ b/spring-batch-docs/asciidoc/appendix.adoc @@ -0,0 +1,128 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[listOfReadersAndWriters]] + +[appendix] +== List of ItemReaders and ItemWriters + +[[itemReadersAppendix]] + +=== Item Readers + +.Available Item Readers +[options="header"] +|=============== +|Item Reader|Description +|AbstractItemCountingItemStreamItemReader|Abstract base class that provides basic + restart capabilities by counting the number of items returned from + an `ItemReader`. +|AggregateItemReader|An `ItemReader` that delivers a list as its + item, storing up objects from the injected `ItemReader` until they + are ready to be packed out as a collection. This `ItemReader` should + mark the beginning and end of records with the constant values in + `FieldSetMapper AggregateItemReader#__$$BEGIN_RECORD$$__` and + `AggregateItemReader#__$$END_RECORD$$__` +|AmqpItemReader|Given a Spring AmqpTemplate it provides + synchronous receive methods. The receiveAndConvert() method + lets you receive POJO objects. +|FlatFileItemReader|Reads from a flat file. Includes `ItemStream` + and Skippable functionality. See section on Read from a + File +|HibernateCursorItemReader|Reads from a cursor based on an HQL query. See + section on Reading from a Database +|HibernatePagingItemReader|Reads from a paginated HQL query +|ItemReaderAdapter|Adapts any class to the + `ItemReader` interface. +|JdbcCursorItemReader|Reads from a database cursor via JDBC. See + HOWTO - Read from a Database +|JdbcPagingItemReader|Given a SQL statement, pages through the rows, + such that large datasets can be read without running out of + memory +|JmsItemReader|Given a Spring JmsOperations object and a JMS + Destination or destination name to send errors, provides items + received through the injected JmsOperations receive() + method +|JpaPagingItemReader|Given a JPQL statement, pages through the + rows, such that large datasets can be read without running out of + memory +|ListItemReader|Provides the items from a list, one at a + time +|MongoItemReader|Given a MongoOperations object and JSON based MongoDB + query, provides items received from the MongoOperations find method +|Neo4jItemReader|Given a Neo4jOperations object and the components of a + Cyhper query, items are returned as the result of the Neo4jOperations.query + method +|RepositoryItemReader|Given a Spring Data PagingAndSortingRepository object, + a Sort and the name of method to execute, returns items provided by the + Spring Data repository implementation +|StoredProcedureItemReader|Reads from a database cursor resulting from the + execution of a database stored procedure. See HOWTO - Read from a + Database +|StaxEventItemReader|Reads via StAX. See HOWTO - Read from a + File + +|=============== + + +[[itemWritersAppendix]] + + +=== Item Writers + +.Available Item Writers +[options="header"] +|=============== +|Item Writer|Description +|AbstractItemStreamItemWriter|Abstract base class that combines the + `ItemStream` and + `ItemWriter` interfaces. +|AmqpItemWriter|Given a Spring AmqpTemplate it provides + for synchronous send method. The convertAndSend(Object) + method lets you send POJO objects. +|CompositeItemWriter|Passes an item to the process method of each + in an injected __List__ of __ItemWriter__ objects +|FlatFileItemWriter|Writes to a flat file. Includes `ItemStream` and + Skippable functionality. See section on Writing to a File +|GemfireItemWriter|Using a GemfireOperations object, items wre either written + or removed from the Gemfire instance based on the configuration of the delete + flag +|HibernateItemWriter|This item writer is hibernate session aware + and handles some transaction-related work that a non-"hibernate + aware" item writer would not need to know about and then delegates + to another item writer to do the actual writing. +|ItemWriterAdapter|Adapts any class to the + `ItemWriter` interface. +|JdbcBatchItemWriter|Uses batching features from a + `PreparedStatement`, if available, and can + take rudimentary steps to locate a failure during a + `flush`. +|JmsItemWriter|Using a JmsOperations object, items are written + to the default queue via the JmsOperations.convertAndSend() method +|JpaItemWriter|This item writer is JPA EntityManager aware + and handles some transaction-related work that a non-"jpa aware" + `ItemWriter` would not need to know about and + then delegates to another writer to do the actual writing. +|MimeMessageItemWriter|Using Spring's JavaMailSender, items of type `MimeMessage` + are sent as mail messages +|MongoItemWriter|Given a MongoOperations object, items are written + via the MongoOperations.save(Object) method. The actual write is delayed + until the last possible moment before the transaction commits. +|Neo4jItemWriter|Given a Neo4jOperations object, items are persisted via the + save(Object) method or deleted via the delete(Object) per the + `ItemWriter's` configuration +|PropertyExtractingDelegatingItemWriter|Extends AbstractMethodInvokingDelegator + creating arguments on the fly. Arguments are created by retrieving + the values from the fields in the item to be processed (via a + SpringBeanWrapper) based on an injected array of field + name +|RepositoryItemWriter|Given a Spring Data CrudRepository implementation, + items are saved via the method specified in the configuration. +|StaxEventItemWriter|Uses an __ObjectToXmlSerializer__ implementation to + convert each item to XML and then writes it to an XML file using + StAX. + +|=============== + + diff --git a/spring-batch-docs/asciidoc/common-patterns.adoc b/spring-batch-docs/asciidoc/common-patterns.adoc new file mode 100644 index 000000000..3ee5a7e80 --- /dev/null +++ b/spring-batch-docs/asciidoc/common-patterns.adoc @@ -0,0 +1,635 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[commonPatterns]] + +== Common Batch Patterns + +Some batch jobs can be assembled purely from off-the-shelf components + in Spring Batch. For instance the `ItemReader` and + `ItemWriter` implementations can be configured to cover + a wide range of scenarios. However, for the majority of cases, custom code + will have to be written. The main API entry points for application + developers are the `Tasklet`, + `ItemReader`, `ItemWriter` and the + various listener interfaces. Most simple batch jobs will be able to use + off-the-shelf input from a Spring Batch `ItemReader`, + but it is often the case that there are custom concerns in the processing + and writing, which require developers to implement an + `ItemWriter` or + `ItemProcessor`. + +Here, we provide a few examples of common patterns in custom business + logic. These examples primarily feature the listener interfaces. It should + be noted that an `ItemReader` or + `ItemWriter` can implement a listener interface as + well, if appropriate. + +[[loggingItemProcessingAndFailures]] +=== Logging Item Processing and Failures + +A common use case is the need for special handling of errors in a + step, item by item, perhaps logging to a special channel, or inserting a + record into a database. A chunk-oriented `Step` + (created from the step factory beans) allows users to implement this use + case with a simple `ItemReadListener`, for errors on + read, and an `ItemWriteListener`, for errors on + write. The below code snippets illustrate a listener that logs both read + and write failures: + +[source, java] +---- +public class ItemFailureLoggerListener extends ItemListenerSupport { + + private static Log logger = LogFactory.getLog("item.error"); + + public void onReadError(Exception ex) { + logger.error("Encountered error on read", e); + } + + public void onWriteError(Exception ex, Object item) { + logger.error("Encountered error on write", ex); + } +} +---- + +Having implemented this listener it must be registered with the step: +[source, xml] +---- + +... + + + + + + +---- + +Remember that if your listener does anything in an + `onError()` method, it will be inside a transaction that is + going to be rolled back. If you need to use a transactional resource such + as a database inside an `onError()` method, consider adding a + declarative transaction to that method (see Spring Core Reference Guide + for details), and giving its propagation attribute the value + REQUIRES_NEW. + + +[[stoppingAJobManuallyForBusinessReasons]] +=== Stopping a Job Manually for Business Reasons + +Spring Batch provides a `stop()` method + through the `JobLauncher` interface, but this is + really for use by the operator rather than the application programmer. + Sometimes it is more convenient or makes more sense to stop a job + execution from within the business logic. + +The simplest thing to do is to throw a + `RuntimeException` (one that isn't retried + indefinitely or skipped). For example, a custom exception type could be + used, as in the example below: + +[source, java] +---- +public class PoisonPillItemWriter implements ItemWriter { + + public void write(T item) throws Exception { + if (isPoisonPill(item)) { + throw new PoisonPillException("Posion pill detected: " + item); + } + } +} +---- + +Another simple way to stop a step from executing is to simply return +`null` from the `ItemReader`: + +[source, java] +---- +public class EarlyCompletionItemReader implements ItemReader { + + private ItemReader delegate; + + public void setDelegate(ItemReader delegate) { ... } + + public T read() throws Exception { + T item = delegate.read(); + if (isEndItem(item)) { + return null; // end the step here + } + return item; + } + +} +---- +The previous example actually relies on the fact that there is a + default implementation of the `CompletionPolicy` + strategy which signals a complete batch when the item to be processed is + `null`. A more sophisticated completion policy could be implemented and + injected into the `Step` through the + `SimpleStepFactoryBean`: + +[source, xml] +---- + + + + + + + +---- + +An alternative is to set a flag in the + `StepExecution`, which is checked by the + `Step` implementations in the framework in between + item processing. To implement this alternative, we need access to the + current `StepExecution`, and this can be achieved by + implementing a `StepListener` and registering it with + the `Step`. Here is an example of a listener that + sets the flag: + +[source, java] +---- +public class CustomItemWriter extends ItemListenerSupport implements StepListener { + + private StepExecution stepExecution; + + public void beforeStep(StepExecution stepExecution) { + this.stepExecution = stepExecution; + } + + public void afterRead(Object item) { + if (isPoisonPill(item)) { + stepExecution.setTerminateOnly(true); + } + } + +} +---- + +The default behavior here when the flag is set is for the step to + throw a `JobInterruptedException`. This can be + controlled through the `StepInterruptionPolicy`, but + the only choice is to throw or not throw an exception, so this is always + an abnormal ending to a job. + + +[[addingAFooterRecord]] +=== Adding a Footer Record + +Often when writing to flat files, a "footer" record must be appended + to the end of the file, after all processing has be completed. This can + also be achieved using the `FlatFileFooterCallback` + interface provided by Spring Batch. The + `FlatFileFooterCallback` (and its counterpart, the + `FlatFileHeaderCallback`) are optional properties of + the `FlatFileItemWriter`: + +[source, xml] +---- + + + + + + +---- + +The footer callback interface is very simple. It has just one method +that is called when the footer must be written: + +[source, java] +---- +public interface FlatFileFooterCallback { + + void writeFooter(Writer writer) throws IOException; + +} +---- + +[[writingASummaryFooter]] +==== Writing a Summary Footer + +A very common requirement involving footer records is to aggregate + information during the output process and to append this information to + the end of the file. This footer serves as a summarization of the file + or provides a checksum. + +For example, if a batch job is writing + `Trade` records to a flat file, and there is a + requirement that the total amount from all the + `Trades` is placed in a footer, then the following + `ItemWriter` implementation can be used: + +[source, java] +---- +public class TradeItemWriter implements ItemWriter, + FlatFileFooterCallback { + + private ItemWriter delegate; + + private BigDecimal totalAmount = BigDecimal.ZERO; + + public void write(List items) { + BigDecimal chunkTotal = BigDecimal.ZERO; + for (Trade trade : items) { + chunkTotal = chunkTotal.add(trade.getAmount()); + } + + delegate.write(items); + + // After successfully writing all items + totalAmount = totalAmount.add(chunkTotal); + } + + public void writeFooter(Writer writer) throws IOException { + writer.write("Total Amount Processed: " + totalAmount); + } + + public void setDelegate(ItemWriter delegate) {...} +} +---- + +This `TradeItemWriter` stores a + `totalAmount` value that is increased with the + `amount` from each Trade item written. + After the last Trade is processed, the framework + will call `writeFooter`, which will put that + `totalAmount` into the file. Note that the + `write` method makes use of a temporary variable, + chunkTotalAmount, that stores the total of the `Trades` + in the chunk. This is done to ensure that if a skip occurs in the + `write` method, that the + `totalAmount` will be left unchanged. It is only at + the end of the `write` method, once we are + guaranteed that no exceptions will be thrown, that we update the + `totalAmount`. + +In order for the `writeFooter` method to be + called, the `TradeItemWriter` (which implements + `FlatFileFooterCallback`) must be wired into the + `FlatFileItemWriter` as the + `footerCallback`: + +[source, xml] +---- + + + + + + + + + +---- + +The way that the `TradeItemWriter` has been + so far will only function correctly if the `Step` + is not restartable. This is because the class is stateful (since it + stores the `totalAmount`), but the `totalAmount` + is not persisted to the database, and therefore, it cannot be retrieved + in the event of a restart. In order to make this class restartable, the + `ItemStream` interface should be implemented along + with the methods `open` and + `update`: + +[source, java] +---- +public void open(ExecutionContext executionContext) { + if (executionContext.containsKey("total.amount") { + totalAmount = (BigDecimal) executionContext.get("total.amount"); + } +} + +public void update(ExecutionContext executionContext) { + executionContext.put("total.amount", totalAmount); +} +---- + +The update method will store the most + current version of `totalAmount` to the + `ExecutionContext` just before that object is + persisted to the database. The open method will + retrieve any existing `totalAmount` from the + `ExecutionContext` and use it as the starting point + for processing, allowing the `TradeItemWriter` to + pick up on restart where it left off the previous time the + `Step` was executed. + + + +[[drivingQueryBasedItemReaders]] +=== Driving Query Based ItemReaders + +In the chapter on readers and writers, database input using paging + was discussed. Many database vendors, such as DB2, have extremely + pessimistic locking strategies that can cause issues if the table being + read also needs to be used by other portions of the online application. + Furthermore, opening cursors over extremely large datasets can cause + issues on certain vendors. Therefore, many projects prefer to use a + 'Driving Query' approach to reading in data. This approach works by + iterating over keys, rather than the entire object that needs to be + returned, as the following example illustrates: + +.Driving Query Job +image::{batch-asciidoc}images/drivingQueryExample.png[Driving Query Job, scaledwidth="60%"] + + +As you can see, this example uses the same 'FOO' table as was used + in the cursor based example. However, rather than selecting the entire + row, only the ID's were selected in the SQL statement. So, rather than a + FOO object being returned from `read`, an Integer + will be returned. This number can then be used to query for the 'details', + which is a complete Foo object: + +.Driving Query Example +image::{batch-asciidoc}images/drivingQueryJob.png[Driving Query Example, scaledwidth="60%"] + +An `ItemProcessor` should be used to transform the key obtained from + the driving query into a full 'Foo' object. An existing DAO can be used to + query for the full object based on the key. + + +[[multiLineRecords]] +==== Multi-Line Records + +While it is usually the case with flat files that one each record is + confined to a single line, it is common that a file might have records + spanning multiple lines with multiple formats. The following excerpt from + a file illustrates this: + +---- +HEA;0013100345;2007-02-15 +NCU;Smith;Peter;;T;20014539;F +BAD;;Oak Street 31/A;;Small Town;00235;IL;US +FOT;2;2;267.34 +---- +Everything between the line starting with 'HEA' and the line + starting with 'FOT' is considered one record. There are a few + considerations that must be made in order to handle this situation + correctly: + + + +Instead of reading one record at a time, the + `ItemReader` must read every line of the + multi-line record as a group, so that it can be passed to the + `ItemWriter` intact. + + + +Each line type may need to be tokenized differently. + + + +Because a single record spans multiple lines, and we may not know + how many lines there are, the `ItemReader` must be + careful to always read an entire record. In order to do this, a custom + `ItemReader` should be implemented as a wrapper for + the `FlatFileItemReader`. + +[source, xml] +---- + + + + + + + + + + + + + + + +---- + +To ensure that each line is tokenized properly, which is especially + important for fixed length input, the + `PatternMatchingCompositeLineTokenizer` can be used + on the delegate `FlatFileItemReader`. See for more details. The delegate + reader will then use a `PassThroughFieldSetMapper` to + deliver a `FieldSet` for each line back to the + wrapping `ItemReader`. + +[source, xml] +---- + + + + + + + + + + +---- + +This wrapper will have to be able recognize the end of a record so + that it can continually call `read()` on its + delegate until the end is reached. For each line that is read, the wrapper + should build up the item to be returned. Once the footer is reached, the + item can be returned for delivery to the + `ItemProcessor` and `ItemWriter`. + +[source, java] +---- +private FlatFileItemReader
delegate; + +public Trade read() throws Exception { + Trade t = null; + + for (FieldSet line = null; (line = this.delegate.read()) != null;) { + String prefix = line.readString(0); + if (prefix.equals("HEA")) { + t = new Trade(); // Record must start with header + } + else if (prefix.equals("NCU")) { + Assert.notNull(t, "No header was found."); + t.setLast(line.readString(1)); + t.setFirst(line.readString(2)); + ... + } + else if (prefix.equals("BAD")) { + Assert.notNull(t, "No header was found."); + t.setCity(line.readString(4)); + t.setState(line.readString(6)); + ... + } + else if (prefix.equals("FOT")) { + return t; // Record must end with footer + } + } + Assert.isNull(t, "No 'END' was found."); + return null; +} +---- + +[[executingSystemCommands]] +=== Executing System Commands + +Many batch jobs may require that an external command be called from + within the batch job. Such a process could be kicked off separately by the + scheduler, but the advantage of common meta-data about the run would be + lost. Furthermore, a multi-step job would also need to be split up into + multiple jobs as well. + +Because the need is so common, Spring Batch provides a + `Tasklet` implementation for calling system + commands: + +[source, xml] +---- + + + + + +---- + +[[handlingStepCompletionWhenNoInputIsFound]] +=== Handling Step Completion When No Input is Found + +In many batch scenarios, finding no rows in a database or file to + process is not exceptional. The `Step` is simply + considered to have found no work and completes with 0 items read. All of + the `ItemReader` implementations provided out of the + box in Spring Batch default to this approach. This can lead to some + confusion if nothing is written out even when input is present. (which + usually happens if a file was misnamed, etc) For this reason, the meta + data itself should be inspected to determine how much work the framework + found to be processed. However, what if finding no input is considered + exceptional? In this case, programmatically checking the meta data for no + items processed and causing failure is the best solution. Because this is + a common use case, a listener is provided with just this + functionality: + +[source, java] +---- +public class NoWorkFoundStepExecutionListener extends StepExecutionListenerSupport { + + public ExitStatus afterStep(StepExecution stepExecution) { + if (stepExecution.getReadCount() == 0) { + return ExitStatus.FAILED; + } + return null; + } + +} +---- + +The above `StepExecutionListener` inspects the + readCount property of the `StepExecution` during the + 'afterStep' phase to determine if no items were read. If that is the case, + an exit code of FAILED is returned, indicating that the + `Step` should fail. Otherwise, `null` is returned, + which will not affect the status of the + `Step`. + + +[[passingDataToFutureSteps]] +=== Passing Data to Future Steps + +It is often useful to pass information from one step to another. + This can be done using the `ExecutionContext`. The + catch is that there are two `ExecutionContexts`: one + at the `Step` level and one at the + `Job` level. The `Step` + `ExecutionContext` lives only as long as the step + while the `Job` + `ExecutionContext` lives through the whole + `Job`. On the other hand, the + `Step` `ExecutionContext` is + updated every time the `Step` commits a chunk while + the `Job` `ExecutionContext` is + updated only at the end of each `Step`. + +The consequence of this separation is that all data must be placed + in the `Step` `ExecutionContext` + while the `Step` is executing. This will ensure that + the data will be stored properly while the `Step` is + on-going. If data is stored to the `Job` + `ExecutionContext`, then it will not be persisted + during `Step` execution and if the + `Step` fails, that data will be lost. + +[source, java] +---- +public class SavingItemWriter implements ItemWriter { + private StepExecution stepExecution; + + public void write(List items) throws Exception { + // ... + + ExecutionContext stepContext = this.stepExecution.getExecutionContext(); + stepContext.put("someKey", someObject); + } + + @BeforeStep + public void saveStepExecution(StepExecution stepExecution) { + this.stepExecution = stepExecution; + } +} +---- + +To make the data available to future `Steps`, + it will have to be "promoted" to the `Job` + `ExecutionContext` after the step has finished. + Spring Batch provides the + `ExecutionContextPromotionListener` for this purpose. + The listener must be configured with the keys related to the data in the + `ExecutionContext` that must be promoted. It can + also, optionally, be configured with a list of exit code patterns for + which the promotion should occur ("COMPLETED" is the default). As with all + listeners, it must be registered on the + `Step`. +[source, xml] +---- + + + + + + + + + + + + ... + + + + + + +---- + +Finally, the saved values must be retrieved from the + `Job` `ExecutionContext`: + +[source, java] +---- +public class RetrievingItemWriter implements ItemWriter { + private Object someObject; + + public void write(List items) throws Exception { + // ... + } + + @BeforeStep + public void retrieveInterstepData(StepExecution stepExecution) { + JobExecution jobExecution = stepExecution.getJobExecution(); + ExecutionContext jobContext = jobExecution.getExecutionContext(); + this.someObject = jobContext.get("someKey"); + } +} +---- diff --git a/spring-batch-docs/asciidoc/domain.adoc b/spring-batch-docs/asciidoc/domain.adoc new file mode 100644 index 000000000..708004b99 --- /dev/null +++ b/spring-batch-docs/asciidoc/domain.adoc @@ -0,0 +1,702 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[domainLanguageOfBatch]] + +== The Domain Language of Batch + +To any experienced batch architect, the overall concepts of batch +processing used in Spring Batch should be familiar and comfortable. There +are "Jobs" and "Steps" and developer supplied processing units called +`ItemReaders` and `ItemWriters`. However, because of the Spring patterns, +operations, templates, callbacks, and idioms, there are opportunities for +the following: + +* significant improvement in adherence to a clear separation of concerns +* clearly delineated architectural layers and services provided as interfaces +* simple and default implementations that allow for quick adoption and ease of use out-of-the-box +* significantly enhanced extensibility + +The diagram below is simplified version of the batch reference +architecture that has been used for decades. It provides an overview of the +components that make up the domain language of batch processing. This +architecture framework is a blueprint that has been proven through decades +of implementations on the last several generations of platforms +(COBOL/Mainframe, C++/Unix, and now Java/anywhere). JCL and COBOL developers +are likely to be as comfortable with the concepts as C++, C# and Java +developers. Spring Batch provides a physical implementation of the layers, +components and technical services commonly found in robust, maintainable +systems used to address the creation of simple to complex batch +applications, with the infrastructure and extensions to address very complex +processing needs. + +.Batch Stereotypes +image::{batch-asciidoc}images/spring-batch-reference-model.png[Figure 2.1: Batch Stereotypes, scaledwidth="60%"] + +The diagram above highlights the key concepts that make up the domain +language of batch. A Job has one to many steps, which has exactly one +`ItemReader`, `ItemProcessor`, and `ItemWriter`. A job needs to be launched +(JobLauncher), and meta data about the currently running process needs to be +stored (JobRepository). + + +=== Job + +This section describes stereotypes relating to the concept of a +batch job. A `Job` is an entity that encapsulates an +entire batch process. As is common with other Spring projects, a +`Job` will be wired together via an XML configuration +file or Java based configuration. This configuration may be referred to as +the "job configuration". However, `Job` is just the +top of an overall hierarchy: + +.Job Hierarchy +image::{batch-asciidoc}images/job-heirarchy.png[Job Hierarchy, scaledwidth="60%"] + +In Spring Batch, a Job is simply a container for Steps. It combines +multiple steps that belong logically together in a flow and allows for +configuration of properties global to all steps, such as restartability. +The job configuration contains: + +* The simple name of the job +* Definition and ordering of Steps +* Whether or not the job is restartable + +A default simple implementation of the Job +interface is provided by Spring Batch in the form of the +`SimpleJob` class which creates some standard +functionality on top of `Job`, however the batch +namespace abstracts away the need to instantiate it directly. Instead, the +`` tag can be used: + +[source, xml] +---- + + + + + +---- + +==== JobInstance + +A `JobInstance` refers to the concept of a +logical job run. Let's consider a batch job that should be run once at +the end of the day, such as the 'EndOfDay' `Job` from the diagram above. +There is one 'EndOfDay' job, but each individual +run of the `Job` must be tracked separately. In the +case of this job, there will be one logical +`JobInstance` per day. For example, there will be a +January 1st run, and a January 2nd run. If the January 1st run fails the +first time and is run again the next day, it is still the January 1st +run. (Usually this corresponds with the data it is processing as well, +meaning the January 1st run processes data for January 1st, etc). +Therefore, each `JobInstance` can have multiple +executions (`JobExecution` is discussed in more +detail below) and only one `JobInstance` +corresponding to a particular `Job` and +identifying `JobParameters` can be running at a given +time. + +The definition of a `JobInstance` has +absolutely no bearing on the data the will be loaded. It is entirely up +to the `ItemReader` implementation used to +determine how data will be loaded. For example, in the EndOfDay +scenario, there may be a column on the data that indicates the +'effective date' or 'schedule date' to which the data belongs. So, the +January 1st run would only load data from the 1st, and the January 2nd +run would only use data from the 2nd. Because this determination will +likely be a business decision, it is left up to the +`ItemReader` to decide. What using the same +`JobInstance` will determine, however, is whether +or not the 'state' (i.e. the `ExecutionContext`, +which is discussed below) from previous executions will be used. Using a +new `JobInstance` will mean 'start from the +beginning' and using an existing instance will generally mean 'start +from where you left off'. + +==== JobParameters + +Having discussed `JobInstance` and how it +differs from Job, the natural question to ask is: +"how is one `JobInstance` distinguished from +another?" The answer is: `JobParameters`. +`JobParameters` is a set of parameters used to +start a batch job. They can be used for identification or even as +reference data during the run: + +.Job Parameters +image::{batch-asciidoc}images/job-stereotypes-parameters.png[Job Parameters, scaledwidth="60%"] + +In the example above, where there are two instances, one for +January 1st, and another for January 2nd, there is really only one Job, +one that was started with a job parameter of 01-01-2017 and another that +was started with a parameter of 01-02-2017. Thus, the contract can be +defined as: `JobInstance` = +`Job` + identifying `JobParameters`. This +allows a developer to effectively control how a +`JobInstance` is defined, since they control what +parameters are passed in. + +NOTE: Not all job parameters are required to contribute to the identification +of a `JobInstance`. By default they do, however the framework +allows the submission of a `Job` with parameters that do +not contribute to the identity of a `JobInstance` as well. + +==== JobExecution + +A `JobExecution` refers to the technical +concept of a single attempt to run a Job. An +execution may end in failure or success, but the +`JobInstance` corresponding to a given execution +will not be considered complete unless the execution completes +successfully. Using the EndOfDay `Job` described +above as an example, consider a `JobInstance` for +01-01-2017 that failed the first time it was run. If it is run again +with the same identifying job parameters as the first run (01-01-2017), a new +`JobExecution` will be created. However, there will +still be only one `JobInstance`. + +A `Job` defines what a job is and how it is +to be executed, and `JobInstance` is a purely +organizational object to group executions together, primarily to enable +correct restart semantics. A `JobExecution`, +however, is the primary storage mechanism for what actually happened +during a run, and as such contains many more properties that must be +controlled and persisted: + + +.JobExecution Properties + +|=== +|Property |Definition +|status +|A `BatchStatus` object that +indicates the status of the execution. While running, it's +BatchStatus.STARTED, if it fails, it's BatchStatus.FAILED, and +if it finishes successfully, it's BatchStatus.COMPLETED + +|startTime +|A `java.util.Date` representing the +current system time when the execution was started. + +|endTime +|A `java.util.Date` representing the +current system time when the execution finished, regardless of +whether or not it was successful. + +|exitStatus +|The `ExitStatus` indicating the +result of the run. It is most important because it contains an +exit code that will be returned to the caller. See chapter 5 for +more details. + +|createTime +|A `java.util.Date` representing the +current system time when the `JobExecution` +was first persisted. The job may not have been started yet (and +thus has no start time), but it will always have a createTime, +which is required by the framework for managing job level +`ExecutionContexts`. + +|lastUpdated +|A `java.util.Date` representing the +last time a `JobExecution` was +persisted. + +|executionContext +|The 'property bag' containing any user data that needs to +be persisted between executions. + +|failureExceptions +|The list of exceptions encountered during the execution +of a Job. These can be useful if more +than one exception is encountered during the failure of a +Job. +|=== + +These properties are important because they will be persisted and +can be used to completely determine the status of an execution. For +example, if the EndOfDay job for 01-01 is executed at 9:00 PM, and fails +at 9:30, the following entries will be made in the batch meta data +tables: + +.BATCH_JOB_INSTANCE + +|=== +|JOB_INST_ID |JOB_NAME +|1 +|EndOfDayJob +|=== + +.BATCH_JOB_EXECUTION_PARAMS +|=== +|JOB_EXECUTION_ID|TYPE_CD|KEY_NAME|DATE_VAL|IDENTIFYING +|1 +|DATE +|schedule.Date +|2017-01-01 +|TRUE +|=== + +.BATCH_JOB_EXECUTION +|=== +|JOB_EXEC_ID|JOB_INST_ID|START_TIME|END_TIME|STATUS +|1 +|1 +|2017-01-01 21:00 +|2017-01-01 21:30 +|FAILED +|=== + +NOTE: column names may have been abbreviated or removed for clarity +and formatting + + +Now that the job has failed, let's assume that it took the entire +course of the night for the problem to be determined, so that the 'batch +window' is now closed. Assuming the window starts at 9:00 PM, the job +will be kicked off again for 01-01, starting where it left off and +completing successfully at 9:30. Because it's now the next day, the +01-02 job must be run as well, which is kicked off just afterwards at +9:31, and completes in its normal one hour time at 10:30. There is no +requirement that one `JobInstance` be kicked off +after another, unless there is potential for the two jobs to attempt to +access the same data, causing issues with locking at the database level. +It is entirely up to the scheduler to determine when a +Job should be run. Since they're separate +`JobInstances`, Spring Batch will make no attempt +to stop them from being run concurrently. (Attempting to run the same +`JobInstance` while another is already running will +result in a `JobExecutionAlreadyRunningException` +being thrown). There should now be an extra entry in both the +`JobInstance` and +`JobParameters` tables, and two extra entries in +the `JobExecution` table: + +.BATCH_JOB_INSTANCE +|=== +|JOB_INST_ID |JOB_NAME +|1 +|EndOfDayJob + +|2 +|EndOfDayJob +|=== + + + + + +.BATCH_JOB_EXECUTION_PARAMS +|=== +|JOB_EXECUTION_ID|TYPE_CD|KEY_NAME|DATE_VAL|IDENTIFYING +|1 +|DATE +|schedule.Date +|2017-01-01 00:00:00 +|TRUE + +|2 +|DATE +|schedule.Date +|2017-01-01 00:00:00 +|TRUE + +|3 +|DATE +|schedule.Date +|2017-01-02 00:00:00 +|TRUE +|=== + +.BATCH_JOB_EXECUTION +|=== +|JOB_EXEC_ID|JOB_INST_ID|START_TIME|END_TIME|STATUS +|1 +|1 +|2017-01-01 21:00 +|2017-01-01 21:30 +|FAILED + +|2 +|1 +|2017-01-02 21:00 +|2017-01-02 21:30 +|COMPLETED + +|3 +|2 +|2017-01-02 21:31 +|2017-01-02 22:29 +|COMPLETED +|=== + +NOTE: column names may have been abbreviated or removed for clarity +and formatting + +=== Step + +A `Step` is a domain object that encapsulates +an independent, sequential phase of a batch job. Therefore, every +Job is composed entirely of one or more steps. A +`Step` contains all of the information necessary to +define and control the actual batch processing. This is a necessarily +vague description because the contents of any given +`Step` are at the discretion of the developer writing +a `Job`. A `Step` can be as simple or complex as the +developer desires. A simple `Step` might load data +from a file into the database, requiring little or no code. (depending +upon the implementations used) A more complex `Step` +may have complicated business rules that are applied as part of the +processing. As with `Job`, a +`Step` has an individual +`StepExecution` that corresponds with a unique +`JobExecution`: + +.Job Hierarchy With Steps +image::{batch-asciidoc}images/jobHeirarchyWithSteps.png[Figure 2.1: Job Hierarchy With Steps, scaledwidth="60%"] + + + +==== StepExecution + +A `StepExecution` represents a single attempt +to execute a `Step`. A new +`StepExecution` will be created each time a +`Step` is run, similar to +`JobExecution`. However, if a step fails to execute +because the step before it fails, there will be no execution persisted +for it. A `StepExecution` will only be created when +its `Step` is actually started. + +`Step` executions are represented by objects of the +`StepExecution` class. Each execution contains a +reference to its corresponding step and +`JobExecution`, and transaction related data such +as commit and rollback count and start and end times. Additionally, each +step execution will contain an `ExecutionContext`, +which contains any data a developer needs persisted across batch runs, +such as statistics or state information needed to restart. The following +is a listing of the properties for +StepExecution: + +.StepExecution Properties +|=== +|Property|Definition +|status +|A `BatchStatus` object that +indicates the status of the execution. While it's running, the +status is BatchStatus.STARTED, if it fails, the status is +BatchStatus.FAILED, and if it finishes successfully, the status +is BatchStatus.COMPLETED + +|startTime +|A `java.util.Date` representing the +current system time when the execution was started. + +|endTime + +|A `java.util.Date` representing the +current system time when the execution finished, regardless of +whether or not it was successful. + +|exitStatus +|The `ExitStatus` indicating the +result of the execution. It is most important because it +contains an exit code that will be returned to the caller. See +chapter 5 for more details. + +|executionContext +|The 'property bag' containing any user data that needs to +be persisted between executions. + +|readCount +|The number of items that have been successfully +read + +|writeCount +|The number of items that have been successfully +written + +|commitCount +|The number transactions that have been committed for this +execution + +|rollbackCount +|The number of times the business transaction controlled +by the `Step` has been rolled back. + +|readSkipCount +|The number of times `read` has +failed, resulting in a skipped item. + +|processSkipCount +|The number of times `process` has +failed, resulting in a skipped item. + +|filterCount +|The number of items that have been 'filtered' by the +`ItemProcessor`. + +|writeSkipCount +|The number of times `write` has +failed, resulting in a skipped item. +|=== + +=== ExecutionContext + +An `ExecutionContext` represents a collection +of key/value pairs that are persisted and controlled by the framework in +order to allow developers a place to store persistent state that is scoped +to a `StepExecution` or +`JobExecution`. For those familiar with Quartz, it is +very similar to JobDataMap. The best usage example +is to facilitate restart. Using flat file input as an example, while +processing individual lines, the framework periodically persists the +`ExecutionContext` at commit points. This allows the +`ItemReader` to store its state in case a fatal error +occurs during the run, or even if the power goes out. All that is needed +is to put the current number of lines read into the context, and the +framework will do the rest: + +[source, java] +---- +executionContext.putLong(getKey(LINES_READ_COUNT), reader.getPosition()); +---- + +Using the EndOfDay example from the `Job` Stereotypes section as an +example, assume there's one step: 'loadData', that loads a file into the +database. After the first failed run, the meta data tables would look like +the following: + +.BATCH_JOB_INSTANCE +|=== +|JOB_INST_ID|JOB_NAME +|1 +|EndOfDayJob +|=== + +.BATCH_JOB_PARAMS +|=== +|JOB_INST_ID|TYPE_CD|KEY_NAME|DATE_VAL +|1 +|DATE +|schedule.Date +|2017-01-01 +|=== + +.BATCH_JOB_EXECUTION +|=== +|JOB_EXEC_ID|JOB_INST_ID|START_TIME|END_TIME|STATUS +|1 +|1 +|2017-01-01 21:00 +|2017-01-01 21:30 +|FAILED +|=== + +.BATCH_STEP_EXECUTION +|=== +|STEP_EXEC_ID|JOB_EXEC_ID|STEP_NAME|START_TIME|END_TIME|STATUS +|1 +|1 +|loadData +|2017-01-01 21:00 +|2017-01-01 21:30 +|FAILED +|=== + +.BATCH_STEP_EXECUTION_CONTEXT +|=== +|STEP_EXEC_ID|SHORT_CONTEXT +|1 +|{piece.count=40321} +|=== + + +In this case, the `Step` ran for 30 minutes +and processed 40,321 'pieces', which would represent lines in a file in +this scenario. This value will be updated just before each commit by the +framework, and can contain multiple rows corresponding to entries within +the `ExecutionContext`. Being notified before a +commit requires one of the various StepListeners, +or an ItemStream, which are discussed in more +detail later in this guide. As with the previous example, it is assumed +that the `Job` is restarted the next day. When it is +restarted, the values from the `ExecutionContext` of +the last run are reconstituted from the database, and when the +`ItemReader` is opened, it can check to see if it has +any stored state in the context, and initialize itself from there: + +[source, java] +---- +if (executionContext.containsKey(getKey(LINES_READ_COUNT))) { + log.debug("Initializing for restart. Restart data is: " + executionContext); + + long lineCount = executionContext.getLong(getKey(LINES_READ_COUNT)); + + LineReader reader = getReader(); + + Object record = ""; + while (reader.getPosition() < lineCount && record != null) { + record = readLine(); + } +} +---- +In this case, after the above code is executed, the current line +will be 40,322, allowing the `Step` to start again +from where it left off. The `ExecutionContext` can +also be used for statistics that need to be persisted about the run +itself. For example, if a flat file contains orders for processing that +exist across multiple lines, it may be necessary to store how many orders +have been processed (which is much different from than the number of lines +read) so that an email can be sent at the end of the +`Step` with the total orders processed in the body. +The framework handles storing this for the developer, in order to +correctly scope it with an individual `JobInstance`. +It can be very difficult to know whether an existing +`ExecutionContext` should be used or not. For +example, using the 'EndOfDay' example from above, when the 01-01 run +starts again for the second time, the framework recognizes that it is the +same `JobInstance` and on an individual +`Step` basis, pulls the +`ExecutionContext` out of the database and hands it +as part of the `StepExecution` to the +`Step` itself. Conversely, for the 01-02 run the +framework recognizes that it is a different instance, so an empty context +must be handed to the `Step`. There are many of these +types of determinations that the framework makes for the developer to +ensure the state is given to them at the correct time. It is also +important to note that exactly one `ExecutionContext` +exists per `StepExecution` at any given time. Clients +of the `ExecutionContext` should be careful because +this creates a shared keyspace, so care should be taken when putting +values in to ensure no data is overwritten. However, the +`Step` stores absolutely no data in the context, so +there is no way to adversely affect the framework. + +It is also important to note that there is at least one +`ExecutionContext` per +`JobExecution`, and one for every +StepExecution. For example, consider the following +code snippet: + +[source, java] +---- +ExecutionContext ecStep = stepExecution.getExecutionContext(); +ExecutionContext ecJob = jobExecution.getExecutionContext(); +//ecStep does not equal ecJob +---- + +As noted in the comment, ecStep will not equal ecJob; they are two +different `ExecutionContexts`. The one scoped to the +`Step` will be saved at every commit point in the +`Step`, whereas the one scoped to the +Job will be saved in between every +`Step` execution. + +=== JobRepository + +`JobRepository` is the persistence mechanism +for all of the Stereotypes mentioned above. It provides CRUD operations +for `JobLauncher`, `Job`, and +`Step` implementations. When a +Job is first launched, a +`JobExecution` is obtained from the repository, and +during the course of execution `StepExecution` and +`JobExecution` implementations are persisted by +passing them to the repository: + +[source, xml] +---- + +---- + +=== JobLauncher + +`JobLauncher` represents a simple interface for +launching a `Job` with a given set of +`JobParameters`: + +[source, java] +---- +public interface JobLauncher { + +public JobExecution run(Job job, JobParameters jobParameters) + throws JobExecutionAlreadyRunningException, JobRestartException; +} +---- +It is expected that implementations will obtain a valid +`JobExecution` from the +`JobRepository` and execute the +`Job`. + +=== Item Reader + +`ItemReader` is an abstraction that represents +the retrieval of input for a `Step`, one item at a +time. When the `ItemReader` has exhausted the items +it can provide, it will indicate this by returning null. More details +about the `ItemReader` interface and its various +implementations can be found in <>. + +=== Item Writer + +`ItemWriter` is an abstraction that +represents the output of a `Step`, one batch +or chunk of items at a time. Generally, an `ItemWriter` has no +knowledge of the input it will receive next, only the item that +was passed in its current invocation. More details about the +`ItemWriter` interface and its various +implementations can be found in <>. + +=== Item Processor + +`ItemProcessor` is an abstraction that +represents the business processing of an item. While the +`ItemReader` reads one item, and the +`ItemWriter` writes them, the +`ItemProcessor` provides access to transform or apply +other business processing. If, while processing the item, it is determined +that the item is not valid, returning null indicates that the item should +not be written out. More details about the `ItemProcessor` interface can be +found in <>. + + +=== Batch Namespace + +Many of the domain concepts listed above need to be configured in a +Spring ApplicationContext. While there are +implementations of the interfaces above that can be used in a standard +bean definition, a namespace has been provided for ease of +configuration: + +[source, xml] +---- + + + + + + + + + + + +---- + +As long as the batch namespace has been declared, any of its +elements can be used. More information on configuring a +Job can be found in <>. More information on configuring a `Step` can be +found in <>. + diff --git a/spring-batch-docs/asciidoc/glossary.adoc b/spring-batch-docs/asciidoc/glossary.adoc new file mode 100644 index 000000000..77ecd1beb --- /dev/null +++ b/spring-batch-docs/asciidoc/glossary.adoc @@ -0,0 +1,119 @@ +[[glossary]] +[appendix] +== Glossary +[glossary] +=== Spring Batch Glossary + +Batch:: + An accumulation of business transactions over time. + +Batch Application Style:: + Term used to designate batch as an application style in its own + right similar to online, Web or SOA. It has standard elements of + input, validation, transformation of information to business model, + business processing and output. In addition, it requires monitoring at + a macro level. + +Batch Processing:: + The handling of a batch of many business transactions that have + accumulated over a period of time (e.g. an hour, day, week, month, or + year). It is the application of a process, or set of processes, to + many data entities or objects in a repetitive and predictable fashion + with either no manual element, or a separate manual element for error + processing. + +Batch Window:: + The time frame within which a batch job must complete. This can + be constrained by other systems coming online, other dependent jobs + needing to execute or other factors specific to the batch + environment. + +Step:: + It is the main batch task or unit of work controller. It + initializes the business logic, and controls the transaction + environment based on commit interval setting, etc. + +Tasklet:: + A component created by application developer to process the + business logic for a Step. + +Batch Job Type:: + Job Types describe application of jobs for particular type of + processing. Common areas are interface processing (typically flat + files), forms processing (either for online pdf generation or print + formats), report processing. + +Driving Query:: + A driving query identifies the set of work for a job to do; the + job then breaks that work into individual units of work. For instance, + identify all financial transactions that have a status of "pending + transmission" and send them to our partner system. The driving query + returns a set of record IDs to process; each record ID then becomes a + unit of work. A driving query may involve a join (if the criteria for + selection falls across two or more tables) or it may work with a + single table. + +Item:: + An item represents the smallest ammount of complete data for + processing. In the simplest terms, this might mean a line in a file, a + row in a database table, or a particular element in an XML + file. + +Logicial Unit of Work (LUW):: + A batch job iterates through a driving query (or another input + source such as a file) to perform the set of work that the job must + accomplish. Each iteration of work performed is a unit of work. + +Commit Interval:: + A set of LUWs processed within a single transaction. + +Partitioning:: + Splitting a job into multiple threads where each thread is + responsible for a subset of the overall data to be processed. The + threads of execution may be within the same JVM or they may span JVMs + in a clustered environment that supports workload balancing. + +Staging Table:: + A table that holds temporary data while it is being + processed. + +Restartable:: + A job that can be executed again and will assume the same + identity as when run initially. In othewords, it is has the same job + instance id. + +Rerunnable:: + A job that is restartable and manages its own state in terms of + previous run's record processing. An example of a rerunnable step is + one based on a driving query. If the driving query can be formed so + that it will limit the processed rows when the job is restarted than + it is re-runnable. This is managed by the application logic. Often + times a condition is added to the where statement to limit the rows + returned by the driving query with something like "and processedFlag + != true". + +Repeat:: + One of the most basic units of batch processing, that defines + repeatability calling a portion of code until it is finished, and + while there is no error. Typically a batch process would be repeatable + as long as there is input. + +Retry:: + Simplifies the execution of operations with retry semantics most + frequently associated with handling transactional output exceptions. + Retry is slightly different from repeat, rather than continually + calling a block of code, retry is stateful, and continually calls the + same block of code with the same input, until it either succeeds, or + some type of retry limit has been exceeded. It is only generally + useful if a subsequent invocation of the operation might succeed + because something in the environment has improved. + +Recover:: + Recover operations handle an exception in such a way that a + repeat process is able to continue. + +Skip:: + Skip is a recovery strategy often used on file input sources as + the strategy for ignoring bad input records that failed + validation. + diff --git a/spring-batch-docs/asciidoc/header/index-header.adoc b/spring-batch-docs/asciidoc/header/index-header.adoc new file mode 100644 index 000000000..3ebf05f8e --- /dev/null +++ b/spring-batch-docs/asciidoc/header/index-header.adoc @@ -0,0 +1,12 @@ += Spring Batch - Reference Documentation + +Lucas Ward, Dave Syer, Thomas Risberg, Robert Kasanicky, Dan Garrette, Wayne Lund, Michael Minella, Chris Schaefer, Gunnar Hillert, Glenn Renfro + +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ + +Copyright © 2009, 2010, 2011, 2012, 2013, 2014, 201, 2016, 2017 Pivotal, Inc. All Rights Reserved. + +Copies of this document may be made for your own use and for +distribution to others, provided that you do not charge any fee for such +copies and further provided that each copy contains this Copyright +Notice, whether distributed in print or electronically. \ No newline at end of file diff --git a/src/site/docbook/reference/images/1-1-step.png b/spring-batch-docs/asciidoc/images/1-1-step.png similarity index 100% rename from src/site/docbook/reference/images/1-1-step.png rename to spring-batch-docs/asciidoc/images/1-1-step.png diff --git a/src/site/docbook/reference/images/BatchExecutionEnvironments.bmp b/spring-batch-docs/asciidoc/images/BatchExecutionEnvironments.bmp similarity index 100% rename from src/site/docbook/reference/images/BatchExecutionEnvironments.bmp rename to spring-batch-docs/asciidoc/images/BatchExecutionEnvironments.bmp diff --git a/src/site/docbook/reference/images/ExecutionEnvironment.png b/spring-batch-docs/asciidoc/images/ExecutionEnvironment.png similarity index 100% rename from src/site/docbook/reference/images/ExecutionEnvironment.png rename to spring-batch-docs/asciidoc/images/ExecutionEnvironment.png diff --git a/src/site/docbook/reference/images/PipeAndFilter.jpg b/spring-batch-docs/asciidoc/images/PipeAndFilter.jpg similarity index 100% rename from src/site/docbook/reference/images/PipeAndFilter.jpg rename to spring-batch-docs/asciidoc/images/PipeAndFilter.jpg diff --git a/src/site/docbook/reference/images/PipeAndFilter.png b/spring-batch-docs/asciidoc/images/PipeAndFilter.png similarity index 100% rename from src/site/docbook/reference/images/PipeAndFilter.png rename to spring-batch-docs/asciidoc/images/PipeAndFilter.png diff --git a/src/site/docbook/reference/images/RepeatTemplate.png b/spring-batch-docs/asciidoc/images/RepeatTemplate.png similarity index 100% rename from src/site/docbook/reference/images/RepeatTemplate.png rename to spring-batch-docs/asciidoc/images/RepeatTemplate.png diff --git a/src/site/docbook/reference/images/RuntimeDependencies.png b/spring-batch-docs/asciidoc/images/RuntimeDependencies.png similarity index 100% rename from src/site/docbook/reference/images/RuntimeDependencies.png rename to spring-batch-docs/asciidoc/images/RuntimeDependencies.png diff --git a/src/site/docbook/reference/images/application-tier.png b/spring-batch-docs/asciidoc/images/application-tier.png similarity index 100% rename from src/site/docbook/reference/images/application-tier.png rename to spring-batch-docs/asciidoc/images/application-tier.png diff --git a/src/site/docbook/reference/images/chunk-oriented-processing.png b/spring-batch-docs/asciidoc/images/chunk-oriented-processing.png similarity index 100% rename from src/site/docbook/reference/images/chunk-oriented-processing.png rename to spring-batch-docs/asciidoc/images/chunk-oriented-processing.png diff --git a/src/site/docbook/reference/images/composite-transformer.png b/spring-batch-docs/asciidoc/images/composite-transformer.png similarity index 100% rename from src/site/docbook/reference/images/composite-transformer.png rename to spring-batch-docs/asciidoc/images/composite-transformer.png diff --git a/src/site/docbook/reference/images/conditional-flow.png b/spring-batch-docs/asciidoc/images/conditional-flow.png similarity index 100% rename from src/site/docbook/reference/images/conditional-flow.png rename to spring-batch-docs/asciidoc/images/conditional-flow.png diff --git a/src/site/docbook/reference/images/cursorExample.png b/spring-batch-docs/asciidoc/images/cursorExample.png similarity index 100% rename from src/site/docbook/reference/images/cursorExample.png rename to spring-batch-docs/asciidoc/images/cursorExample.png diff --git a/src/site/docbook/reference/images/domain-classdiagram.jpg b/spring-batch-docs/asciidoc/images/domain-classdiagram.jpg similarity index 100% rename from src/site/docbook/reference/images/domain-classdiagram.jpg rename to spring-batch-docs/asciidoc/images/domain-classdiagram.jpg diff --git a/src/site/docbook/reference/images/drivingQueryExample.png b/spring-batch-docs/asciidoc/images/drivingQueryExample.png similarity index 100% rename from src/site/docbook/reference/images/drivingQueryExample.png rename to spring-batch-docs/asciidoc/images/drivingQueryExample.png diff --git a/src/site/docbook/reference/images/drivingQueryJob.png b/spring-batch-docs/asciidoc/images/drivingQueryJob.png similarity index 100% rename from src/site/docbook/reference/images/drivingQueryJob.png rename to spring-batch-docs/asciidoc/images/drivingQueryJob.png diff --git a/src/site/docbook/reference/images/errorOnFlush.png b/spring-batch-docs/asciidoc/images/errorOnFlush.png similarity index 100% rename from src/site/docbook/reference/images/errorOnFlush.png rename to spring-batch-docs/asciidoc/images/errorOnFlush.png diff --git a/src/site/docbook/reference/images/errorOnWrite.png b/spring-batch-docs/asciidoc/images/errorOnWrite.png similarity index 100% rename from src/site/docbook/reference/images/errorOnWrite.png rename to spring-batch-docs/asciidoc/images/errorOnWrite.png diff --git a/src/site/docbook/reference/images/execution-environment-config.jpg b/spring-batch-docs/asciidoc/images/execution-environment-config.jpg similarity index 100% rename from src/site/docbook/reference/images/execution-environment-config.jpg rename to spring-batch-docs/asciidoc/images/execution-environment-config.jpg diff --git a/src/site/docbook/reference/images/flat-file-input-source-design.gif b/spring-batch-docs/asciidoc/images/flat-file-input-source-design.gif similarity index 100% rename from src/site/docbook/reference/images/flat-file-input-source-design.gif rename to spring-batch-docs/asciidoc/images/flat-file-input-source-design.gif diff --git a/src/site/docbook/reference/images/flat-file-input-source-design.jpg b/spring-batch-docs/asciidoc/images/flat-file-input-source-design.jpg similarity index 100% rename from src/site/docbook/reference/images/flat-file-input-source-design.jpg rename to spring-batch-docs/asciidoc/images/flat-file-input-source-design.jpg diff --git a/src/site/docbook/reference/images/flatfile-input-source-diagram.jpg b/spring-batch-docs/asciidoc/images/flatfile-input-source-diagram.jpg similarity index 100% rename from src/site/docbook/reference/images/flatfile-input-source-diagram.jpg rename to spring-batch-docs/asciidoc/images/flatfile-input-source-diagram.jpg diff --git a/src/site/docbook/reference/images/handling-informational-messages.png b/spring-batch-docs/asciidoc/images/handling-informational-messages.png similarity index 100% rename from src/site/docbook/reference/images/handling-informational-messages.png rename to spring-batch-docs/asciidoc/images/handling-informational-messages.png diff --git a/src/site/docbook/reference/images/io-design.jpg b/spring-batch-docs/asciidoc/images/io-design.jpg similarity index 100% rename from src/site/docbook/reference/images/io-design.jpg rename to spring-batch-docs/asciidoc/images/io-design.jpg diff --git a/src/site/docbook/reference/images/item-oriented-processing.png b/spring-batch-docs/asciidoc/images/item-oriented-processing.png similarity index 100% rename from src/site/docbook/reference/images/item-oriented-processing.png rename to spring-batch-docs/asciidoc/images/item-oriented-processing.png diff --git a/src/site/docbook/reference/images/item-reader-design.jpg b/spring-batch-docs/asciidoc/images/item-reader-design.jpg similarity index 100% rename from src/site/docbook/reference/images/item-reader-design.jpg rename to spring-batch-docs/asciidoc/images/item-reader-design.jpg diff --git a/src/site/docbook/reference/images/item-stream-adapter.jpg b/spring-batch-docs/asciidoc/images/item-stream-adapter.jpg similarity index 100% rename from src/site/docbook/reference/images/item-stream-adapter.jpg rename to spring-batch-docs/asciidoc/images/item-stream-adapter.jpg diff --git a/src/site/docbook/reference/images/jmx-job.jpg b/spring-batch-docs/asciidoc/images/jmx-job.jpg similarity index 100% rename from src/site/docbook/reference/images/jmx-job.jpg rename to spring-batch-docs/asciidoc/images/jmx-job.jpg diff --git a/src/site/docbook/reference/images/jmx.jpg b/spring-batch-docs/asciidoc/images/jmx.jpg similarity index 100% rename from src/site/docbook/reference/images/jmx.jpg rename to spring-batch-docs/asciidoc/images/jmx.jpg diff --git a/src/site/docbook/reference/images/job-heirarchy.png b/spring-batch-docs/asciidoc/images/job-heirarchy.png similarity index 100% rename from src/site/docbook/reference/images/job-heirarchy.png rename to spring-batch-docs/asciidoc/images/job-heirarchy.png diff --git a/src/site/docbook/reference/images/job-launcher-sequence-async.png b/spring-batch-docs/asciidoc/images/job-launcher-sequence-async.png similarity index 100% rename from src/site/docbook/reference/images/job-launcher-sequence-async.png rename to spring-batch-docs/asciidoc/images/job-launcher-sequence-async.png diff --git a/src/site/docbook/reference/images/job-launcher-sequence-sync.png b/spring-batch-docs/asciidoc/images/job-launcher-sequence-sync.png similarity index 100% rename from src/site/docbook/reference/images/job-launcher-sequence-sync.png rename to spring-batch-docs/asciidoc/images/job-launcher-sequence-sync.png diff --git a/src/site/docbook/reference/images/job-repository-advanced.png b/spring-batch-docs/asciidoc/images/job-repository-advanced.png similarity index 100% rename from src/site/docbook/reference/images/job-repository-advanced.png rename to spring-batch-docs/asciidoc/images/job-repository-advanced.png diff --git a/src/site/docbook/reference/images/job-repository.png b/spring-batch-docs/asciidoc/images/job-repository.png similarity index 100% rename from src/site/docbook/reference/images/job-repository.png rename to spring-batch-docs/asciidoc/images/job-repository.png diff --git a/src/site/docbook/reference/images/job-stereotypes-parameters.png b/spring-batch-docs/asciidoc/images/job-stereotypes-parameters.png similarity index 100% rename from src/site/docbook/reference/images/job-stereotypes-parameters.png rename to spring-batch-docs/asciidoc/images/job-stereotypes-parameters.png diff --git a/src/site/docbook/reference/images/jobHeirarchyWithSteps.png b/spring-batch-docs/asciidoc/images/jobHeirarchyWithSteps.png similarity index 100% rename from src/site/docbook/reference/images/jobHeirarchyWithSteps.png rename to spring-batch-docs/asciidoc/images/jobHeirarchyWithSteps.png diff --git a/src/site/docbook/reference/images/jobTier.png b/spring-batch-docs/asciidoc/images/jobTier.png similarity index 100% rename from src/site/docbook/reference/images/jobTier.png rename to spring-batch-docs/asciidoc/images/jobTier.png diff --git a/src/site/docbook/reference/images/launch-batch-job-svg.svg b/spring-batch-docs/asciidoc/images/launch-batch-job-svg.svg similarity index 100% rename from src/site/docbook/reference/images/launch-batch-job-svg.svg rename to spring-batch-docs/asciidoc/images/launch-batch-job-svg.svg diff --git a/src/site/docbook/reference/images/launch-batch-job.png b/spring-batch-docs/asciidoc/images/launch-batch-job.png similarity index 100% rename from src/site/docbook/reference/images/launch-batch-job.png rename to spring-batch-docs/asciidoc/images/launch-batch-job.png diff --git a/src/site/docbook/reference/images/launch-from-request.png b/spring-batch-docs/asciidoc/images/launch-from-request.png similarity index 100% rename from src/site/docbook/reference/images/launch-from-request.png rename to spring-batch-docs/asciidoc/images/launch-from-request.png diff --git a/src/site/docbook/reference/images/meta-data-erd.png b/spring-batch-docs/asciidoc/images/meta-data-erd.png similarity index 100% rename from src/site/docbook/reference/images/meta-data-erd.png rename to spring-batch-docs/asciidoc/images/meta-data-erd.png diff --git a/src/site/docbook/reference/images/nfljob-config.jpg b/spring-batch-docs/asciidoc/images/nfljob-config.jpg similarity index 100% rename from src/site/docbook/reference/images/nfljob-config.jpg rename to spring-batch-docs/asciidoc/images/nfljob-config.jpg diff --git a/src/site/docbook/reference/images/nfljob.jpg b/spring-batch-docs/asciidoc/images/nfljob.jpg similarity index 100% rename from src/site/docbook/reference/images/nfljob.jpg rename to spring-batch-docs/asciidoc/images/nfljob.jpg diff --git a/src/site/docbook/reference/images/oxm-fragments.png b/spring-batch-docs/asciidoc/images/oxm-fragments.png similarity index 100% rename from src/site/docbook/reference/images/oxm-fragments.png rename to spring-batch-docs/asciidoc/images/oxm-fragments.png diff --git a/src/site/docbook/reference/images/partitioned.png b/spring-batch-docs/asciidoc/images/partitioned.png similarity index 100% rename from src/site/docbook/reference/images/partitioned.png rename to spring-batch-docs/asciidoc/images/partitioned.png diff --git a/src/site/docbook/reference/images/partitioning-overview.png b/spring-batch-docs/asciidoc/images/partitioning-overview.png similarity index 100% rename from src/site/docbook/reference/images/partitioning-overview.png rename to spring-batch-docs/asciidoc/images/partitioning-overview.png diff --git a/src/site/docbook/reference/images/partitioning-spi.png b/spring-batch-docs/asciidoc/images/partitioning-spi.png similarity index 100% rename from src/site/docbook/reference/images/partitioning-spi.png rename to spring-batch-docs/asciidoc/images/partitioning-spi.png diff --git a/src/site/docbook/reference/images/remote-chunking-sbi.png b/spring-batch-docs/asciidoc/images/remote-chunking-sbi.png similarity index 100% rename from src/site/docbook/reference/images/remote-chunking-sbi.png rename to spring-batch-docs/asciidoc/images/remote-chunking-sbi.png diff --git a/src/site/docbook/reference/images/remote-chunking.png b/spring-batch-docs/asciidoc/images/remote-chunking.png similarity index 100% rename from src/site/docbook/reference/images/remote-chunking.png rename to spring-batch-docs/asciidoc/images/remote-chunking.png diff --git a/src/site/docbook/reference/images/remote-partitioning.png b/spring-batch-docs/asciidoc/images/remote-partitioning.png similarity index 100% rename from src/site/docbook/reference/images/remote-partitioning.png rename to spring-batch-docs/asciidoc/images/remote-partitioning.png diff --git a/src/site/docbook/reference/images/repository-classdiagram.jpg b/spring-batch-docs/asciidoc/images/repository-classdiagram.jpg similarity index 100% rename from src/site/docbook/reference/images/repository-classdiagram.jpg rename to spring-batch-docs/asciidoc/images/repository-classdiagram.jpg diff --git a/src/site/docbook/reference/images/run-tier.png b/spring-batch-docs/asciidoc/images/run-tier.png similarity index 100% rename from src/site/docbook/reference/images/run-tier.png rename to spring-batch-docs/asciidoc/images/run-tier.png diff --git a/src/site/docbook/reference/images/s1-job-configuration.jpg b/spring-batch-docs/asciidoc/images/s1-job-configuration.jpg similarity index 100% rename from src/site/docbook/reference/images/s1-job-configuration.jpg rename to spring-batch-docs/asciidoc/images/s1-job-configuration.jpg diff --git a/src/site/docbook/reference/images/sequential-flow.png b/spring-batch-docs/asciidoc/images/sequential-flow.png similarity index 100% rename from src/site/docbook/reference/images/sequential-flow.png rename to spring-batch-docs/asciidoc/images/sequential-flow.png diff --git a/src/site/docbook/reference/images/simple-batch-execution-env.jpg b/spring-batch-docs/asciidoc/images/simple-batch-execution-env.jpg similarity index 100% rename from src/site/docbook/reference/images/simple-batch-execution-env.jpg rename to spring-batch-docs/asciidoc/images/simple-batch-execution-env.jpg diff --git a/src/site/docbook/reference/images/simple-tasklet-job-configuration.jpg b/spring-batch-docs/asciidoc/images/simple-tasklet-job-configuration.jpg similarity index 100% rename from src/site/docbook/reference/images/simple-tasklet-job-configuration.jpg rename to spring-batch-docs/asciidoc/images/simple-tasklet-job-configuration.jpg diff --git a/src/site/docbook/reference/images/simplified-chunk-oriented-processing.png b/spring-batch-docs/asciidoc/images/simplified-chunk-oriented-processing.png similarity index 100% rename from src/site/docbook/reference/images/simplified-chunk-oriented-processing.png rename to spring-batch-docs/asciidoc/images/simplified-chunk-oriented-processing.png diff --git a/src/site/docbook/reference/images/spring-batch-football-graph.jpg b/spring-batch-docs/asciidoc/images/spring-batch-football-graph.jpg similarity index 100% rename from src/site/docbook/reference/images/spring-batch-football-graph.jpg rename to spring-batch-docs/asciidoc/images/spring-batch-football-graph.jpg diff --git a/src/site/docbook/reference/images/spring-batch-layers.png b/spring-batch-docs/asciidoc/images/spring-batch-layers.png similarity index 100% rename from src/site/docbook/reference/images/spring-batch-layers.png rename to spring-batch-docs/asciidoc/images/spring-batch-layers.png diff --git a/src/site/docbook/reference/images/spring-batch-reference-model.png b/spring-batch-docs/asciidoc/images/spring-batch-reference-model.png similarity index 100% rename from src/site/docbook/reference/images/spring-batch-reference-model.png rename to spring-batch-docs/asciidoc/images/spring-batch-reference-model.png diff --git a/src/site/docbook/reference/images/step.png b/spring-batch-docs/asciidoc/images/step.png similarity index 100% rename from src/site/docbook/reference/images/step.png rename to spring-batch-docs/asciidoc/images/step.png diff --git a/src/site/docbook/reference/images/xmlinput.png b/spring-batch-docs/asciidoc/images/xmlinput.png similarity index 100% rename from src/site/docbook/reference/images/xmlinput.png rename to spring-batch-docs/asciidoc/images/xmlinput.png diff --git a/spring-batch-docs/asciidoc/index-pdf.adoc b/spring-batch-docs/asciidoc/index-pdf.adoc new file mode 100644 index 000000000..8cc69698d --- /dev/null +++ b/spring-batch-docs/asciidoc/index-pdf.adoc @@ -0,0 +1,39 @@ +:doctype: book +:toc: +:toclevels: 4 + +include::header/index-header.adoc[] + +include::spring-batch-intro.adoc[] + +include::whatsnew.adoc[] + +include::domain.adoc[] + +include::job.adoc[] + +include::step.adoc[] + +include::readersAndWriters.adoc[] + +include::scalability.adoc[] + +include::repeat.adoc[] + +include::retry.adoc[] + +include::testing.adoc[] + +include::common-patterns.adoc[] + +include::jsr-352.adoc[] + +include::spring-batch-integration.adoc[] + +include::appendix.adoc[] + +include::schema-appendix.adoc[] + +include::transaction-appendix.adoc[] + +include::glossary.adoc[] \ No newline at end of file diff --git a/spring-batch-docs/asciidoc/index-single.adoc b/spring-batch-docs/asciidoc/index-single.adoc new file mode 100644 index 000000000..4a75be4fc --- /dev/null +++ b/spring-batch-docs/asciidoc/index-single.adoc @@ -0,0 +1,39 @@ +:doctype: book +:toc: left +:toclevels: 4 + +include::header/index-header.adoc[] + +include::spring-batch-intro.adoc[] + +include::whatsnew.adoc[] + +include::domain.adoc[] + +include::job.adoc[] + +include::step.adoc[] + +include::readersAndWriters.adoc[] + +include::scalability.adoc[] + +include::repeat.adoc[] + +include::retry.adoc[] + +include::testing.adoc[] + +include::common-patterns.adoc[] + +include::jsr-352.adoc[] + +include::spring-batch-integration.adoc[] + +include::appendix.adoc[] + +include::schema-appendix.adoc[] + +include::transaction-appendix.adoc[] + +include::glossary.adoc[] \ No newline at end of file diff --git a/spring-batch-docs/asciidoc/index.adoc b/spring-batch-docs/asciidoc/index.adoc new file mode 100644 index 000000000..016094b60 --- /dev/null +++ b/spring-batch-docs/asciidoc/index.adoc @@ -0,0 +1,39 @@ +include::header/index-header.adoc[] + +// ====================================================================================== + +* <> + +* <> + +* <> + +* <> + +* <> + +* <> + +* <> + +* <> + +* <> + +* <> + +* <> + +* <> + +* <> + +[big maroon]#Appendix# + +* <> + +* <> + +* <> + +* <> diff --git a/spring-batch-docs/asciidoc/job.adoc b/spring-batch-docs/asciidoc/job.adoc new file mode 100644 index 000000000..e20742fe0 --- /dev/null +++ b/spring-batch-docs/asciidoc/job.adoc @@ -0,0 +1,1210 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[configureJob]] + +== Configuring and Running a Job + +In the <> , the overall + architecture design was discussed, using the following diagram as a + guide: + +.Batch Stereotypes +image::{batch-asciidoc}images/spring-batch-reference-model.png[Figure 2.1: Batch Stereotypes, scaledwidth="60%"] + +While the `Job` object may seem like a simple +container for steps, there are many configuration options of which a +developers must be aware . Furthermore, there are many considerations for +how a `Job` will be run and how its meta-data will be +stored during that run. This chapter will explain the various configuration +options and runtime concerns of a `Job`. + +[[configuringAJob]] + +=== Configuring a Job + +There are multiple implementations of the <> interface, however, the namespace +abstracts away the differences in configuration. It has only three +required dependencies: a name, `JobRepository` , and +a list of `Step` s. + + +[source, xml] +---- + + + + + +---- + +The examples here use a parent bean definition to create the steps; +see the section on <> +for more options declaring specific step details inline. The XML namespace +defaults to referencing a repository with an id of 'jobRepository', which +is a sensible default. However, this can be overridden explicitly: + + +[source, xml] +---- + + + + + +---- + +In addition to steps a job configuration can contain other elements + that help with parallelisation (``), + declarative flow control (``) and + externalization of flow definitions + (``). + +[[restartability]] + +==== Restartability + +One key issue when executing a batch job concerns the behavior of +a `Job` when it is restarted. The launching of a +`Job` is considered to be a 'restart' if a +`JobExecution` already exists for the particular +`JobInstance`. Ideally, all jobs should be able to +start up where they left off, but there are scenarios where this is not +possible. __It is entirely up to the developer to ensure that a new `JobInstance` is created in this scenario__. However, Spring Batch does provide some help. If a +`Job` should never be restarted, but should always +be run as part of a new `JobInstance`, then the +restartable property may be set to 'false': + + +[source, xml] +---- + + ... + +---- + +To phrase it another way, setting restartable to false means "this +`Job` does not support being started again". Restarting a `Job` that is not +restartable will cause a `JobRestartException` to +be thrown: + +[source, java] +---- +Job job = new SimpleJob(); +job.setRestartable(false); + +JobParameters jobParameters = new JobParameters(); + +JobExecution firstExecution = jobRepository.createJobExecution(job, jobParameters); +jobRepository.saveOrUpdate(firstExecution); + +try { + jobRepository.createJobExecution(job, jobParameters); + fail(); +} +catch (JobRestartException e) { + // expected +} +---- + +This snippet of JUnit code shows how attempting to create a +`JobExecution` the first time for a non restartable +job will cause no issues. However, the second +attempt will throw a `JobRestartException`. + +[[interceptingJobExecution]] + +==== Intercepting Job Execution + +During the course of the execution of a +Job, it may be useful to be notified of various +events in its lifecycle so that custom code may be executed. The +`SimpleJob` allows for this by calling a +`JobListener` at the appropriate time: + +[source, java] +---- +public interface JobExecutionListener { + + void beforeJob(JobExecution jobExecution); + + void afterJob(JobExecution jobExecution); + +} +---- + +`JobListeners` can be added to a +`SimpleJob` via the listeners element on the +job: + + +[source, xml] +---- + + + + + + + + +---- + +It should be noted that afterJob will be + called regardless of the success or failure of the + Job. If success or failure needs to be determined + it can be obtained from the `JobExecution`: + + +[source, java] +---- +public void afterJob(JobExecution jobExecution){ + if( jobExecution.getStatus() == BatchStatus.COMPLETED ){ + //job success + } + else if(jobExecution.getStatus() == BatchStatus.FAILED){ + //job failure + } +} +---- + +The annotations corresponding to this interface are: + + +* `@BeforeJob` +* `@AfterJob` + +[[inheritingFromAParentJob]] + + +==== Inheriting from a Parent Job + +If a group of Jobs share similar, but not + identical, configurations, then it may be helpful to define a "parent" + `Job` from which the concrete + Jobs may inherit properties. Similar to class + inheritance in Java, the "child" `Job` will combine + its elements and attributes with the parent's. + +In the following example, "baseJob" is an abstract + `Job` definition that defines only a list of + listeners. The `Job` "job1" is a concrete + definition that inherits the list of listeners from "baseJob" and merges + it with its own list of listeners to produce a + `Job` with two listeners and one + `Step`, "step1". + + +[source, xml] +---- + + + + + + + + + + + + + +---- + +Please see the section on <> + for more detailed information. + + + +==== JobParametersValidator + +A job declared in the XML namespace or using any subclass of + AbstractJob can optionally declare a validator for the job parameters at + runtime. This is useful when for instance you need to assert that a job + is started with all its mandatory parameters. There is a + DefaultJobParametersValidator that can be used to constrain combinations + of simple mandatory and optional parameters, and for more complex + constraints you can implement the interface yourself. The configuration + of a validator is supported through the XML namespace through a child + element of the job, e.g: + + +[source, xml] +---- + + + + +---- + +The validator can be specified as a reference (as above) or as a + nested bean definition in the beans namespace. + +[[javaConfig]] + + +=== Java Config + +Spring 3 brought the ability to configure applications via java instead + of XML. As of Spring Batch 2.2.0, batch jobs can be configured using the same + java config. There are two components for the java based configuration: + the `@EnableBatchConfiguration` annotation and two builders. + +The `@EnableBatchProcessing` works similarly to the other + @Enable* annotations in the Spring family. In this case, + `@EnableBatchProcessing` provides a base configuration for + building batch jobs. Within this base configuration, an instance of + `StepScope` is created in addition to a number of beans made + available to be autowired: + + + +* `JobRepository` - bean name "jobRepository" + + +* `JobLauncher` - bean name "jobLauncher" + + +* `JobRegistry` - bean name "jobRegistry" + + +* `PlatformTransactionManager` - bean name "transactionManager" + + +* `JobBuilderFactory` - bean name "jobBuilders" + + +* `StepBuilderFactory` - bean name "stepBuilders" + +The core interface for this configuration is the `BatchConfigurer`. + The default implementation provides the beans mentioned above and requires a + `DataSource` as a bean within the context to be provided. This data + source will be used by the JobRepository. + + + +[NOTE] +==== +Only one configuration class needs to have the + `@EnableBatchProcessing` annotation. Once you have a class + annotated with it, you will have all of the above available. + +==== + + +With the base configuration in place, a user can use the provided builder factories + to configure a job. Below is an example of a two step job configured via the + `JobBuilderFactory` and the `StepBuilderFactory`. + + +[source, java] +---- +@Configuration +@EnableBatchProcessing +@Import(DataSourceConfiguration.class) +public class AppConfig { + + @Autowired + private JobBuilderFactory jobs; + + @Autowired + private StepBuilderFactory steps; + + @Bean + public Job job(@Qualifier("step1") Step step1, @Qualifier("step2") Step step2) { + return jobs.get("myJob").start(step1).next(step2).build(); + } + + @Bean + protected Step step1(ItemReader reader, ItemProcessor processor, ItemWriter writer) { + return steps.get("step1") + . chunk(10) + .reader(reader) + .processor(processor) + .writer(writer) + .build(); + } + + @Bean + protected Step step2(Tasklet tasklet) { + return steps.get("step2") + .tasklet(tasklet) + .build(); + } +} +---- + +[[configuringJobRepository]] + +=== Configuring a JobRepository + +As described in earlier, the <> is used for basic CRUD operations of the various persisted + domain objects within Spring Batch, such as + `JobExecution` and + `StepExecution`. It is required by many of the major + framework features, such as the JobLauncher, + Job, and `Step`. The batch + namespace abstracts away many of the implementation details of the + `JobRepository` implementations and their + collaborators. However, there are still a few configuration options + available: + + +[source, xml] +---- + +---- + +None of the configuration options listed above are required except + the id. If they are not set, the defaults shown above will be used. They + are shown above for awareness purposes. The + `max-varchar-length` defaults to 2500, which is the + length of the long `VARCHAR` columns in the <> + +[[txConfigForJobRepository]] + + +==== Transaction Configuration for the JobRepository + +If the namespace is used, transactional advice will be + automatically created around the repository. This is to ensure that the + batch meta data, including state that is necessary for restarts after a + failure, is persisted correctly. The behavior of the framework is not + well defined if the repository methods are not transactional. The + isolation level in the `create*` method attributes is + specified separately to ensure that when jobs are launched, if two + processes are trying to launch the same job at the same time, only one + will succeed. The default isolation level for that method is + SERIALIZABLE, which is quite aggressive: READ_COMMITTED would work just + as well; READ_UNCOMMITTED would be fine if two processes are not likely + to collide in this way. However, since a call to the + `create*` method is quite short, it is unlikely + that the SERIALIZED will cause problems, as long as the database + platform supports it. However, this can be overridden: + + + +[source, xml] +---- + +---- + + + + +If the namespace or factory beans aren't used then it is also + essential to configure the transactional behavior of the repository + using AOP: + + + +[source, xml] +---- + + + + + + + + + + +---- + + + + +This fragment can be used as is, with almost no changes. Remember + also to include the appropriate namespace declarations and to make sure + spring-tx and spring-aop (or the whole of spring) are on the + classpath. + +[[repositoryTablePrefix]] + + +==== Changing the Table Prefix + +Another modifiable property of the + `JobRepository` is the table prefix of the + meta-data tables. By default they are all prefaced with BATCH_. + BATCH_JOB_EXECUTION and BATCH_STEP_EXECUTION are two examples. However, + there are potential reasons to modify this prefix. If the schema names + needs to be prepended to the table names, or if more than one set of + meta data tables is needed within the same schema, then the table prefix + will need to be changed: + + +[source, xml] +---- + +---- + +Given the above changes, every query to the meta data tables will + be prefixed with "SYSTEM.TEST_". BATCH_JOB_EXECUTION will be referred to + as SYSTEM.TEST_JOB_EXECUTION. + + +[NOTE] +==== +Only the table prefix is configurable. The table and column + names are not. + +==== + + +[[inMemoryRepository]] + + +==== In-Memory Repository + +There are scenarios in which you may not want to persist your + domain objects to the database. One reason may be speed; storing domain + objects at each commit point takes extra time. Another reason may be + that you just don't need to persist status for a particular job. For + this reason, Spring batch provides an in-memory Map version of the job + repository: + + +[source, xml] +---- + + + +---- + +Note that the in-memory repository is volatile and so does not + allow restart between JVM instances. It also cannot guarantee that two + job instances with the same parameters are launched simultaneously, and + is not suitable for use in a multi-threaded Job, or a locally + partitioned `Step`. So use the database version of the repository wherever + you need those features. + +However it does require a transaction manager to be defined + because there are rollback semantics within the repository, and because + the business logic might still be transactional (e.g. RDBMS access). For + testing purposes many people find the + `ResourcelessTransactionManager` useful. + +[[nonStandardDatabaseTypesInRepository]] + + +==== Non-standard Database Types in a Repository + +If you are using a database platform that is not in the list of + supported platforms, you may be able to use one of the supported types, + if the SQL variant is close enough. To do this you can use the raw + `JobRepositoryFactoryBean` instead of the namespace + shortcut and use it to set the database type to the closest + match: + + +[source, xml] +---- + + + + +---- + +(The `JobRepositoryFactoryBean` tries to + auto-detect the database type from the `DataSource` + if it is not specified.) The major differences between platforms are + mainly accounted for by the strategy for incrementing primary keys, so + often it might be necessary to override the + `incrementerFactory` as well (using one of the standard + implementations from the Spring Framework). + +If even that doesn't work, or you are not using an RDBMS, then the + only option may be to implement the various `Dao` + interfaces that the `SimpleJobRepository` depends + on and wire one up manually in the normal Spring way. + +[[configuringJobLauncher]] + + +=== Configuring a JobLauncher + +The most basic implementation of the + `JobLauncher` interface is the + `SimpleJobLauncher`. Its only required dependency is + a JobRepository, in order to obtain an + execution: + + +[source, xml] +---- + + + +---- + +Once a <> is + obtained, it is passed to the execute method of + Job, ultimately returning the + `JobExecution` to the caller: + +.Job Launcher Sequence +image::{batch-asciidoc}images/job-launcher-sequence-sync.png[Job Launcher Sequence, scaledwidth="60%"] + +The sequence is straightforward and works well when launched from a + scheduler. However, issues arise when trying to launch from an HTTP + request. In this scenario, the launching needs to be done asynchronously + so that the `SimpleJobLauncher` returns immediately + to its caller. This is because it is not good practice to keep an HTTP + request open for the amount of time needed by long running processes such + as batch. An example sequence is below: + +.Asynchronous Job Launcher Sequence +image::{batch-asciidoc}images/job-launcher-sequence-async.png[Async Job Launcher Sequence, scaledwidth="60%"] + + +The `SimpleJobLauncher` can easily be + configured to allow for this scenario by configuring a + `TaskExecutor`: + +[source, xml] +---- + + + + + + +---- + +Any implementation of the spring `TaskExecutor` + interface can be used to control how jobs are asynchronously + executed. + +[[runningAJob]] + + +=== Running a Job + +At a minimum, launching a batch job requires two things: the + `Job` to be launched and a + JobLauncher. Both can be contained within the same + context or different contexts. For example, if launching a job from the + command line, a new JVM will be instantiated for each Job, and thus every + job will have its own `JobLauncher`. However, if + running from within a web container within the scope of an + `HttpRequest`, there will usually be one + `JobLauncher`, configured for asynchronous job + launching, that multiple requests will invoke to launch their jobs. + +[[runningJobsFromCommandLine]] + + +==== Running Jobs from the Command Line + +For users that want to run their jobs from an enterprise + scheduler, the command line is the primary interface. This is because + most schedulers (with the exception of Quartz unless using the + NativeJob) work directly with operating system + processes, primarily kicked off with shell scripts. There are many ways + to launch a Java process besides a shell script, such as Perl, Ruby, or + even 'build tools' such as ant or maven. However, because most people + are familiar with shell scripts, this example will focus on them. + +[[commandLineJobRunner]] + + +===== The CommandLineJobRunner + +Because the script launching the job must kick off a Java + Virtual Machine, there needs to be a class with a main method to act + as the primary entry point. Spring Batch provides an implementation + that serves just this purpose: + `CommandLineJobRunner`. It's important to note + that this is just one way to bootstrap your application, but there are + many ways to launch a Java process, and this class should in no way be + viewed as definitive. The `CommandLineJobRunner` + performs four tasks: + + +* Load the appropriate + ApplicationContext + + +* Parse command line arguments into + JobParameters + + +* Locate the appropriate job based on arguments + + +* Use the `JobLauncher` provided in the + application context to launch the job. + +All of these tasks are accomplished using only the arguments + passed in. The following are required arguments: + +.CommandLineJobRunner arguments + +|=============== +|jobPath|The location of the XML file that will be used to + create an ApplicationContext. This file + should contain everything needed to run the complete + Job +|jobName|The name of the job to be run. + +|=============== + + +These arguments must be passed in with the path first and the + name second. All arguments after these are considered to be + JobParameters and must be in the format of 'name=value': + + +[source] +---- +>. The first argument is + 'endOfDayJob.xml', which is the Spring + ApplicationContext containing the + Job. The second argument, 'endOfDay' represents + the job name. The final argument, 'schedule.date(date)=2007/05/05' + will be converted into JobParameters. An + example of the XML configuration is below: + + +[source, xml] +---- + + + + + + +---- + +This example is overly simplistic, since there are many more + requirements to a run a batch job in Spring Batch in general, but it + serves to show the two main requirements of the + `CommandLineJobRunner`: + `Job` and + JobLauncher + +[[exitCodes]] + + +===== ExitCodes + +When launching a batch job from the command-line, an enterprise + scheduler is often used. Most schedulers are fairly dumb and work only + at the process level. This means that they only know about some + operating system process such as a shell script that they're invoking. + In this scenario, the only way to communicate back to the scheduler + about the success or failure of a job is through return codes. A + return code is a number that is returned to a scheduler by the process + that indicates the result of the run. In the simplest case: 0 is + success and 1 is failure. However, there may be more complex + scenarios: If job A returns 4 kick off job B, and if it returns 5 kick + off job C. This type of behavior is configured at the scheduler level, + but it is important that a processing framework such as Spring Batch + provide a way to return a numeric representation of the 'Exit Code' + for a particular batch job. In Spring Batch this is encapsulated + within an ExitStatus, which is covered in more + detail in Chapter 5. For the purposes of discussing exit codes, the + only important thing to know is that an + ExitStatus has an exit code property that is + set by the framework (or the developer) and is returned as part of the + `JobExecution` returned from the + JobLauncher. The + `CommandLineJobRunner` converts this string value + to a number using the ExitCodeMapper + interface: + + +[source, java] +---- +public interface ExitCodeMapper { + + public int intValue(String exitCode); + +} +---- + +The essential contract of an + ExitCodeMapper is that, given a string exit + code, a number representation will be returned. The default + implementation used by the job runner is the SimpleJvmExitCodeMapper + that returns 0 for completion, 1 for generic errors, and 2 for any job + runner errors such as not being able to find a + `Job` in the provided context. If anything more + complex than the 3 values above is needed, then a custom + implementation of the ExitCodeMapper interface + must be supplied. Because the + `CommandLineJobRunner` is the class that creates + an ApplicationContext, and thus cannot be + 'wired together', any values that need to be overwritten must be + autowired. This means that if an implementation of + ExitCodeMapper is found within the BeanFactory, + it will be injected into the runner after the context is created. All + that needs to be done to provide your own + ExitCodeMapper is to declare the implementation + as a root level bean and ensure that it is part of the + ApplicationContext that is loaded by the + runner. + +[[runningJobsFromWebContainer]] + + +==== Running Jobs from within a Web Container + +Historically, offline processing such as batch jobs have been + launched from the command-line, as described above. However, there are + many cases where launching from an `HttpRequest` is + a better option. Many such use cases include reporting, ad-hoc job + running, and web application support. Because a batch job by definition + is long running, the most important concern is ensuring to launch the + job asynchronously: + +.Asynchronous Job Launcher Sequence From Web Container +image::{batch-asciidoc}images/launch-from-request.png[Async Job Launcher Sequence from web container, scaledwidth="60%"] + + +The controller in this case is a Spring MVC controller. More + information on Spring MVC can be found here: link:$$http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html$$[http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html]. + The controller launches a `Job` using a + `JobLauncher` that has been configured to launch + <>, which + immediately returns a `JobExecution`. The + `Job` will likely still be running, however, this + nonblocking behaviour allows the controller to return immediately, which + is required when handling an `HttpRequest`. An + example is below: + + +[source, java] +---- +@Controller +public class JobLauncherController { + + @Autowired + JobLauncher jobLauncher; + + @Autowired + Job job; + + @RequestMapping("/jobLauncher.html") + public void handle() throws Exception{ + jobLauncher.run(job, new JobParameters()); + } +} +---- + +[[advancedMetaData]] + + +=== Advanced Meta-Data Usage + +So far, both the `JobLauncher` and `JobRepository` interfaces have been + discussed. Together, they represent simple launching of a job, and basic + CRUD operations of batch domain objects: + +.Job Repository +image::{batch-asciidoc}images/job-repository.png[Job Repository, scaledwidth="60%"] + +A `JobLauncher` uses the + `JobRepository` to create new + `JobExecution` objects and run them. + `Job` and `Step` implementations + later use the same `JobRepository` for basic updates + of the same executions during the running of a Job. + The basic operations suffice for simple scenarios, but in a large batch + environment with hundreds of batch jobs and complex scheduling + requirements, more advanced access of the meta data is required: + +.Advanced Job Repository Access +image::{batch-asciidoc}images/job-repository-advanced.png[Job Repository Advanced, scaledwidth="80%"] + +The JobExplorer and + JobOperator interfaces, which will be discussed + below, add additional functionality for querying and controlling the meta + data. + +[[queryingRepository]] + + +==== Querying the Repository + +The most basic need before any advanced features is the ability to + query the repository for existing executions. This functionality is + provided by the JobExplorer interface: + + +[source, java] +---- +public interface JobExplorer { + + List getJobInstances(String jobName, int start, int count); + + JobExecution getJobExecution(Long executionId); + + StepExecution getStepExecution(Long jobExecutionId, Long stepExecutionId); + + JobInstance getJobInstance(Long instanceId); + + List getJobExecutions(JobInstance jobInstance); + + Set findRunningJobExecutions(String jobName); +} +---- + +As is evident from the method signatures above, + JobExplorer is a read-only version of the + JobRepository, and like the + JobRepository, it can be easily configured via a + factory bean: + + +[source, xml] +---- + +---- + +<>, it was mentioned that the table prefix of the + `JobRepository` can be modified to allow for + different versions or schemas. Because the + JobExplorer is working with the same tables, it + too needs the ability to set a prefix: + + +[source, xml] +---- + +---- + +There are two ways to populate a `JobRegistry` automatically: using + a bean post processor and using a registrar lifecycle component. These + two mechanisms are described in the following sections. + +===== JobRegistryBeanPostProcessor + +This is a bean post-processor that can register all jobs as they + are created: + + +[source, xml] +---- + + + +---- + +Athough it is not strictly necessary the post-processor in the + example has been given an id so that it can be included in child + contexts (e.g. as a parent bean definition) and cause all jobs created + there to also be regsistered automatically. + + + +===== AutomaticJobRegistrar + +This is a lifecycle component that creates child contexts and + registers jobs from those contexts as they are created. One advantage + of doing this is that, while the job names in the child contexts still + have to be globally unique in the registry, their dependencies can + have "natural" names. So for example, you can create a set of XML + configuration files each having only one Job, + but all having different definitions of an + ItemReader with the same bean name, e.g. + "reader". If all those files were imported into the same context, the + reader definitions would clash and override one another, but with the + automatic regsistrar this is avoided. This makes it easier to + integrate jobs contributed from separate modules of an + application. + + +[source, xml] +---- + + + + + + + + + + + + +---- + +The registrar has two mandatory properties, one is an array of + ApplicationContextFactory (here created from a + convenient factory bean), and the other is a + JobLoader. The JobLoader + is responsible for managing the lifecycle of the child contexts and + registering jobs in the JobRegistry. + +The ApplicationContextFactory is + responsible for creating the child context and the most common usage + would be as above using a + ClassPathXmlApplicationContextFactory. One of + the features of this factory is that by default it copies some of the + configuration down from the parent context to the child. So for + instance you don't have to re-define the + PropertyPlaceholderConfigurer or AOP + configuration in the child, if it should be the same as the + parent. + +The AutomaticJobRegistrar can be used in + conjunction with a JobRegistryBeanPostProcessor + if desired (as long as the DefaultJobLoader is + used as well). For instance this might be desirable if there are jobs + defined in the main parent context as well as in the child + locations. + +[[JobOperator]] + + +==== JobOperator + +As previously discussed, the JobRepository + provides CRUD operations on the meta-data, and the + JobExplorer provides read-only operations on the + meta-data. However, those operations are most useful when used together + to perform common monitoring tasks such as stopping, restarting, or + summarizing a Job, as is commonly done by batch operators. Spring Batch + provides for these types of operations via the + JobOperator interface: + + +[source, java] +---- +public interface JobOperator { + + List getExecutions(long instanceId) throws NoSuchJobInstanceException; + + List getJobInstances(String jobName, int start, int count) + throws NoSuchJobException; + + Set getRunningExecutions(String jobName) throws NoSuchJobException; + + String getParameters(long executionId) throws NoSuchJobExecutionException; + + Long start(String jobName, String parameters) + throws NoSuchJobException, JobInstanceAlreadyExistsException; + + Long restart(long executionId) + throws JobInstanceAlreadyCompleteException, NoSuchJobExecutionException, + NoSuchJobException, JobRestartException; + + Long startNextInstance(String jobName) + throws NoSuchJobException, JobParametersNotFoundException, JobRestartException, + JobExecutionAlreadyRunningException, JobInstanceAlreadyCompleteException; + + boolean stop(long executionId) + throws NoSuchJobExecutionException, JobExecutionNotRunningException; + + String getSummary(long executionId) throws NoSuchJobExecutionException; + + Map getStepExecutionSummaries(long executionId) + throws NoSuchJobExecutionException; + + Set getJobNames(); + +} +---- + +The above operations represent methods from many different + interfaces, such as JobLauncher, + JobRepository, + JobExplorer, and + JobRegistry. For this reason, the provided + implementation of JobOperator, + SimpleJobOperator, has many dependencies: + + +[source, xml] +---- + + + + + + + + + + +---- + + +[NOTE] +==== + +If you set the table prefix on the job repository, don't forget to set it on the job explorer as well. +==== + + +[[JobParametersIncrementer]] + + +==== JobParametersIncrementer + +Most of the methods on JobOperator are + self-explanatory, and more detailed explanations can be found on the + link:$$http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/launch/JobOperator.html$$[javadoc of the interface]. However, the + startNextInstance method is worth noting. This + method will always start a new instance of a Job. + This can be extremely useful if there are serious issues in a + `JobExecution` and the Job + needs to be started over again from the beginning. Unlike + `JobLauncher` though, which requires a new + `JobParameters` object that will trigger a new + `JobInstance` if the parameters are different from + any previous set of parameters, the + startNextInstance method will use the + `JobParametersIncrementer` tied to the + `Job` to force the `Job` to a + new instance: + + +[source, java] +---- +public interface JobParametersIncrementer { + + JobParameters getNext(JobParameters parameters); + +} +---- + +The contract of `JobParametersIncrementer` is + that, given a <> + object, it will return the 'next' JobParameters + object by incrementing any necessary values it may contain. This + strategy is useful because the framework has no way of knowing what + changes to the `JobParameters` make it the 'next' + instance. For example, if the only value in + `JobParameters` is a date, and the next instance + should be created, should that value be incremented by one day? Or one + week (if the job is weekly for instance)? The same can be said for any + numerical values that help to identify the Job, + as shown below: + + +[source, java] +---- +public class SampleIncrementer implements JobParametersIncrementer { + + public JobParameters getNext(JobParameters parameters) { + if (parameters==null || parameters.isEmpty()) { + return new JobParametersBuilder().addLong("run.id", 1L).toJobParameters(); + } + long id = parameters.getLong("run.id",1L) + 1; + return new JobParametersBuilder().addLong("run.id", id).toJobParameters(); + } +} +---- + +In this example, the value with a key of 'run.id' is used to + discriminate between `JobInstances`. If the + `JobParameters` passed in is null, it can be + assumed that the `Job` has never been run before + and thus its initial state can be returned. However, if not, the old + value is obtained, incremented by one, and returned. An incrementer can + be associated with `Job` via the 'incrementer' + attribute in the namespace: + + +[source, xml] +---- + + ... + +---- + +[[stoppingAJob]] + + +==== Stopping a Job + +One of the most common use cases of + JobOperator is gracefully stopping a + Job: + + +[source, java] +---- +Set executions = jobOperator.getRunningExecutions("sampleJob"); +jobOperator.stop(executions.iterator().next()); +---- + +The shutdown is not immediate, since there is no way to force + immediate shutdown, especially if the execution is currently in + developer code that the framework has no control over, such as a + business service. However, as soon as control is returned back to the + framework, it will set the status of the current + `StepExecution` to + `BatchStatus.STOPPED`, save it, then do the same + for the `JobExecution` before finishing. + + + +==== Aborting a Job + +A job execution which is `FAILED` can be + restarted (if the `Job` is restartable). A job execution whose status is + `ABANDONED` will not be restarted by the framework. + The `ABANDONED` status is also used in step + executions to mark them as skippable in a restarted job execution: if a + job is executing and encounters a step that has been marked + `ABANDONED` in the previous failed job execution, it + will move on to the next step (as determined by the job flow definition + and the step execution exit status). + +If the process died (`"kill -9"` or server + failure) the job is, of course, not running, but the `JobRepository` has + no way of knowing because no-one told it before the process died. You + have to tell it manually that you know that the execution either failed + or should be considered aborted (change its status to + `FAILED` or `ABANDONED`) - it's + a business decision and there is no way to automate it. Only change the + status to `FAILED` if it is not restartable, or if + you know the restart data is valid. There is a utility in Spring Batch + Admin `JobService` to abort a job execution. + diff --git a/spring-batch-docs/asciidoc/jsr-352.adoc b/spring-batch-docs/asciidoc/jsr-352.adoc new file mode 100644 index 000000000..d12ee8f28 --- /dev/null +++ b/spring-batch-docs/asciidoc/jsr-352.adoc @@ -0,0 +1,626 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[jsr-352]] + +== JSR-352 Support + +As of Spring Batch 3.0 support for JSR-352 has been fully implemented. This section is not a replacement for + the spec itself and instead, intends to explain how the JSR-352 specific concepts apply to Spring Batch. + Additional information on JSR-352 can be found via the + JCP here: link:$$https://jcp.org/en/jsr/detail?id=352$$[https://jcp.org/en/jsr/detail?id=352] + +[[jsrGeneralNotes]] + + +=== General Notes Spring Batch and JSR-352 + +Spring Batch and JSR-352 are structurally the same. They both have jobs that are made up of steps. They + both have readers, processors, writers, and listeners. However, their interactions are subtly different. + For example, the `org.springframework.batch.core.SkipListener#onSkipInWrite(S item, Throwable t)` + within Spring Batch receives two parameters: the item that was skipped and the Exception that caused the + skip. The JSR-352 version of the same method + (`javax.batch.api.chunk.listener.SkipWriteListener#onSkipWriteItem(List<Object> items, Exception ex)`) + also receives two parameters. However the first one is a `List` of all the items + within the current chunk with the second being the `Exception` that caused the skip. + Because of these differences, it is important to note that there are two paths to execute a job within + Spring Batch: either a traditional Spring Batch job or a JSR-352 based job. While the use of Spring Batch + artifacts (readers, writers, etc) will work within a job configured via JSR-352's JSL and executed via the + `JsrJobOperator`, they will behave according to the rules of JSR-352. It is also + important to note that batch artifacts that have been developed against the JSR-352 interfaces will not work + within a traditional Spring Batch job. + +[[jsrSetup]] + + +=== Setup + +[[jsrSetupContexts]] + + +==== Application Contexts + +All JSR-352 based jobs within Spring Batch consist of two application contexts. A parent context, that + contains beans related to the infrastructure of Spring Batch such as the `JobRepository`, + `PlatformTransactionManager`, etc and a child context that consists of the configuration + of the job to be run. The parent context is defined via the `baseContext.xml` provided + by the framework. This context may be overridden via the `JSR-352-BASE-CONTEXT` system + property. + + +[NOTE] +==== +The base context is not processed by the JSR-352 processors for things like property injection so + no components requiring that additional processing should be configured there. + +==== + + +[[jsrSetupLaunching]] + + +==== Launching a JSR-352 based job + +JSR-352 requires a very simple path to executing a batch job. The following code is all that is needed to + execute your first batch job: + + + +[source, java] +---- +JobOperator operator = BatchRuntime.getJobOperator(); +jobOperator.start("myJob", new Properties()); +---- + +While that is convenient for developers, the devil is in the details. Spring Batch bootstraps a bit of + infrastructure behind the scenes that a developer may want to override. The following is bootstrapped the + first time `BatchRuntime.getJobOperator()` is called: + +|=============== +|__Bean Name__|__Default Configuration__|__Notes__ +| + dataSource + | + Apache DBCP BasicDataSource with configured values. + | + By default, HSQLDB is bootstrapped. + +|`transactionManager`|`org.springframework.jdbc.datasource.DataSourceTransactionManager`| + References the dataSource bean defined above. + +| + A Datasource initializer + || + This is configured to execute the scripts configured via the + `batch.drop.script` and `batch.schema.script` properties. By + default, the schema scripts for HSQLDB are executed. This behavior can be disabled via + `batch.data.source.init` property. + +| + jobRepository + | + A JDBC based `SimpleJobRepository`. + | + This `JobRepository` uses the previously mentioned data source and transaction + manager. The schema's table prefix is configurable (defaults to BATCH_) via the + `batch.table.prefix` property. + +| + jobLauncher + |`org.springframework.batch.core.launch.support.SimpleJobLauncher`| + Used to launch jobs. + +| + batchJobOperator + |`org.springframework.batch.core.launch.support.SimpleJobOperator`| + The `JsrJobOperator` wraps this to provide most of it's functionality. + +| + jobExplorer + |`org.springframework.batch.core.explore.support.JobExplorerFactoryBean`| + Used to address lookup functionality provided by the `JsrJobOperator`. + +| + jobParametersConverter + |`org.springframework.batch.core.jsr.JsrJobParametersConverter`| + JSR-352 specific implementation of the `JobParametersConverter`. + +| + jobRegistry + |`org.springframework.batch.core.configuration.support.MapJobRegistry`| + Used by the `SimpleJobOperator`. + +| + placeholderProperties + |`org.springframework.beans.factory.config.PropertyPlaceholderConfigure`| + Loads the properties file `batch-${ENVIRONMENT:hsql}.properties` to configure + the properties mentioned above. ENVIRONMENT is a System property (defaults to hsql) + that can be used to specify any of the supported databases Spring Batch currently + supports. + + +|=============== + + + + + + +[NOTE] +==== +None of the above beans are optional for executing JSR-352 based jobs. All may be overriden to + provide customized functionality as needed. +==== + + +[[dependencyInjection]] + + +=== Dependency Injection + +JSR-352 is based heavily on the Spring Batch programming model. As such, while not explicitly requiring a + formal dependency injection implementation, DI of some kind implied. Spring Batch supports all three + methods for loading batch artifacts defined by JSR-352: + + +* Implementation Specific Loader - Spring Batch is built upon Spring and so supports Spring + dependency injection within JSR-352 batch jobs. + + +* Archive Loader - JSR-352 defines the existing of a batch.xml file that provides mappings between a + logical name and a class name. This file must be found within the /META-INF/ directory if it is + used. + + +* Thread Context Class Loader - JSR-352 allows configurations to specify batch artifact + implementations in their JSL by providing the fully qualified class name inline. Spring Batch + supports this as well in JSR-352 configured jobs. + +To use Spring dependency injection within a JSR-352 based batch job consists of configuring batch + artifacts using a Spring application context as beans. Once the beans have been defined, a job can refer to + them as it would any bean defined within the batch.xml. + + +[source, xml] +---- + + + + + + + + + + + + + + + + +---- + +The assembly of Spring contexts (imports, etc) works with JSR-352 jobs just as it would with any other + Spring based application. The only difference with a JSR-352 based job is that the entry point for the + context definition will be the job definition found in /META-INF/batch-jobs/. + +To use the thread context class loader approach, all you need to do is provide the fully qualified class + name as the ref. It is important to note that when using this approach or the batch.xml approach, the class + referenced requires a no argument constructor which will be used to create the bean. + + +[source, xml] +---- + + + + + + + +---- + +[[jsrJobProperties]] + + +=== Batch Properties + +[[jsrPropertySupport]] + + +==== Property Support + +JSR-352 allows for properties to be defined at the Job, Step and batch artifact level by way of + configuration in the JSL. Batch properties are configured at each level in the following way: + + +[source, xml] +---- + + + + +---- + + +`Properties` may be configured on any batch artifact. + +[[jsrBatchPropertyAnnotation]] + + +==== @BatchProperty annotation + +`Properties` are referenced in batch artifacts by annotating class fields with the + `@BatchProperty` and `@Inject` annotations (both annotations + are required by the spec). As defined by JSR-352, fields for properties must be String typed. Any type + conversion is up to the implementing developer to perform. + +An `javax.batch.api.chunk.ItemReader` artifact could be configured with a + properties block such as the one described above and accessed as such: + + +[source, java] +---- +public class MyItemReader extends AbstractItemReader { + @Inject + @BatchProperty + private String propertyName1; + + ... +} +---- + + +The value of the field "propertyName1" will be "propertyValue1" + +[[jsrPropertySubstitution]] + + +==== Property Substitution + +Property substitution is provided by way of operators and simple conditional expressions. The general + usage is `#{operator['key']}`. + +Supported operators: + +* jobParameters - access job parameter values that the job was started/restarted with. + + +* jobProperties - access properties configured at the job level of the JSL. + + +* systemProperties - access named system properties. + + +* partitionPlan - access named property from the partition plan of a partitioned step. + +---- +#{jobParameters['unresolving.prop']}?:#{systemProperties['file.separator']} +---- + +The left hand side of the assignment is the expected value, the right hand side is the default value. In +this example, the result will resolve to a value of the system property file.separator as +#{jobParameters['unresolving.prop']} is assumed to not be resolvable. If neither expressions can be +resolved, an empty String will be returned. Multiple conditions can be used, which are separated by a +';'. + + +[[jsrProcessingModels]] + + +=== Processing Models + +JSR-352 provides the same two basic processing models that Spring Batch does: + + + +* Item based processing - Using an `javax.batch.api.chunk.ItemReader`, an + optional `javax.batch.api.chunk.ItemProcessor`, and an + `javax.batch.api.chunk.ItemWriter`. + + +* Task based processing - Using a `javax.batch.api.Batchlet` + implementation. This processing model is the same as the + `org.springframework.batch.core.step.tasklet.Tasklet` based processing + currently available. + + + + + + +==== Item based processing + +Item based processing in this context is a chunk size being set by the number of items read by an + `ItemReader`. To configure a step this way, specify the + `item-count` (which defaults to 10) and optionally configure the + `checkpoint-policy` as item (this is the default). + + + +[source, xml] +---- +... + + + + + + + +... +---- + + +If item based checkpointing is chosen, an additional attribute `time-limit` is + supported. This sets a time limit for how long the number of items specified has to be processed. If + the timeout is reached, the chunk will complete with however many items have been read by then + regardless of what the `item-count` is configured to be. + + + + +==== Custom checkpointing + +JSR-352 calls the process around the commit interval within a step "checkpointing". Item based + checkpointing is one approach as mentioned above. However, this will not be robust enough in many + cases. Because of this, the spec allows for the implementation of a custom checkpointing algorithm by + implementing the `javax.batch.api.chunk.CheckpointAlgorithm` interface. This + functionality is functionally the same as Spring Batch's custom completion policy. To use an + implementation of `CheckpointAlgorithm`, configure your step with the custom + `checkpoint-policy` as shown below where fooCheckpointer refers to an + implementation of `CheckpointAlgorithm`. + + + +[source, xml] +---- +... + + + + + + + + +... +---- + +[[jsrRunningAJob]] + + +=== Running a job + +The entrance to executing a JSR-352 based job is through the + `javax.batch.operations.JobOperator`. Spring Batch provides our own implementation to + this interface (`org.springframework.batch.core.jsr.launch.JsrJobOperator`). This + implementation is loaded via the `javax.batch.runtime.BatchRuntime`. Launching a + JSR-352 based batch job is implemented as follows: + + +[source, java] +---- + +JobOperator jobOperator = BatchRuntime.getJobOperator(); +long jobExecutionId = jobOperator.start("fooJob", new Properties()); + +---- + +The above code does the following: + + + +* Bootstraps a base `ApplicationContext` - In order to provide batch functionality, the framework + needs some infrastructure bootstrapped. This occurs once per JVM. The components that are + bootstrapped are similar to those provided by `@EnableBatchProcessing`. + Specific details can be found in the javadoc for the `JsrJobOperator`. + + + +* Loads an `ApplicationContext` for the job requested - In the example + above, the framework will look in /META-INF/batch-jobs for a file named fooJob.xml and load a + context that is a child of the shared context mentioned previously. + + +* Launch the job - The job defined within the context will be executed asynchronously. The + `JobExecution's` id will be returned. + + + + + +[NOTE] +==== +All JSR-352 based batch jobs are executed asynchronously. +==== + + +When `JobOperator#start` is called using `SimpleJobOperator`, + Spring Batch determines if the call is an initial run or a retry of a previously executed run. Using the + JSR-352 based `JobOperator#start(String jobXMLName, Properties jobParameters)`, the + framework will always create a new JobInstance (JSR-352 job parameters are + non-identifying). In order to restart a job, a call to + `JobOperator#restart(long executionId, Properties restartParameters)` is required. + + +[[jsrContexts]] + + +=== Contexts + +JSR-352 defines two context objects that are used to interact with the meta-data of a job or step from + within a batch artifact: `javax.batch.runtime.context.JobContext` and + `javax.batch.runtime.context.StepContext`. Both of these are available in any step + level artifact (`Batchlet`, `ItemReader`, etc) with the + `JobContext` being available to job level artifacts as well + (JobListener for example). + +To obtain a reference to the `JobContext` or `StepContext` + within the current scope, simply use the `@Inject` annotation: + + +[source, java] +---- +@Inject +JobContext jobContext; + +---- + + +[NOTE] +.@Autowire for JSR-352 contexts +==== +Using Spring's @Autowire is not supported for the injection of these contexts. +==== + + +In Spring Batch, the `JobContext` and `StepContext` wrap their + corresponding execution objects (`JobExecution` and + `StepExecution` respectively). Data stored via + `StepContext#persistent#setPersistentUserData(Serializable data)` is stored in the + Spring Batch `StepExecution#executionContext`. + +[[jsrStepFlow]] + + +=== Step Flow + +Within a JSR-352 based job, the flow of steps works similarly as it does within Spring Batch. + However, there are a few subtle differences: + + + +* Decision's are steps - In a regular Spring Batch job, a decision is a state that does not + have an independent `StepExecution` or any of the rights and + responsibilities that go along with being a full step.. However, with JSR-352, a decision + is a step just like any other and will behave just as any other steps (transactionality, + it gets a `StepExecution`, etc). This means that they are treated the + same as any other step on restarts as well. + + +* `next` attribute and step transitions - In a regular job, these are + allowed to appear together in the same step. JSR-352 allows them to both be used in the + same step with the next attribute taking precedence in evaluation. + + +* Transition element ordering - In a standard Spring Batch job, transition elements are + sorted from most specific to least specific and evaluated in that order. JSR-352 jobs + evaluate transition elements in the order they are specified in the XML. + + + + +[[jsrScaling]] + + +=== Scaling a JSR-352 batch job + +Traditional Spring Batch jobs have four ways of scaling (the last two capable of being executed across + multiple JVMs): + +* Split - Running multiple steps in parallel. + + +* Multiple threads - Executing a single step via multiple threads. + + +* Partitioning - Dividing the data up for parallel processing (master/slave). + + +* Remote Chunking - Executing the processor piece of logic remotely. + + + + +JSR-352 provides two options for scaling batch jobs. Both options support only a single JVM: + +* Split - Same as Spring Batch + + +* Partitioning - Conceptually the same as Spring Batch however implemented slightly different. + + + + + +[[jsrPartitioning]] + + +==== Partitioning + +Conceptually, partitioning in JSR-352 is the same as it is in Spring Batch. Meta-data is provided + to each slave to identify the input to be processed with the slaves reporting back to the master the + results upon completion. However, there are some important differences: + +* Partitioned `Batchlet` - This will run multiple instances of the + configured `Batchlet` on multiple threads. Each instance will have + it's own set of properties as provided by the JSL or the + `PartitionPlan` + + +* `PartitionPlan` - With Spring Batch's partitioning, an + `ExecutionContext` is provided for each partition. With JSR-352, a + single `javax.batch.api.partition.PartitionPlan` is provided with an + array of `Properties` providing the meta-data for each partition. + + + +* `PartitionMapper` - JSR-352 provides two ways to generate partition + meta-data. One is via the JSL (partition properties). The second is via an implementation + of the `javax.batch.api.partition.PartitionMapper` interface. + Functionally, this interface is similar to the + `org.springframework.batch.core.partition.support.Partitioner` + interface provided by Spring Batch in that it provides a way to programmatically generate + meta-data for partitioning. + + +* `StepExecutions` - In Spring Batch, partitioned steps are run as + master/slave. Within JSR-352, the same configuration occurs. However, the slave steps do + not get official `StepExecutions`. Because of that, calls to + `JsrJobOperator#getStepExecutions(long jobExecutionId)` will only + return the `StepExecution` for the master. +[NOTE] +==== +The child `StepExecutions` still exist in the job repository and are available +via the `JobExplorer` and Spring Batch Admin. + +==== + + +* Compensating logic - Since Spring Batch implements the master/slave logic of + partitioning using steps, `StepExecutionListeners` can be used to + handle compensating logic if something goes wrong. However, since the slaves JSR-352 + provides a collection of other components for the ability to provide compensating logic when + errors occur and to dynamically set the exit status. These components include the following: + +|=============== +|__Artifact Interface__|__Description__ +|`javax.batch.api.partition.PartitionCollector`|Provides a way for slave steps to send information back to the + master. There is one instance per slave thread. +|`javax.batch.api.partition.PartitionAnalyzer`|End point that receives the information collected by the + `PartitionCollector` as well as the resulting + statuses from a completed partition. +|`javax.batch.api.partition.PartitionReducer`|Provides the ability to provide compensating logic for a partitioned + step. + +|=============== + + +[[jsrTesting]] + +=== Testing + +Since all JSR-352 based jobs are executed asynchronously, it can be difficult to determine when a job has + completed. To help with testing, Spring Batch provides the + `org.springframework.batch.core.jsr.JsrTestUtils`. This utility class provides the + ability to start a job and restart a job and wait for it to complete. Once the job completes, the + associated `JobExecution` is returned. + diff --git a/spring-batch-docs/asciidoc/readersAndWriters.adoc b/spring-batch-docs/asciidoc/readersAndWriters.adoc new file mode 100644 index 000000000..7e057e606 --- /dev/null +++ b/spring-batch-docs/asciidoc/readersAndWriters.adoc @@ -0,0 +1,3008 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[readersAndWriters]] + +== ItemReaders and ItemWriters + +All batch processing can be described in its most simple form as + reading in large amounts of data, performing some type of calculation or + transformation, and writing the result out. Spring Batch provides three key + interfaces to help perform bulk reading and writing: + `ItemReader`, `ItemProcessor` and + `ItemWriter`. + +[[itemReader]] +=== ItemReader + +Although a simple concept, an `ItemReader` is +the means for providing data from many different types of input. The most +general examples include: + +* Flat File- Flat File Item Readers read lines of data from a +flat file that typically describe records with fields of data +defined by fixed positions in the file or delimited by some special +character (e.g. Comma). + +* XML - XML `ItemReaders` process XML independently of +technologies used for parsing, mapping and validating objects. Input +data allows for the validation of an XML file against an XSD +schema. + +* Database - A database resource is accessed to return +resultsets which can be mapped to objects for processing. The +default SQL `ItemReaders` invoke a `RowMapper` to +return objects, keep track of the current row if restart is +required, store basic statistics, and provide some transaction +enhancements that will be explained later. + +There are many more possibilities, but we'll focus on the +basic ones for this chapter. A complete list of all available `ItemReaders` +can be found in Appendix A. + +`ItemReader` is a basic interface for generic +input operations: + + +[source, java] +---- +public interface ItemReader { + + T read() throws Exception, UnexpectedInputException, ParseException; + +} +---- + +The read method defines the most essential +contract of the `ItemReader`; calling it returns one +Item or null if no more items are left. An item might represent a line in +a file, a row in a database, or an element in an XML file. It is generally +expected that these will be mapped to a usable domain object (i.e. Trade, +Foo, etc) but there is no requirement in the contract to do so. + +It is expected that implementations of the +`ItemReader` interface will be forward only. However, +if the underlying resource is transactional (such as a JMS queue) then +calling read may return the same logical item on subsequent calls in a +rollback scenario. It is also worth noting that a lack of items to process +by an `ItemReader` will not cause an exception to be +thrown. For example, a database `ItemReader` that is +configured with a query that returns 0 results will simply return null on +the first invocation of read. + +[[itemWriter]] + + +=== ItemWriter + +`ItemWriter` is similar in functionality to an +`ItemReader`, but with inverse operations. Resources +still need to be located, opened and closed but they differ in that an +`ItemWriter` writes out, rather than reading in. In +the case of databases or queues these may be inserts, updates, or sends. +The format of the serialization of the output is specific to each batch +job. + +As with `ItemReader`, +`ItemWriter` is a fairly generic interface: + + +[source, java] +---- +public interface ItemWriter { + + void write(List items) throws Exception; + +} +---- + +As with `read` on +`ItemReader`, `write` provides +the basic contract of `ItemWriter`; it will attempt +to write out the list of items passed in as long as it is open. Because it +is generally expected that items will be 'batched' together into a chunk +and then output, the interface accepts a list of items, rather than an +item by itself. After writing out the list, any flushing that may be +necessary can be performed before returning from the write method. For +example, if writing to a Hibernate DAO, multiple calls to write can be +made, one for each item. The writer can then call close on the hibernate +Session before returning. + +[[itemProcessor]] + + +=== ItemProcessor + +The `ItemReader` and `ItemWriter` interfaces are both very useful for +their specific tasks, but what if you want to insert business logic before +writing? One option for both reading and writing is to use the composite +pattern: create an `ItemWriter` that contains another +`ItemWriter`, or an `ItemReader` +that contains another `ItemReader`. For +example: + + +[source, java] +---- +public class CompositeItemWriter implements ItemWriter { + + ItemWriter itemWriter; + + public CompositeItemWriter(ItemWriter itemWriter) { + this.itemWriter = itemWriter; + } + + public void write(List items) throws Exception { + //Add business logic here + itemWriter.write(item); + } + + public void setDelegate(ItemWriter itemWriter){ + this.itemWriter = itemWriter; + } +} +---- + +The class above contains another `ItemWriter` +to which it delegates after having provided some business logic. This +pattern could easily be used for an `ItemReader` as +well, perhaps to obtain more reference data based upon the input that was +provided by the main `ItemReader`. It is also useful +if you need to control the call to `write` yourself. +However, if you only want to 'transform' the item passed in for writing +before it is actually written, there isn't much need to call +`write` yourself: you just want to modify the item. +For this scenario, Spring Batch provides the +`ItemProcessor` interface: + + +[source, java] +---- +public interface ItemProcessor { + + O process(I item) throws Exception; +} +---- + +An `ItemProcessor` is very simple; given one +object, transform it and return another. The provided object may or may +not be of the same type. The point is that business logic may be applied +within process, and is completely up to the developer to create. An +`ItemProcessor` can be wired directly into a step, +For example, assuming an `ItemReader` provides a +class of type Foo, and it needs to be converted to type Bar before being +written out. An `ItemProcessor` can be written that +performs the conversion: + + +[source, java] +---- +public class Foo {} + +public class Bar { + public Bar(Foo foo) {} +} + +public class FooProcessor implements ItemProcessor{ + public Bar process(Foo foo) throws Exception { + //Perform simple transformation, convert a Foo to a Bar + return new Bar(foo); + } +} + +public class BarWriter implements ItemWriter{ + public void write(List bars) throws Exception { + //write bars + } +} +---- + +In the very simple example above, there is a class +`Foo`, a class `Bar`, and a +class `FooProcessor` that adheres to the +`ItemProcessor` interface. The transformation is +simple, but any type of transformation could be done here. The +`BarWriter` will be used to write out +`Bar` objects, throwing an exception if any other +type is provided. Similarly, the `FooProcessor` will +throw an exception if anything but a `Foo` is +provided. The `FooProcessor` can then be injected +into a `Step`: + + +[source, xml] +---- + + + + + + + +---- + +[[chainingItemProcessors]] + + +==== Chaining ItemProcessors + +Performing a single transformation is useful in many scenarios, +but what if you want to 'chain' together multiple +`ItemProcessors`? This can be accomplished using +the composite pattern mentioned previously. To update the previous, +single transformation, example, `Foo` will be +transformed to `Bar`, which will be transformed to +`Foobar` and written out: + + +[source, java] +---- +public class Foo {} + +public class Bar { + public Bar(Foo foo) {} +} + +public class Foobar{ + public Foobar(Bar bar) {} +} + +public class FooProcessor implements ItemProcessor{ + public Bar process(Foo foo) throws Exception { + //Perform simple transformation, convert a Foo to a Bar + return new Bar(foo); + } +} + +public class BarProcessor implements ItemProcessor{ + public FooBar process(Bar bar) throws Exception { + return new Foobar(bar); + } +} + +public class FoobarWriter implements ItemWriter{ + public void write(List items) throws Exception { + //write items + } +} +---- + +A `FooProcessor` and + `BarProcessor` can be 'chained' together to give + the resultant `Foobar`: + + +[source, java] +---- +CompositeItemProcessor compositeProcessor = + new CompositeItemProcessor(); +List itemProcessors = new ArrayList(); +itemProcessors.add(new FooTransformer()); +itemProcessors.add(new BarTransformer()); +compositeProcessor.setDelegates(itemProcessors); +---- + +Just as with the previous example, the composite processor can be + configured into the `Step`: + + +[source, xml] +---- + + + + + + + + + + + + + + + + +---- + +[[filiteringRecords]] + + +==== Filtering Records + +One typical use for an item processor is to filter out records +before they are passed to the `ItemWriter`. Filtering is an action +distinct from skipping; skipping indicates that a record is invalid +whereas filtering simply indicates that a record should not be +written. + +For example, consider a batch job that reads a file containing +three different types of records: records to insert, records to update, +and records to delete. If record deletion is not supported by the +system, then we would not want to send any "delete" records to the +`ItemWriter`. But, since these records are not +actually bad records, we would want to filter them out, rather than +skip. As a result, the `ItemWriter` would receive only "insert" and +"update" records. + +To filter a record, one simply returns "null" from the +`ItemProcessor`. The framework will detect that the +result is "null" and avoid adding that item to the list of records +delivered to the `ItemWriter`. As usual, an +exception thrown from the `ItemProcessor` will +result in a skip. + +[[faultTolerant]] + + +==== Fault Tolerance + +When a chunk is rolled back, items that have been cached + during reading may be reprocessed. If a step is configured to + be fault tolerant (uses skip or retry processing typically), + any `ItemProcessor` used should be implemented in a way that is + idempotent. Typically that would consist of performing no changes + on the input item for the `ItemProcessor` and only updating the + instance that is the result. + +[[itemStream]] + +=== ItemStream + +Both `ItemReaders` and +`ItemWriters` serve their individual purposes well, +but there is a common concern among both of them that necessitates another +interface. In general, as part of the scope of a batch job, readers and +writers need to be opened, closed, and require a mechanism for persisting +state: + + +[source, java] +---- +public interface ItemStream { + + void open(ExecutionContext executionContext) throws ItemStreamException; + + void update(ExecutionContext executionContext) throws ItemStreamException; + + void close() throws ItemStreamException; +} +---- + +Before describing each method, we should mention the +`ExecutionContext`. Clients of an `ItemReader` that also implement +ItemStream should call +`open` before any calls to +`read` in order to open any resources such as files +or to obtain connections. A similar restriction applies to an +`ItemWriter` that implements +ItemStream. As mentioned in Chapter 2, if expected +data is found in the `ExecutionContext`, it may be +used to start the `ItemReader` or +`ItemWriter` at a location other than its initial +state. Conversely, `close` will be called to ensure +that any resources allocated during open will be +released safely. `update` is called primarily to +ensure that any state currently being held is loaded into the provided +`ExecutionContext`. This method will be called before +committing, to ensure that the current state is persisted in the database +before commit. + +In the special case where the client of an +`ItemStream` is a `Step` (from +the Spring Batch Core), an `ExecutionContext` is +created for each StepExecution to allow users to +store the state of a particular execution, with the expectation that it +will be returned if the same `JobInstance` is started +again. For those familiar with Quartz, the semantics are very similar to a +Quartz `JobDataMap`. + +[[delegatePatternAndRegistering]] + +=== The Delegate Pattern and Registering with the Step + +Note that the `CompositeItemWriter` is an + example of the delegation pattern, which is common in Spring Batch. The + delegates themselves might implement callback interfaces `StepListener`. + If they do, and they are being used in conjunction with Spring Batch Core + as part of a `Step` in a `Job`, + then they almost certainly need to be registered manually with the + `Step`. A reader, writer, or processor that is + directly wired into the `Step` will be registered automatically if it + implements `ItemStream` or a + `StepListener` interface. But because the delegates + are not known to the `Step`, they need to be injected + as listeners or streams (or both if appropriate): + +[source, xml] +---- + + + + + + + + + + + + + + + + + +---- + +[[flatFiles]] + +=== Flat Files + +One of the most common mechanisms for interchanging bulk data has +always been the flat file. Unlike XML, which has an agreed upon standard +for defining how it is structured (XSD), anyone reading a flat file must +understand ahead of time exactly how the file is structured. In general, +all flat files fall into two types: Delimited and Fixed Length. Delimited +files are those in which fields are separated by a delimiter, such as a +comma. Fixed Length files have fields that are a set length. + +[[fieldSet]] + +==== The FieldSet + +When working with flat files in Spring Batch, regardless of +whether it is for input or output, one of the most important classes is +the `FieldSet`. Many architectures and libraries +contain abstractions for helping you read in from a file, but they +usually return a String or an array of Strings. This really only gets +you halfway there. A `FieldSet` is Spring Batch's +abstraction for enabling the binding of fields from a file resource. It +allows developers to work with file input in much the same way as they +would work with database input. A `FieldSet` is +conceptually very similar to a Jdbc ResultSet. +`FieldSets` only require one argument, a String +array of tokens. Optionally, you can also configure in the names of the +fields so that the fields may be accessed either by index or name as +patterned after ResultSet: + + +[source, java] +---- +String[] tokens = new String[]{"foo", "1", "true"}; +FieldSet fs = new DefaultFieldSet(tokens); +String name = fs.readString(0); +int value = fs.readInt(1); +boolean booleanValue = fs.readBoolean(2); +---- + +There are many more options on the `FieldSet` +interface, such as `Date`, long, +`BigDecimal`, etc. The biggest advantage of the +`FieldSet` is that it provides consistent parsing +of flat file input. Rather than each batch job parsing differently in +potentially unexpected ways, it can be consistent, both when handling +errors caused by a format exception, or when doing simple data +conversions. + +[[flatFileItemReader]] + +==== FlatFileItemReader + +A flat file is any type of file that contains at most +two-dimensional (tabular) data. Reading flat files in the Spring Batch +framework is facilitated by the class +`FlatFileItemReader`, which provides basic +functionality for reading and parsing flat files. The two most important +required dependencies of `FlatFileItemReader` are +`Resource` and `LineMapper`. +The `LineMapper` interface will be +explored more in the next sections. The resource property represents a +Spring Core `Resource`. Documentation explaining +how to create beans of this type can be found in link:$$http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/resources.html$$[Spring +Framework, Chapter 5.Resources]. Therefore, this +guide will not go into the details of creating +`Resource` objects. However, a simple example of a +file system resource can be found below: + +[source, java] +---- +Resource resource = new FileSystemResource("resources/trades.csv"); +---- + +In complex batch environments the directory structures are often + managed by the EAI infrastructure where drop zones for external + interfaces are established for moving files from ftp locations to batch + processing locations and vice versa. File moving utilities are beyond + the scope of the spring batch architecture but it is not unusual for + batch job streams to include file moving utilities as steps in the job + stream. It is sufficient that the batch architecture only needs to know + how to locate the files to be processed. Spring Batch begins the process + of feeding the data into the pipe from this starting point. However, + link:$$http://projects.spring.io/spring-integration/$$[Spring + Integration] provides many of these types of + services. + +The other properties in `FlatFileItemReader` +allow you to further specify how your data will be interpreted: `FlatFileItemReader` Properties + +[options="header"] +|=============== +|Property|Type|Description +|comments|String[]|Specifies line prefixes that indicate + comment rows +|encoding|String|Specifies what text encoding to use - + default is "ISO-8859-1" +|lineMapper|`LineMapper`|Converts a `String` + to an `Object` representing the + item. +|linesToSkip|int|Number of lines to ignore at the top of + the file +|recordSeparatorPolicy|RecordSeparatorPolicy|Used to determine where the line endings + are and do things like continue over a line ending if inside a + quoted string. +|resource|`Resource`|The resource from which to read. +|skippedLinesCallback|LineCallbackHandler|Interface which passes the raw line + content of the lines in the file to be skipped. If linesToSkip + is set to 2, then this interface will be called twice. +|strict|boolean|In strict mode, the reader will throw an + exception on `ExecutionContext` if the input resource does not + exist. + +|=============== + +[[lineMapper]] + + +===== LineMapper + +As with `RowMapper`, which takes a low +level construct such as ResultSet and returns +an Object, flat file processing requires the +same construct to convert a String line into an +Object: + + + +[source, java] +---- +public interface LineMapper { + + T mapLine(String line, int lineNumber) throws Exception; + +} +---- + +The basic contract is that, given the current line and the line +number with which it is associated, the mapper should return a +resulting domain object. This is similar to +`RowMapper` in that each line is associated with +its line number, just as each row in a +ResultSet is tied to its row number. This +allows the line number to be tied to the resulting domain object for +identity comparison or for more informative logging. However, unlike +`RowMapper`, the +`LineMapper` is given a raw line which, as +discussed above, only gets you halfway there. The line must be +tokenized into a `FieldSet`, which can then be +mapped to an object, as described below. + +[[lineTokenizer]] + + +===== LineTokenizer + +An abstraction for turning a line of input into a line into a +`FieldSet` is necessary because there can be many +formats of flat file data that need to be converted to a +`FieldSet`. In Spring Batch, this interface is +the `LineTokenizer`: + + +[source, java] +---- +public interface LineTokenizer { + + FieldSet tokenize(String line); + +} +---- + +The contract of a `LineTokenizer` is such +that, given a line of input (in theory the +`String` could encompass more than one line), a +`FieldSet` representing the line will be +returned. This `FieldSet` can then be passed to a +`FieldSetMapper`. Spring Batch contains the +following `LineTokenizer` implementations: + + +* `DelmitedLineTokenizer` - Used for +files where fields in a record are separated by a delimiter. The +most common delimiter is a comma, but pipes or semicolons are +often used as well. + + +* `FixedLengthTokenizer` - Used for files +where fields in a record are each a 'fixed width'. The width of +each field must be defined for each record type. + + +* `PatternMatchingCompositeLineTokenizer` +- Determines which among a list of +`LineTokenizers` should be used on a +particular line by checking against a pattern. + +[[fieldSetMapper]] + +===== FieldSetMapper + +The `FieldSetMapper` interface defines a +single method, `mapFieldSet`, which takes a +`FieldSet` object and maps its contents to an +object. This object may be a custom DTO, a domain object, or a simple +array, depending on the needs of the job. The +`FieldSetMapper` is used in conjunction with the +`LineTokenizer` to translate a line of data from +a resource into an object of the desired type: + + +[source, java] +---- +public interface FieldSetMapper { + + T mapFieldSet(FieldSet fieldSet); + +} +---- + +The pattern used is the same as the + `RowMapper` used by + `JdbcTemplate`. + +[[defaultLineMapper]] + + +===== DefaultLineMapper + +Now that the basic interfaces for reading in flat files have +been defined, it becomes clear that three basic steps are +required: + +. Read one line from the file. + +. Pass the string line into the `LineTokenizer#tokenize()` method, in +order to retrieve a `FieldSet`. + + +. Pass the `FieldSet` returned from tokenizing to a `FieldSetMapper`, returning +the result from the `ItemReader#read()` method. + + + +The two interfaces described above represent two separate tasks: +converting a line into a `FieldSet`, and mapping +a `FieldSet` to a domain object. Because the +input of a `LineTokenizer` matches the input of +the `LineMapper` (a line), and the output of a +`FieldSetMapper` matches the output of the +`LineMapper`, a default implementation that uses +both a `LineTokenizer` and +`FieldSetMapper` is provided. The +`DefaultLineMapper` represents the behavior most +users will need: + + +[source, java] +---- + +public class DefaultLineMapper; implements LineMapper<>, InitializingBean { + + private LineTokenizer tokenizer; + + private FieldSetMapper fieldSetMapper; + + public T mapLine(String line, int lineNumber) throws Exception { + return fieldSetMapper.mapFieldSet(tokenizer.tokenize(line)); + } + + public void setLineTokenizer(LineTokenizer tokenizer) { + this.tokenizer = tokenizer; + } + + public void setFieldSetMapper(FieldSetMapper; fieldSetMapper) { + this.fieldSetMapper = fieldSetMapper; + } +} +---- + +The above functionality is provided in a default implementation, +rather than being built into the reader itself (as was done in +previous versions of the framework) in order to allow users greater +flexibility in controlling the parsing process, especially if access +to the raw line is needed. + +[[simpleDelimitedFileReadingExample]] + +===== Simple Delimited File Reading Example + +The following example will be used to illustrate this using an +actual domain scenario. This particular batch job reads in football +players from the following file: + + + +---- +ID,lastName,firstName,position,birthYear,debutYear +"AbduKa00,Abdul-Jabbar,Karim,rb,1974,1996", +"AbduRa00,Abdullah,Rabih,rb,1975,1999", +"AberWa00,Abercrombie,Walter,rb,1959,1982", +"AbraDa00,Abramowicz,Danny,wr,1945,1967", +"AdamBo00,Adams,Bob,te,1946,1969", +"AdamCh00,Adams,Charlie,wr,1979,2003" +---- + +The contents of this file will be mapped to the following +`Player` domain object: + +[source, java] +---- +public class Player implements Serializable { + + private String ID; + private String lastName; + private String firstName; + private String position; + private int birthYear; + private int debutYear; + + public String toString() { + return "PLAYER:ID=" + ID + ",Last Name=" + lastName + + ",First Name=" + firstName + ",Position=" + position + + ",Birth Year=" + birthYear + ",DebutYear=" + + debutYear; + } + + // setters and getters... +} +---- + +In order to map a `FieldSet` into a + `Player` object, a + `FieldSetMapper` that returns players needs to be + defined: + + +[source, java] +---- +protected static class PlayerFieldSetMapper implements FieldSetMapper { + public Player mapFieldSet(FieldSet fieldSet) { + Player player = new Player(); + + player.setID(fieldSet.readString(0)); + player.setLastName(fieldSet.readString(1)); + player.setFirstName(fieldSet.readString(2)); + player.setPosition(fieldSet.readString(3)); + player.setBirthYear(fieldSet.readInt(4)); + player.setDebutYear(fieldSet.readInt(5)); + + return player; + } +} +---- + +The file can then be read by correctly constructing a + `FlatFileItemReader` and calling + read: + + +[source, java] +---- +FlatFileItemReader itemReader = new FlatFileItemReader(); +itemReader.setResource(new FileSystemResource("resources/players.csv")); +//DelimitedLineTokenizer defaults to comma as its delimiter +DefaultLineMapper lineMapper = new DefaultLineMapper(); +lineMapper.setLineTokenizer(new DelimitedLineTokenizer()); +lineMapper.setFieldSetMapper(new PlayerFieldSetMapper()); +itemReader.setLineMapper(lineMapper); +itemReader.open(new ExecutionContext()); +Player player = itemReader.read(); +---- + +Each call to read will return a new + `Player` object from each line in the file. When the end of the file is + reached, null will be returned. + +[[mappingFieldsByName]] + +===== Mapping Fields by Name + +There is one additional piece of functionality that is allowed +by both `DelimitedLineTokenizer` and +`FixedLengthTokenizer` that is similar in +function to a Jdbc `ResultSet`. The names of the +fields can be injected into either of these +`LineTokenizer` implementations to increase the +readability of the mapping function. First, the column names of all +fields in the flat file are injected into the tokenizer: + + +[source, java] +---- +tokenizer.setNames(new String[] {"ID", "lastName","firstName","position","birthYear","debutYear"}); +---- + +A `FieldSetMapper` can use this information + as follows: + + +[source, java] +---- + { + public Player mapFieldSet(FieldSet fs) { + + if(fs == null){ + return null; + } + + Player player = new Player(); + player.setID(fs.readString("ID")); + player.setLastName(fs.readString("lastName")); + player.setFirstName(fs.readString("firstName")); + player.setPosition(fs.readString("position")); + player.setDebutYear(fs.readInt("debutYear")); + player.setBirthYear(fs.readInt("birthYear")); + + return player; + } +} +---- + +[[beanWrapperFieldSetMapper]] + +===== Automapping FieldSets to Domain Objects + +For many, having to write a specific +`FieldSetMapper` is equally as cumbersome as +writing a specific `RowMapper` for a +`JdbcTemplate`. Spring Batch makes this easier by +providing a `FieldSetMapper` that automatically +maps fields by matching a field name with a setter on the object using +the JavaBean specification. Again using the football example, the +`BeanWrapperFieldSetMapper` configuration looks +like the following: + + +[source, xml] +---- + + + + + +---- + +For each entry in the `FieldSet`, the +mapper will look for a corresponding setter on a new instance of the +`Player` object (for this reason, prototype scope +is required) in the same way the Spring container will look for +setters matching a property name. Each available field in the +`FieldSet` will be mapped, and the resultant +`Player` object will be returned, with no code +required. + +[[fixedLengthFileFormats]] + + +===== Fixed Length File Formats + +So far only delimited files have been discussed in much detail, + however, they represent only half of the file reading picture. Many + organizations that use flat files use fixed length formats. An example + fixed length file is below: + + +---- +UK21341EAH4121131.11customer1 +UK21341EAH4221232.11customer2 +UK21341EAH4321333.11customer3 +UK21341EAH4421434.11customer4 +UK21341EAH4521535.11customer5 +---- + +While this looks like one large field, it actually represent 4 distinct fields: + + +. ISIN: Unique identifier for the item being order - 12 characters long. + + +. Quantity: Number of this item being ordered - 3 characters long. + + +. Price: Price of the item - 5 characters long. + + +. Customer: Id of the customer ordering the item - 9 characters long. + +When configuring the `FixedLengthLineTokenizer`, each of these lengths +must be provided in the form of ranges: + + +[source, xml] +---- + + + + +---- + +Because the `FixedLengthLineTokenizer` uses +the same `LineTokenizer` interface as discussed +above, it will return the same `FieldSet` as if a +delimiter had been used. This allows the same approaches to be used in +handling its output, such as using the +`BeanWrapperFieldSetMapper`. + + +[NOTE] +==== +Supporting the above syntax for ranges requires that a +specialized property editor, +`RangeArrayPropertyEditor`, be configured in +the `ApplicationContext`. However, this bean +is automatically declared in an +`ApplicationContext` where the batch +namespace is used. +==== + +[[prefixMatchingLineMapper]] + +===== Multiple Record Types within a Single File + +All of the file reading examples up to this point have all made +a key assumption for simplicity's sake: all of the records in a file +have the same format. However, this may not always be the case. It is +very common that a file might have records with different formats that +need to be tokenized differently and mapped to different objects. The +following excerpt from a file illustrates this: + +---- +USER;Smith;Peter;;T;20014539;F +LINEA;1044391041ABC037.49G201XX1383.12H +LINEB;2134776319DEF422.99M005LI +---- + +In this file we have three types of records, "USER", "LINEA", +and "LINEB". A "USER" line corresponds to a User object. "LINEA" and +"LINEB" both correspond to Line objects, though a "LINEA" has more +information than a "LINEB". + +The `ItemReader` will read each line +individually, but we must specify different +`LineTokenizer` and +`FieldSetMapper` objects so that the +`ItemWriter` will receive the correct items. The +`PatternMatchingCompositeLineMapper` makes this +easy by allowing maps of patterns to +`LineTokenizers` and patterns to +`FieldSetMappers` to be configured: + + +[source, xml] +---- + + + + + + + + + + + + + + + +---- + +In this example, "LINEA" and "LINEB" have separate +`LineTokenizers` but they both use the same +`FieldSetMapper`. + +The `PatternMatchingCompositeLineMapper` +makes use of the `PatternMatcher's` +match method in order to select the correct +delegate for each line. The `PatternMatcher` +allows for two wildcard characters with special meaning: the question +mark ("?") will match exactly one character, while the asterisk ("\*") +will match zero or more characters. Note that in the configuration +above, all patterns end with an asterisk, making them effectively +prefixes to lines. The `PatternMatcher` will +always match the most specific pattern possible, regardless of the +order in the configuration. So if "LINE*" and "LINEA*" were both +listed as patterns, "LINEA" would match pattern "LINEA*", while +"LINEB" would match pattern "LINE*". Additionally, a single asterisk +("*") can serve as a default by matching any line not matched by any +other pattern. + + +[source, xml] +---- + +---- + +There is also a + `PatternMatchingCompositeLineTokenizer` that can + be used for tokenization alone. + +It is also common for a flat file to contain records that each + span multiple lines. To handle this situation, a more complex strategy + is required. A demonstration of this common pattern can be found in + <>. + +[[exceptionHandlingInFlatFiles]] + + +===== Exception Handling in Flat Files + +There are many scenarios when tokenizing a line may cause +exceptions to be thrown. Many flat files are imperfect and contain +records that aren't formatted correctly. Many users choose to skip +these erroneous lines, logging out the issue, original line, and line +number. These logs can later be inspected manually or by another batch +job. For this reason, Spring Batch provides a hierarchy of exceptions +for handling parse exceptions: `FlatFileParseException` and `FlatFileFormatException`. +`FlatFileParseException` is thrown by the `FlatFileItemReader` when any errors are +encountered while trying to read a file. +`FlatFileFormatException` is thrown by +implementations of the `LineTokenizer` interface, +and indicates a more specific error encountered while +tokenizing. + +[[incorrectTokenCountException]] + +====== IncorrectTokenCountException + +Both `DelimitedLineTokenizer` and +`FixedLengthLineTokenizer` have the ability to +specify column names that can be used for creating a +`FieldSet`. However, if the number of column +names doesn't match the number of columns found while tokenizing a +line the `FieldSet` can't be created, and a +`IncorrectTokenCountException` is thrown, which +contains the number of tokens encountered, and the number +expected: + + +[source, java] +---- +tokenizer.setNames(new String[] {"A", "B", "C", "D"}); + +try { + tokenizer.tokenize("a,b,c"); +} +catch(IncorrectTokenCountException e){ + assertEquals(4, e.getExpectedCount()); + assertEquals(3, e.getActualCount()); +} +---- + +Because the tokenizer was configured with 4 column names, but +only 3 tokens were found in the file, an +`IncorrectTokenCountException` was +thrown. + +[[incorrectLineLengthException]] + +====== IncorrectLineLengthException + +Files formatted in a fixed length format have additional +requirements when parsing because, unlike a delimited format, each +column must strictly adhere to its predefined width. If the total +line length doesn't add up to the widest value of this column, an +exception is thrown: + + +[source, java] +---- +tokenizer.setColumns(new Range[] { new Range(1, 5), + new Range(6, 10), + new Range(11, 15) }); +try { + tokenizer.tokenize("12345"); + fail("Expected IncorrectLineLengthException"); +} +catch (IncorrectLineLengthException ex) { + assertEquals(15, ex.getExpectedLength()); + assertEquals(5, ex.getActualLength()); +} +---- + +The configured ranges for the tokenizer above are: 1-5, 6-10, +and 11-15, thus the total length of the line expected is 15. +However, in this case a line of length 5 was passed in, causing an +`IncorrectLineLengthException` to be thrown. +Throwing an exception here rather than only mapping the first column +allows the processing of the line to fail earlier, and with more +information than it would if it failed while trying to read in +column 2 in a `FieldSetMapper`. However, there +are scenarios where the length of the line isn't always constant. +For this reason, validation of line length can be turned off via the +'strict' property: + +[source, java] +---- +tokenizer.setColumns(new Range[] { new Range(1, 5), new Range(6, 10) }); +tokenizer.setStrict(false); +FieldSet tokens = tokenizer.tokenize("12345"); +assertEquals("12345", tokens.readString(0)); +assertEquals("", tokens.readString(1)); +---- + +The above example is almost identical to the one before it, +except that tokenizer.setStrict(false) was called. This setting +tells the tokenizer to not enforce line lengths when tokenizing the +line. A `FieldSet` is now correctly created and +returned. However, it will only contain empty tokens for the +remaining values. + +[[flatFileItemWriter]] + +==== FlatFileItemWriter + +Writing out to flat files has the same problems and issues that +reading in from a file must overcome. A step must be able to write out +in either delimited or fixed length formats in a transactional +manner. + +[[lineAggregator]] + +===== LineAggregator + +Just as the `LineTokenizer` interface is +necessary to take an item and turn it into a +String, file writing must have a way to +aggregate multiple fields into a single string for writing to a file. +In Spring Batch this is the +`LineAggregator`: + + +[source, java] +---- +public interface LineAggregator { + + public String aggregate(T item); + +} +---- + +The `LineAggregator` is the opposite of a `LineTokenizer`. `LineTokenizer` takes a +`String` and returns a `FieldSet`, whereas `LineAggregator` takes an `item` and returns a +`String`. + +[[PassThroughLineAggregator]] + +====== PassThroughLineAggregator + +The most basic implementation of the `LineAggregator` interface + is the `PassThroughLineAggregator`, which + simply assumes that the object is already a string, or that its + string representation is acceptable for writing: + + +[source, java] +---- +public class PassThroughLineAggregator implements LineAggregator { + + public String aggregate(T item) { + return item.toString(); + } +} +---- + +The above implementation is useful if direct control of +creating the string is required, but the advantages of a +`FlatFileItemWriter`, such as transaction and +restart support, are necessary. + +[[SimplifiedFileWritingExample]] + +===== Simplified File Writing Example + +Now that the `LineAggregator` interface and its most basic implementation, +`PassThroughLineAggregator`, have been defined, the basic flow of writing can be explained: + + +. The object to be written is passed to the `LineAggregator` in order to obtain a +String. + + +. The returned String is written to the configured file. + +The following excerpt from the `FlatFileItemWriter` expresses this in code: + + +[source, java] +---- +public void write(T item) throws Exception { + write(lineAggregator.aggregate(item) + LINE_SEPARATOR); +} +---- + +A simple configuration would look like the following: + + +[source, xml] +---- + + + + + + +---- + +[[FieldExtractor]] + +===== FieldExtractor + +The above example may be useful for the most basic uses of a + writing to a file. However, most users of the + `FlatFileItemWriter` will have a domain object + that needs to be written out, and thus must be converted into a line. + In file reading, the following was required: + +. Read one line from the file. + +. Pass the string line into the `LineTokenizer#tokenize()` method, in +order to retrieve a `FieldSet` + +. Pass the `FieldSet` returned from tokenizing to a `FieldSetMapper`, returning +the result from the `ItemReader#read()` method + + + +File writing has similar, but inverse steps: + +. Pass the item to be written to the writer + +. convert the fields on the item into an array + +. aggregate the resulting array into a line + +Because there is no way for the framework to know which fields +from the object need to be written out, a +`FieldExtractor` must be written to accomplish +the task of turning the item into an array: + + +[source, java] +---- +public interface FieldExtractor { + + Object[] extract(T item); + +} +---- + +Implementations of the `FieldExtractor` +interface should create an array from the fields of the provided +object, which can then be written out with a delimiter between the +elements, or as part of a field-width line. + +[[PassThroughFieldExtractor]] + +====== PassThroughFieldExtractor + +There are many cases where a collection, such as an array, +`Collection`, or +`FieldSet`, needs to be written out. +"Extracting" an array from a one of these collection types is very +straightforward: simply convert the collection to an array. +Therefore, the `PassThroughFieldExtractor` +should be used in this scenario. It should be noted, that if the +object passed in is not a type of collection, then the +`PassThroughFieldExtractor` will return an +array containing solely the item to be extracted. + +[[BeanWrapperFieldExtractor]] + + +====== BeanWrapperFieldExtractor + +As with the `BeanWrapperFieldSetMapper` +described in the file reading section, it is often preferable to +configure how to convert a domain object to an object array, rather +than writing the conversion yourself. The +`BeanWrapperFieldExtractor` provides just this +type of functionality: + + +[source, java] +---- +BeanWrapperFieldExtractor extractor = new BeanWrapperFieldExtractor(); +extractor.setNames(new String[] { "first", "last", "born" }); + +String first = "Alan"; +String last = "Turing"; +int born = 1912; + +Name n = new Name(first, last, born); +Object[] values = extractor.extract(n); + +assertEquals(first, values[0]); +assertEquals(last, values[1]); +assertEquals(born, values[2]); +---- + +This extractor implementation has only one required property, +the names of the fields to map. Just as the +`BeanWrapperFieldSetMapper` needs field names +to map fields on the `FieldSet` to setters on +the provided object, the +`BeanWrapperFieldExtractor` needs names to map +to getters for creating an object array. It is worth noting that the +order of the names determines the order of the fields within the +array. + +[[delimitedFileWritingExample]] + +===== Delimited File Writing Example + +The most basic flat file format is one in which all fields are +separated by a delimiter. This can be accomplished using a +`DelimitedLineAggregator`. The example below +writes out a simple domain object that represents a credit to a +customer account: + + +[source, java] +---- +public class CustomerCredit { + + private int id; + private String name; + private BigDecimal credit; + + //getters and setters removed for clarity +} +---- + +Because a domain object is being used, an implementation of the +`FieldExtractor` interface must be provided, along with the delimiter to +use: + + +[source, xml] +---- + + + + + + + + + + + + + +---- + +In this case, the +`BeanWrapperFieldExtractor` described earlier in +this chapter is used to turn the name and credit fields within +`CustomerCredit` into an object array, which is +then written out with commas between each field. + +[[fixedWidthFileWritingExample]] + + +===== Fixed Width File Writing Example + +Delimited is not the only type of flat file format. Many prefer +to use a set width for each column to delineate between fields, which +is usually referred to as 'fixed width'. Spring Batch supports this in +file writing via the `FormatterLineAggregator`. +Using the same `CustomerCredit` domain object +described above, it can be configured as follows: + + +[source, xml] +---- + + + + + + + + + + + + + +---- + +Most of the above example should look familiar. However, the +value of the format property is new: + + +[source, xml] +---- + +---- + +The underlying implementation is built using the same +`Formatter` added as part of Java 5. The Java +`Formatter` is based on the +`printf` functionality of the C programming +language. Most details on how to configure a formatter can be found in +the javadoc of link:$$http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html$$[Formatter]. + +[[handlingFileCreation]] + +===== Handling File Creation + +`FlatFileItemReader` has a very simple +relationship with file resources. When the reader is initialized, it +opens the file if it exists, and throws an exception if it does not. +File writing isn't quite so simple. At first glance it seems like a +similar straight forward contract should exist for +`FlatFileItemWriter`: if the file already exists, +throw an exception, and if it does not, create it and start writing. +However, potentially restarting a `Job` can cause +issues. In normal restart scenarios, the contract is reversed: if the +file exists, start writing to it from the last known good position, +and if it does not, throw an exception. However, what happens if the +file name for this job is always the same? In this case, you would +want to delete the file if it exists, unless it's a restart. Because +of this possibility, the `FlatFileItemWriter` +contains the property, `shouldDeleteIfExists`. +Setting this property to true will cause an existing file with the +same name to be deleted when the writer is opened. + +[[xmlReadingWriting]] + +=== XML Item Readers and Writers + +Spring Batch provides transactional infrastructure for both reading +XML records and mapping them to Java objects as well as writing Java +objects as XML records. + + +[NOTE] +.Constraints on streaming XML +==== +The StAX API is used for I/O as other standard XML parsing APIs do +not fit batch processing requirements (DOM loads the whole input into +memory at once and SAX controls the parsing process allowing the user +only to provide callbacks). +==== + +Lets take a closer look how XML input and output works in Spring +Batch. First, there are a few concepts that vary from file reading and +writing but are common across Spring Batch XML processing. With XML +processing, instead of lines of records (`FieldSets`) that need to be +tokenized, it is assumed an XML resource is a collection of 'fragments' +corresponding to individual records: + +.XML Input +image::{batch-asciidoc}images/xmlinput.png[XML Input, scaledwidth="60%"] + + + +The 'trade' tag is defined as the 'root element' in the scenario +above. Everything between '<trade>' and '</trade>' is +considered one 'fragment'. Spring Batch uses Object/XML Mapping (OXM) to +bind fragments to objects. However, Spring Batch is not tied to any +particular XML binding technology. Typical use is to delegate to link:$$http://docs.spring.io/spring-ws/site/reference/html/oxm.html$$[Spring +OXM], which provides uniform abstraction for the most +popular OXM technologies. The dependency on Spring OXM is optional and you +can choose to implement Spring Batch specific interfaces if desired. The +relationship to the technologies that OXM supports can be shown as the +following: + +.OXM Binding +image::{batch-asciidoc}images/oxm-fragments.png[OXM Binding, scaledwidth="60%"] + +Now with an introduction to OXM and how one can use XML fragments to +represent records, let's take a closer look at readers and writers. + +[[StaxEventItemReader]] + +==== StaxEventItemReader + +The `StaxEventItemReader` configuration +provides a typical setup for the processing of records from an XML input +stream. First, lets examine a set of XML records that the +`StaxEventItemReader` can process. + + +[source, xml] +---- + + + + XYZ0001 + 5 + 11.39 + Customer1 + + + XYZ0002 + 2 + 72.99 + Customer2c + + + XYZ0003 + 9 + 99.99 + Customer3 + + +---- + +To be able to process the XML records the following is needed: + +* Root Element Name - Name of the root element of the fragment +that constitutes the object to be mapped. The example +configuration demonstrates this with the value of trade. + + +* Resource - Spring Resource that represents the file to be +read. + + +* `Unmarshaller` - Unmarshalling +facility provided by Spring OXM for mapping the XML fragment to an +object. + + + + +[source, xml] +---- + + + + + +---- + +Notice that in this example we have chosen to use an +`XStreamMarshaller` which accepts an alias passed +in as a map with the first key and value being the name of the fragment +(i.e. root element) and the object type to bind. Then, similar to a +`FieldSet`, the names of the other elements that +map to fields within the object type are described as key/value pairs in +the map. In the configuration file we can use a Spring configuration +utility to describe the required alias as follows: + + +[source, xml] +---- + + + + + + + + + +---- + +On input the reader reads the XML resource until it recognizes +that a new fragment is about to start (by matching the tag name by +default). The reader creates a standalone XML document from the fragment +(or at least makes it appear so) and passes the document to a +deserializer (typically a wrapper around a Spring OXM +`Unmarshaller`) to map the XML to a Java +object. + +In summary, this procedure is analogous to the following scripted +Java code which uses the injection provided by the Spring +configuration: + +[source, java] +---- +StaxEventItemReader xmlStaxEventItemReader = new StaxEventItemReader() +Resource resource = new ByteArrayResource(xmlResource.getBytes()) + +Map aliases = new HashMap(); +aliases.put("trade","org.springframework.batch.sample.domain.Trade"); +aliases.put("price","java.math.BigDecimal"); +aliases.put("customer","java.lang.String"); +XStreamMarshaller unmarshaller = new XStreamMarshaller(); +unmarshaller.setAliases(aliases); +xmlStaxEventItemReader.setUnmarshaller(unmarshaller); +xmlStaxEventItemReader.setResource(resource); +xmlStaxEventItemReader.setFragmentRootElementName("trade"); +xmlStaxEventItemReader.open(new ExecutionContext()); + +boolean hasNext = true + +CustomerCredit credit = null; + +while (hasNext) { + credit = xmlStaxEventItemReader.read(); + if (credit == null) { + hasNext = false; + } + else { + System.out.println(credit); + } +} +---- + +[[StaxEventItemWriter]] + +==== StaxEventItemWriter + +Output works symmetrically to input. The +`StaxEventItemWriter` needs a +Resource, a marshaller, and a `rootTagName`. A Java +object is passed to a marshaller (typically a standard Spring OXM +Marshaller) which writes to a +Resource using a custom event writer that filters +the StartDocument and +EndDocument events produced for each fragment by +the OXM tools. We'll show this in an example using the +MarshallingEventWriterSerializer. The Spring +configuration for this setup looks as follows: + + +[source, xml] +---- + + + + + + +---- + +The configuration sets up the three required properties and +optionally sets the overwriteOutput=true, mentioned earlier in the +chapter for specifying whether an existing file can be overwritten. It +should be noted the marshaller used for the writer is the exact same as +the one used in the reading example from earlier in the chapter: + + +[source, xml] +---- + + + + + + + + + +---- + +To summarize with a Java example, the following code illustrates +all of the points discussed, demonstrating the programmatic setup of the +required properties: + + +[source, java] +---- +StaxEventItemWriter staxItemWriter = new StaxEventItemWriter() +FileSystemResource resource = new FileSystemResource("data/outputFile.xml") + +Map aliases = new HashMap(); +aliases.put("customer","org.springframework.batch.sample.domain.CustomerCredit"); +aliases.put("credit","java.math.BigDecimal"); +aliases.put("name","java.lang.String"); +Marshaller marshaller = new XStreamMarshaller(); +marshaller.setAliases(aliases); + +staxItemWriter.setResource(resource); +staxItemWriter.setMarshaller(marshaller); +staxItemWriter.setRootTagName("trades"); +staxItemWriter.setOverwriteOutput(true); + +ExecutionContext executionContext = new ExecutionContext(); +staxItemWriter.open(executionContext); +CustomerCredit Credit = new CustomerCredit(); +trade.setPrice(11.39); +credit.setName("Customer1"); +staxItemWriter.write(trade); +---- + +[[multiFileInput]] + + +=== Multi-File Input + +It is a common requirement to process multiple files within a single + `Step`. Assuming the files all have the same + formatting, the `MultiResourceItemReader` supports + this type of input for both XML and flat file processing. Consider the + following files in a directory: + + +---- +file-1.txt file-2.txt ignored.txt +---- + +file-1.txt and file-2.txt are formatted the same and for business + reasons should be processed together. The + MuliResourceItemReader can be used to read in both + files by using wildcards: + + +[source, xml] +---- + + + + +---- + +The referenced delegate is a simple +`FlatFileItemReader`. The above configuration will +read input from both files, handling rollback and restart scenarios. It +should be noted that, as with any `ItemReader`, +adding extra input (in this case a file) could cause potential issues when +restarting. It is recommended that batch jobs work with their own +individual directories until completed successfully. + +[[database]] + + +=== Database + +Like most enterprise application styles, a database is the central +storage mechanism for batch. However, batch differs from other application +styles due to the sheer size of the datasets with which the system must +work. If a SQL statement returns 1 million rows, the result set probably +holds all returned results in memory until all rows have been read. Spring +Batch provides two types of solutions for this problem: Cursor and Paging +database `ItemReaders`. + +[[cursorBasedItemReaders]] + +==== Cursor Based ItemReaders + +Using a database cursor is generally the default approach of most +batch developers, because it is the database's solution to the problem +of 'streaming' relational data. The Java +`ResultSet` class is essentially an object +orientated mechanism for manipulating a cursor. A +`ResultSet` maintains a cursor to the current row +of data. Calling `next` on a +`ResultSet` moves this cursor to the next row. +Spring Batch cursor based `ItemReaders` open the a cursor on +initialization, and move the cursor forward one row for every call to +`read`, returning a mapped object that can be +used for processing. The `close` method will then +be called to ensure all resources are freed up. The Spring core +`JdbcTemplate` gets around this problem by using +the callback pattern to completely map all rows in a +`ResultSet` and close before returning control back +to the method caller. However, in batch this must wait until the step is +complete. Below is a generic diagram of how a cursor based +`ItemReader` works, and while a SQL statement is +used as an example since it is so widely known, any technology could +implement the basic approach: + +.Cursor Example +image::{batch-asciidoc}images/cursorExample.png[Cursor Example, scaledwidth="60%"] + + +This example illustrates the basic pattern. Given a 'FOO' table, +which has three columns: ID, NAME, and BAR, select all rows with an ID +greater than 1 but less than 7. This puts the beginning of the cursor +(row 1) on ID 2. The result of this row should be a completely mapped +Foo object. Calling `read()` again moves the +cursor to the next row, which is the Foo with an ID of 3. The results of +these reads will be written out after each +`read`, thus allowing the objects to be garbage +collected (assuming no instance variables are maintaining references to +them). + +[[JdbcCursorItemReader]] + + +===== JdbcCursorItemReader + +`JdbcCursorItemReader` is the Jdbc +implementation of the cursor based technique. It works directly with a +`ResultSet` and requires a SQL statement to run +against a connection obtained from a +DataSource. The following database schema will +be used as an example: + + +[source, sql] +---- +CREATE TABLE CUSTOMER ( + ID BIGINT IDENTITY PRIMARY KEY, + NAME VARCHAR(45), + CREDIT FLOAT +); +---- + +Many people prefer to use a domain object for each row, so we'll +use an implementation of the `RowMapper` +interface to map a `CustomerCredit` +object: + + +[source, java] +---- +public class CustomerCreditRowMapper implements RowMapper { + + public static final String ID_COLUMN = "id"; + public static final String NAME_COLUMN = "name"; + public static final String CREDIT_COLUMN = "credit"; + + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + CustomerCredit customerCredit = new CustomerCredit(); + + customerCredit.setId(rs.getInt(ID_COLUMN)); + customerCredit.setName(rs.getString(NAME_COLUMN)); + customerCredit.setCredit(rs.getBigDecimal(CREDIT_COLUMN)); + + return customerCredit; + } +} +---- + +Because `JdbcTemplate` is so familiar to +users of Spring, and the `JdbcCursorItemReader` +shares key interfaces with it, it is useful to see an example of how +to read in this data with `JdbcTemplate`, in +order to contrast it with the `ItemReader`. For +the purposes of this example, let's assume there are 1,000 rows in the +CUSTOMER database. The first example will be using +`JdbcTemplate`: + + +[source, java] +---- +//For simplicity sake, assume a dataSource has already been obtained +JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); +List customerCredits = jdbcTemplate.query("SELECT ID, NAME, CREDIT from CUSTOMER", + new CustomerCreditRowMapper()); +---- + +After running this code snippet the customerCredits list will +contain 1,000 `CustomerCredit` objects. In the +query method, a connection will be obtained from the +DataSource, the provided SQL will be run +against it, and the `mapRow` method will be +called for each row in the `ResultSet`. Let's +contrast this with the approach of the +`JdbcCursorItemReader`: + + +[source, java] +---- +JdbcCursorItemReader itemReader = new JdbcCursorItemReader(); +itemReader.setDataSource(dataSource); +itemReader.setSql("SELECT ID, NAME, CREDIT from CUSTOMER"); +itemReader.setRowMapper(new CustomerCreditRowMapper()); +int counter = 0; +ExecutionContext executionContext = new ExecutionContext(); +itemReader.open(executionContext); +Object customerCredit = new Object(); +while(customerCredit != null){ + customerCredit = itemReader.read(); + counter++; +} +itemReader.close(executionContext); +---- + +After running this code snippet the counter will equal 1,000. If +the code above had put the returned customerCredit into a list, the +result would have been exactly the same as with the +`JdbcTemplate` example. However, the big +advantage of the `ItemReader` is that it allows +items to be 'streamed'. The `read` method can +be called once, and the item written out via an +`ItemWriter`, and then the next item obtained via +`read`. This allows item reading and writing to +be done in 'chunks' and committed periodically, which is the essence +of high performance batch processing. Furthermore, it is very easily +configured for injection into a Spring Batch +`Step`: + + +[source, xml] +---- + + + + + + + +---- + +[[JdbcCursorItemReaderProperties]] + +====== Additional Properties + +Because there are so many varying options for opening a cursor +in Java, there are many properties on the +JdbcCustorItemReader that can be set: + +.JdbcCursorItemReader Properties + +|=============== +|ignoreWarnings|Determines whether or not SQLWarnings are logged or + cause an exception - default is true +|fetchSize|Gives the Jdbc driver a hint as to the number of rows + that should be fetched from the database when more rows are + needed by the `ResultSet` object used + by the `ItemReader`. By default, no + hint is given. +|maxRows|Sets the limit for the maximum number of rows the + underlying `ResultSet` can hold at any + one time. +|queryTimeout|Sets the number of seconds the driver will wait for a + `Statement` object to execute to the + given number of seconds. If the limit is exceeded, a + `DataAccessException` is thrown. + (Consult your driver vendor documentation for + details). +|verifyCursorPosition|Because the same `ResultSet` + held by the `ItemReader` is passed to + the `RowMapper`, it is possible for + users to call `ResultSet.next()` + themselves, which could cause issues with the reader's + internal count. Setting this value to true will cause an + exception to be thrown if the cursor position is not the + same after the `RowMapper` call as it + was before. +|saveState|Indicates whether or not the reader's state should be + saved in the `ExecutionContext` + provided by + `ItemStream#update(ExecutionContext)` + The default value is true. +|driverSupportsAbsolute|Defaults to false. Indicates whether the Jdbc driver + supports setting the absolute row on a + `ResultSet`. It is recommended that + this is set to true for Jdbc drivers that supports + `ResultSet`.absolute() as it may + improve performance, especially if a step fails while + working with a large data set. +|setUseSharedExtendedConnection|Defaults to false. Indicates whether the connection + used for the cursor should be used by all other processing + thus sharing the same transaction. If this is set to false, + which is the default, then the cursor will be opened using + its own connection and will not participate in any + transactions started for the rest of the step processing. If + you set this flag to true then you must wrap the + DataSource in an + `ExtendedConnectionDataSourceProxy` to + prevent the connection from being closed and released after + each commit. When you set this option to true then the + statement used to open the cursor will be created with both + 'READ_ONLY' and 'HOLD_CUSORS_OVER_COMMIT' options. This + allows holding the cursor open over transaction start and + commits performed in the step processing. To use this + feature you need a database that supports this and a Jdbc + driver supporting Jdbc 3.0 or later. + +|=============== + + +[[HibernateCursorItemReader]] + +===== HibernateCursorItemReader + +Just as normal Spring users make important decisions about +whether or not to use ORM solutions, which affect whether or not they +use a `JdbcTemplate` or a +`HibernateTemplate`, Spring Batch users have the +same options. `HibernateCursorItemReader` is the +Hibernate implementation of the cursor technique. Hibernate's usage in +batch has been fairly controversial. This has largely been because +Hibernate was originally developed to support online application +styles. However, that doesn't mean it can't be used for batch +processing. The easiest approach for solving this problem is to use a +`StatelessSession` rather than a standard +session. This removes all of the caching and dirty checking hibernate +employs that can cause issues in a batch scenario. For more +information on the differences between stateless and normal hibernate +sessions, refer to the documentation of your specific hibernate +release. The `HibernateCursorItemReader` allows +you to declare an HQL statement and pass in a +`SessionFactory`, which will pass back one item +per call to read in the same basic fashion as +the `JdbcCursorItemReader`. Below is an example +configuration using the same 'customer credit' example as the JDBC +reader: + + +[source, java] +---- +HibernateCursorItemReader itemReader = new HibernateCursorItemReader(); +itemReader.setQueryString("from CustomerCredit"); +//For simplicity sake, assume sessionFactory already obtained. +itemReader.setSessionFactory(sessionFactory); +itemReader.setUseStatelessSession(true); +int counter = 0; +ExecutionContext executionContext = new ExecutionContext(); +itemReader.open(executionContext); +Object customerCredit = new Object(); +while(customerCredit != null){ + customerCredit = itemReader.read(); + counter++; +} +itemReader.close(executionContext); +---- + +This configured `ItemReader` will return +`CustomerCredit` objects in the exact same manner +as described by the `JdbcCursorItemReader`, +assuming hibernate mapping files have been created correctly for the +Customer table. The 'useStatelessSession' property defaults to true, +but has been added here to draw attention to the ability to switch it +on or off. It is also worth noting that the fetchSize of the +underlying cursor can be set via the setFetchSize property. As with +`JdbcCursorItemReader`, configuration is +straightforward: + + +[source, xml] +---- + + + + +---- + +[[StoredProcedureItemReader]] + +===== StoredProcedureItemReader + +Sometimes it is necessary to obtain the cursor data using a +stored procedure. The `StoredProcedureItemReader` +works like the `JdbcCursorItemReader` except that +instead of executing a query to obtain a cursor we execute a stored +procedure that returns a cursor. The stored procedure can return the +cursor in three different ways: + + +. as a returned `ResultSet` (used by SQL Server, Sybase, DB2, Derby and MySQL) + +. as a ref-cursor returned as an out parameter (used by Oracle and PostgreSQL) + +. as the return value of a stored function call + +Below is a basic example configuration using the same 'customer +credit' example as earlier: + + +[source, xml] +---- + + + + + + + + +---- + +This example relies on the stored procedure to provide a +`ResultSet` as a returned result (option 1 above). + +If the stored procedure returned a ref-cursor (option 2) then we +would need to provide the position of the out parameter that is the +returned ref-cursor. Here is an example where the first parameter is +the returned ref-cursor: + +[source, xml] +---- + + + + + + + + + +---- + +If the cursor was returned from a stored function (option 3) we +would need to set the property "[maroon]#function#" to +`true`. It defaults to `false`. Here +is what that would look like: + + +[source, xml] +---- + + + + + + + + + +---- + +In all of these cases we need to define a + `RowMapper` as well as a + DataSource and the actual procedure + name. + +If the stored procedure or function takes in parameter then they + must be declared and set via the parameters property. Here is an + example for Oracle that declares three parameters. The first one is + the out parameter that returns the ref-cursor, the second and third + are in parameters that takes a value of type INTEGER: + + +[source, xml] +---- + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +---- + +In addition to the parameter declarations we need to specify a +`PreparedStatementSetter` implementation that +sets the parameter values for the call. This works the same as for the +`JdbcCursorItemReader` above. All the additional +properties listed in <> +apply to the `StoredProcedureItemReader` as well. + +[[pagingItemReaders]] + +==== Paging ItemReaders + +An alternative to using a database cursor is executing multiple + queries where each query is bringing back a portion of the results. We + refer to this portion as a page. Each query that is executed must + specify the starting row number and the number of rows that we want + returned for the page. + +[[JdbcPagingItemReader]] + +===== JdbcPagingItemReader + +One implementation of a paging `ItemReader` + is the `JdbcPagingItemReader`. The + `JdbcPagingItemReader` needs a + `PagingQueryProvider` responsible for providing + the SQL queries used to retrieve the rows making up a page. Since each + database has its own strategy for providing paging support, we need to + use a different `PagingQueryProvider` for each + supported database type. There is also the + `SqlPagingQueryProviderFactoryBean` that will + auto-detect the database that is being used and determine the + appropriate `PagingQueryProvider` implementation. + This simplifies the configuration and is the recommended best + practice. + +The `SqlPagingQueryProviderFactoryBean` + requires that you specify a select clause and a from clause. You can + also provide an optional where clause. These clauses will be used to + build an SQL statement combined with the required sortKey. + +After the reader has been opened, it will pass back one item per + call to `read` in the same basic fashion as any + other `ItemReader`. The paging happens behind the + scenes when additional rows are needed. + +Below is an example configuration using a similar 'customer + credit' example as the cursor based `ItemReaders` above: + + +[source, xml] +---- + + + + + + + + + + + + + + + + + + +---- + +This configured `ItemReader` will return +`CustomerCredit` objects using the +`RowMapper` that must be specified. The +'pageSize' property determines the number of entities read from the +database for each query execution. + +The 'parameterValues' property can be used to specify a Map of +parameter values for the query. If you use named parameters in the +where clause the key for each entry should match the name of the named +parameter. If you use a traditional '?' placeholder then the key for +each entry should be the number of the placeholder, starting with +1. + +[[JpaPagingItemReader]] + +===== JpaPagingItemReader + +Another implementation of a paging +`ItemReader` is the +`JpaPagingItemReader`. JPA doesn't have a concept +similar to the Hibernate `StatelessSession` so we +have to use other features provided by the JPA specification. Since +JPA supports paging, this is a natural choice when it comes to using +JPA for batch processing. After each page is read, the entities will +become detached and the persistence context will be cleared in order +to allow the entities to be garbage collected once the page is +processed. + +The `JpaPagingItemReader` allows you to +declare a JPQL statement and pass in a +`EntityManagerFactory`. It will then pass back +one item per call to read in the same basic +fashion as any other `ItemReader`. The paging +happens behind the scenes when additional entities are needed. Below +is an example configuration using the same 'customer credit' example +as the JDBC reader above: + + +[source, xml] +---- + + + + + +---- + +This configured `ItemReader` will return +`CustomerCredit` objects in the exact same manner +as described by the `JdbcPagingItemReader` above, +assuming the Customer object has the correct JPA annotations or ORM +mapping file. The 'pageSize' property determines the number of +entities read from the database for each query execution. + + +[[databaseItemWriters]] + +==== Database ItemWriters + +While both Flat Files and XML have specific `ItemWriters`, there is +no exact equivalent in the database world. This is because transactions +provide all the functionality that is needed. `ItemWriters` are necessary +for files because they must act as if they're transactional, keeping +track of written items and flushing or clearing at the appropriate +times. Databases have no need for this functionality, since the write is +already contained in a transaction. Users can create their own DAOs that +implement the `ItemWriter` interface or use one +from a custom `ItemWriter` that's written for +generic processing concerns, either way, they should work without any +issues. One thing to look out for is the performance and error handling +capabilities that are provided by batching the outputs. This is most +common when using hibernate as an `ItemWriter`, but +could have the same issues when using Jdbc batch mode. Batching database +output doesn't have any inherent flaws, assuming we are careful to flush +and there are no errors in the data. However, any errors while writing +out can cause confusion because there is no way to know which individual +item caused an exception, or even if any individual item was +responsible, as illustrated below: + +.Error On Flush +image::{batch-asciidoc}images/errorOnFlush.png[Error On Flush, scaledwidth="60%"] + + +If items are buffered before being written out, any +errors encountered will not be thrown until the buffer is flushed just +before a commit. For example, let's assume that 20 items will be written +per chunk, and the 15th item throws a DataIntegrityViolationException. +As far as the `Step` is concerned, all 20 item will be written out +successfully, since there's no way to know that an error will occur +until they are actually written out. Once +Session#flush() is +called, the buffer will be emptied and the exception will be hit. At +this point, there's nothing the `Step` can do, the +transaction must be rolled back. Normally, this exception might cause +the Item to be skipped (depending upon the skip/retry policies), and +then it won't be written out again. However, in the batched scenario, +there's no way for it to know which item caused the issue, the whole +buffer was being written out when the failure happened. The only way to +solve this issue is to flush after each item: + +.Error On Write +image::{batch-asciidoc}images/errorOnWrite.png[Error On Write, scaledwidth="60%"] + +http://docs.spring.io/spring-batch/reference/html/images/errorOnWrite.png.pagespeed.ce.SKTuwx-ca1.png +This is a common use case, especially when using Hibernate, and +the simple guideline for implementations of `ItemWriter`, is to flush on each call to +`write()`. Doing so allows for items to be +skipped reliably, with Spring Batch taking care internally of the +granularity of the calls to `ItemWriter` after an error. + + +[[reusingExistingServices]] + + +=== Reusing Existing Services + +Batch systems are often used in conjunction with other application +styles. The most common is an online system, but it may also support +integration or even a thick client application by moving necessary bulk +data that each application style uses. For this reason, it is common that +many users want to reuse existing DAOs or other services within their +batch jobs. The Spring container itself makes this fairly easy by allowing +any necessary class to be injected. However, there may be cases where the +existing service needs to act as an `ItemReader` or +`ItemWriter`, either to satisfy the dependency of +another Spring Batch class, or because it truly is the main +`ItemReader` for a step. It is fairly trivial to +write an adaptor class for each service that needs wrapping, but because +it is such a common concern, Spring Batch provides implementations: +`ItemReaderAdapter` and +`ItemWriterAdapter`. Both classes implement the +standard Spring method invoking the delegate pattern and are fairly simple +to set up. Below is an example of the reader: + + +[source, xml] +---- + + + + + + +---- + +One important point to note is that the contract of the targetMethod +must be the same as the contract for `read`: when +exhausted it will return null, otherwise an `Object`. +Anything else will prevent the framework from knowing when processing +should end, either causing an infinite loop or incorrect failure, +depending upon the implementation of the +`ItemWriter`. The `ItemWriter` +implementation is equally as simple: + + +[source, xml] +---- + + + + + + + +---- + +[[validatingInput]] + + +=== Validating Input + +During the course of this chapter, multiple approaches to parsing +input have been discussed. Each major implementation will throw an +exception if it is not 'well-formed'. The +`FixedLengthTokenizer` will throw an exception if a +range of data is missing. Similarly, attempting to access an index in a +`RowMapper` of `FieldSetMapper` +that doesn't exist or is in a different format than the one expected will +cause an exception to be thrown. All of these types of exceptions will be +thrown before read returns. However, they don't +address the issue of whether or not the returned item is valid. For +example, if one of the fields is an age, it obviously cannot be negative. +It will parse correctly, because it existed and is a number, but it won't +cause an exception. Since there are already a plethora of Validation +frameworks, Spring Batch does not attempt to provide yet another, but +rather provides a very simple interface that can be implemented by any +number of frameworks: + + +[source, java] +---- +public interface Validator { + + void validate(Object value) throws ValidationException; + +} +---- + +The contract is that the `validate` method +will throw an exception if the object is invalid, and return normally if +it is valid. Spring Batch provides an out of the box +`ItemProcessor`: + + +[source, xml] +---- + + + + + + + + + + 0 AND ? <= 9999999999 : 'Incorrect order ID' : 'error.order.id' } + { totalLines : ? = size(lineItems) : 'Bad count of order lines' + : 'error.order.lines.badcount'} + { customer.registered : customer.businessCustomer = FALSE OR ? = TRUE + : 'Business customer must be registered' + : 'error.customer.registration'} + { customer.companyName : customer.businessCustomer = FALSE OR ? HAS TEXT + : 'Company name for business customer is mandatory' + :'error.customer.companyname'} + ]]> + + + + + +---- + +This simple example shows a simple +`ValangValidator` that is used to validate an order +object. The intent is not to show Valang functionality as much as to show +how a validator could be added. + +[[process-indicator]] + + +=== Preventing State Persistence + +By default, all of the `ItemReader` and +`ItemWriter` implementations store their current +state in the `ExecutionContext` before it is +committed. However, this may not always be the desired behavior. For +example, many developers choose to make their database readers +'rerunnable' by using a process indicator. An extra column is added to the +input data to indicate whether or not it has been processed. When a +particular record is being read (or written out) the processed flag is +flipped from false to true. The SQL statement can then contain an extra +statement in the where clause, such as "where PROCESSED_IND = false", +thereby ensuring that only unprocessed records will be returned in the +case of a restart. In this scenario, it is preferable to not store any +state, such as the current row number, since it will be irrelevant upon +restart. For this reason, all readers and writers include the 'saveState' +property: + + +[source, xml] +---- + + + + + + + + + SELECT games.player_id, games.year_no, SUM(COMPLETES), + SUM(ATTEMPTS), SUM(PASSING_YARDS), SUM(PASSING_TD), + SUM(INTERCEPTIONS), SUM(RUSHES), SUM(RUSH_YARDS), + SUM(RECEPTIONS), SUM(RECEPTIONS_YARDS), SUM(TOTAL_TD) + from games, players where players.player_id = + games.player_id group by games.player_id, games.year_no + + + +---- + +The `ItemReader` configured above will not make +any entries in the `ExecutionContext` for any +executions in which it participates. + +[[customReadersWriters]] + +=== Creating Custom ItemReaders and ItemWriters + +So far in this chapter the basic contracts that exist for reading +and writing in Spring Batch and some common implementations have been +discussed. However, these are all fairly generic, and there are many +potential scenarios that may not be covered by out of the box +implementations. This section will show, using a simple example, how to +create a custom `ItemReader` and +`ItemWriter` implementation and implement their +contracts correctly. The `ItemReader` will also +implement `ItemStream`, in order to illustrate how to +make a reader or writer restartable. + +[[customReader]] + +==== Custom ItemReader Example + +For the purpose of this example, a simple +`ItemReader` implementation that reads from a +provided list will be created. We'll start out by implementing the most +basic contract of `ItemReader`, +`read`: + + +[source, java] +---- +public class CustomItemReader implements ItemReader{ + + List items; + + public CustomItemReader(List items) { + this.items = items; + } + + public T read() throws Exception, UnexpectedInputException, + NoWorkFoundException, ParseException { + + if (!items.isEmpty()) { + return items.remove(0); + } + return null; + } +} +---- + +This very simple class takes a list of items, and returns them one +at a time, removing each from the list. When the list is empty, it +returns null, thus satisfying the most basic requirements of an +`ItemReader`, as illustrated below: + + +[source, java] +---- +List items = new ArrayList(); +items.add("1"); +items.add("2"); +items.add("3"); + +ItemReader itemReader = new CustomItemReader(items); +assertEquals("1", itemReader.read()); +assertEquals("2", itemReader.read()); +assertEquals("3", itemReader.read()); +assertNull(itemReader.read()); +---- + +[[restartableReader]] + + +===== Making the ItemReader Restartable + +The final challenge now is to make the +`ItemReader` restartable. Currently, if the power +goes out, and processing begins again, the +`ItemReader` must start at the beginning. This is +actually valid in many scenarios, but it is sometimes preferable that +a batch job starts where it left off. The key discriminant is often +whether the reader is stateful or stateless. A stateless reader does +not need to worry about restartability, but a stateful one has to try +and reconstitute its last known state on restart. For this reason, we +recommend that you keep custom readers stateless if possible, so you +don't have to worry about restartability. + +If you do need to store state, then the +`ItemStream` interface should be used: + + +[source, java] +---- +public class CustomItemReader implements ItemReader, ItemStream { + + List items; + int currentIndex = 0; + private static final String CURRENT_INDEX = "current.index"; + + public CustomItemReader(List items) { + this.items = items; + } + + public T read() throws Exception, UnexpectedInputException, + ParseException { + + if (currentIndex < items.size()) { + return items.get(currentIndex++); + } + + return null; + } + + public void open(ExecutionContext executionContext) throws ItemStreamException { + if(executionContext.containsKey(CURRENT_INDEX)){ + currentIndex = new Long(executionContext.getLong(CURRENT_INDEX)).intValue(); + } + else{ + currentIndex = 0; + } + } + + public void update(ExecutionContext executionContext) throws ItemStreamException { + executionContext.putLong(CURRENT_INDEX, new Long(currentIndex).longValue()); + } + + public void close() throws ItemStreamException {} +} +---- + +On each call to the `ItemStream` +`update` method, the current index of the +`ItemReader` will be stored in the provided +`ExecutionContext` with a key of 'current.index'. +When the `ItemStream` `open` +method is called, the `ExecutionContext` is +checked to see if it contains an entry with that key. If the key is +found, then the current index is moved to that location. This is a +fairly trivial example, but it still meets the general +contract: + + +[source, java] +---- +ExecutionContext executionContext = new ExecutionContext(); +((ItemStream)itemReader).open(executionContext); +assertEquals("1", itemReader.read()); +((ItemStream)itemReader).update(executionContext); + +List items = new ArrayList(); +items.add("1"); +items.add("2"); +items.add("3"); +itemReader = new CustomItemReader(items); + +((ItemStream)itemReader).open(executionContext); +assertEquals("2", itemReader.read()); +---- + +Most `ItemReaders` have much more sophisticated restart logic. The +`JdbcCursorItemReader`, for example, stores the +row id of the last processed row in the Cursor. + +It is also worth noting that the key used within the +`ExecutionContext` should not be trivial. That is +because the same `ExecutionContext` is used for +all `ItemStreams` within a +`Step`. In most cases, simply prepending the key +with the class name should be enough to guarantee uniqueness. However, +in the rare cases where two of the same type of +`ItemStream` are used in the same step (which can +happen if two files are need for output) then a more unique name will +be needed. For this reason, many of the Spring Batch +`ItemReader` and +`ItemWriter` implementations have a +`setName()` property that allows this key name +to be overridden. + +[[customWriter]] + + +==== Custom ItemWriter Example + +Implementing a Custom `ItemWriter` is similar +in many ways to the `ItemReader` example above, but +differs in enough ways as to warrant its own example. However, adding +restartability is essentially the same, so it won't be covered in this +example. As with the `ItemReader` example, a +`List` will be used in order to keep the example as +simple as possible: + + +[source, java] +---- +public class CustomItemWriter implements ItemWriter { + + List output = TransactionAwareProxyFactory.createTransactionalList(); + + public void write(List items) throws Exception { + output.addAll(items); + } + + public List getOutput() { + return output; + } +} +---- + +[[restartableWriter]] + + +===== Making the ItemWriter Restartable + +To make the `ItemWriter` restartable we would follow the same +process as for the `ItemReader`, adding and +implementing the `ItemStream` interface to +synchronize the execution context. In the example we might have to +count the number of items processed and add that as a footer record. +If we needed to do that, we could implement +`ItemStream` in our +`ItemWriter` so that the counter was +reconstituted from the execution context if the stream was +re-opened. + +In many realistic cases, custom `ItemWriters` also delegate to +another writer that itself is restartable (e.g. when writing to a +file), or else it writes to a transactional resource so doesn't need +to be restartable because it is stateless. When you have a stateful +writer you should probably also be sure to implement +`ItemStream` as well as +`ItemWriter`. Remember also that the client of +the writer needs to be aware of the `ItemStream`, +so you may need to register it as a stream in the configuration +xml. + +[[itemReaderAndWriterImplementations]] +=== Item Reader and Writer Implementations +In this section we will introduce you to Reader and Writers that have not +already been discussed in the previous sections. + +[[decorators]] +==== Decorators + +In some cases a user needs a specialized behavior to be appended to a +pre-existing ItemReader. Spring Batch offers some out of the box decorators +that can add additional behavior to to your `ItemReaders` and `ItemWriters`. + +[[synchronizedItemStreamReader]] +===== SynchronizedItemStreamReader +When using a `ItemReader` that is not thread safe, Spring Batch offers the +`SynchronizedItemStreamReader` decorator that can be used to make the `ItemReader` + thread safe. Spring Batch provides a +`SynchronizedItemStreamReaderBuilder` to construct an instance of the +`SynchronizedItemStreamReader`. + +[[singleItemPeekableItemReader]] +===== SingleItemPeekableItemReader +A decorator that adds a peek method to an `ItemReader`. +This peek method allow the user to peek one item ahead. Repeated calls to the +peek will return the same item, and this will be the next item returned from read method. +Spring Batch provides a `SingleItemPeekableItemReaderBuilder` to construct an +instance of the `SingleItemPeekableItemReader`. + +NOTE: SingleItemPeekableItemReader's peek method is not thread-safe: +it wouldn't be possible to honour the peek in multiple threads because only one +of the threads that peeked would get that item in the next call to read. + +[[multiResourceItemWriter]] +===== MultiResourceItemWriter +The MultiResourceItemWriter wraps a `ResourceAwareItemWriterItemStream` and +creates a new output resource when the count of items written in current +resource exceeds the `itemCountLimitPerResource`. +Spring Batch provides a `MultiResourceItemWriterBuilder` to construct an +instance of the `MultiResourceItemWriter`. + + +[[messagingReadersAndWriters]] +==== Messaging Readers And Writers +Spring Batch offers readers and writers to some commonly used messaging systems. + +[[amqpItemReader]] +===== AmqpItemReader +The `AmqpItemReader` is an `ItemReader` that uses an `AmqpTemplate` to receive and/or +convert messages from an exchange. Spring Batch provides a `AmqpItemReaderBuilder` +to construct an instance of the `AmqpItemReader`. + +[[amqpItemWriter]] +===== AmqpItemWriter +The `AmqpItemWriter` is an `ItemWriter` that uses an `AmqpTemplate` to +send messages to an AMQP exchange. Messages will be sent to the nameless exchange if +not specified on the provided `AmqpTemplate`. Spring Batch provides a `AmqpItemWriterBuilder` +to construct an instance of the `AmqpItemWriter`. + + +[[jmsItemReader]] +===== JmsItemReader +The `JmsItemReader` is an `ItemReader` for JMS that uses an `JmsTemplate`. The template +should have a default destination, which will be used to provide items +for the `read()` method. +Spring Batch provides a `JmsItemReaderBuilder` to construct an instance of the `JmsItemReader`. + +[[jmsItemWriter]] +===== JmsItemWriter +The `JmsItemWriter` is an `ItemWriter` for JMS that uses an `JmsTemplate`. The template +should have a default destination, which will be used to send items in `write(List)`. +Spring Batch provides a `JmsItemWriterBuilder` to construct an instance of the `JmsItemWriter`. + + +[[databaseReaders]] +==== Database Readers +Here are the database readers offered by Spring Batch out of the box. + +[[Neo4jItemReader]] +===== Neo4jItemReader +The `Neo4jItemReader` is an `ItemReader` that reads objects from the graph database Neo4j via a paging technique. +Spring Batch provides a `Neo4jItemReaderBuilder` to construct an instance of the `Neo4jItemReader`. + +[[mongoItemReader]] +===== MongoItemReader +The `MongoItemReader` is an `ItemReader` that reads documents from MongoDB via a paging technique. +Spring Batch provides a `MongoItemReaderBuilder` to construct an instance of the `MongoItemReader`. + +[[hibernateCursorItemReader]] +===== HibernateCursorItemReader +The `HibernateCursorItemReader` is an `ItemStreamReader` for reading database +records built on top of Hibernate. It executes the HQL query, then when initialized, +iterates over the result set as the `read()` method is called, returning an object +corresponding to the current row. +Spring Batch provides a `HibernateCursorItemReaderBuilder` to construct an instance of the `HibernateCursorItemReader`. + + +[[hibernatePagingItemReader]] +===== HibernatePagingItemReader +The `HibernatePagingItemReader` is an `ItemReader` for reading database records +built on top of Hibernate and reading only up to a fixed number of items at a time. +Spring Batch provides a `HibernatePagingItemReaderBuilder` to construct an instance of the `HibernatePagingItemReader`. + + +[[repositoryItemReader]] +===== RepositoryItemReader +The `RepositoryItemReader` is an `ItemReader` that reads records utilizing +a `PagingAndSortingRepository`. +Spring Batch provides a `RepositoryItemReaderBuilder` to construct an instance +of the `RepositoryItemReader`. + +[[databaseWriters]] +==== Database Writers +Here are the database writers offered by Spring Batch out of the box. + +[[neo4jItemWriter]] +===== Neo4jItemWriter +The `Neo4jItemWriter` is an `ItemWriter` implementation that writes to a Neo4j database. +Spring Batch provides a `Neo4jItemWriterBuilder` to construct an instance +of the `Neo4jItemWriter`. + +[[mongoItemWriter]] +===== MongoItemWriter +The `MongoItemWriter` is an `ItemWriter` implementation that writes to a +MongoDB store using an implementation of Spring Data's `MongoOperations`. +Spring Batch provides a `MongoItemWriterBuilder` to construct an instance +of the `MongoItemWriter`. + +[[repositoryItemWriter]] +===== RepositoryItemWriter +The `RepositoryItemWriter` is an `ItemWriter` wrapper for a `CrudRepository` from Spring Data. +Spring Batch provides a `RepositoryItemWriterBuilder` to construct an instance +of the `RepositoryItemWriter`. + +[[hibernateItemWriter]] +===== HibernateItemWriter +The `HibernateItemWriter` is an `ItemWriter` that uses a Hibernate session to save or update entities +that are not part of the current Hibernate session. +Spring Batch provides a `HibernateItemWriterBuilder` to construct an instance +of the `HibernateItemWriter`. + +[[jdbcBatchItemWriter]] +===== JdbcBatchItemWriter +The `JdbcBatchItemWriter` is an `ItemWriter` that uses the batching features from +`NamedParameterJdbcTemplate` to execute a batch of statements for all items +provided. +Spring Batch provides a `JdbcBatchItemWriterBuilder` to construct an instance +of the `JdbcBatchItemWriter`. + +[[jpaItemWriter]] +===== JpaItemWriter +The `JpaItemWriter` is an `ItemWriter` that is using a JPA EntityManagerFactory +to merge any Entities that aren't part of the persistence context. +Spring Batch provides a `JpaItemWriterBuilder` to construct an instance +of the `JpaItemWriter`. + +[[specializedReaders]] +==== Specialized Readers +Here are some specialized readers offered by Spring Batch out of the box. + +[[ldifReader]] +===== LdifReader +The `LdifReader` reads LDIF (LDAP Data Interchange Format) records from a `Resource`, parses them +and returns a `LdapAttribute` object for each `read` executed. +Spring Batch provides a `LdifReaderBuilder` to construct an instance of the `LdifReader`. + + +[[mappingLdifReader]] +===== MappingLdifReader +The `MappingLdifReader` reads LDIF (LDAP Data Interchange Format) records from a `Resource`, parses them +then maps each LDIF record to a POJO (Plain Old Java Object). Each read returns a POJO. +Spring Batch provides a `MappingLdifReaderBuilder` to construct an instance of the `MappingLdifReader`. + +[[specializedWriters]] +==== Specialized Writers +Here are some specialized writers offered by Spring Batch out of the box. + +[[classifierCompositeItemWriter]] +===== ClassifierCompositeItemWriter +The `ClassifierCompositeItemWriter` calls one of a collection of ItemWriters for +each item, based on a router pattern implemented through the provided +`Classifier`. The implementation is thread-safe if all delegates are thread-safe. +Spring Batch provides a `ClassifierCompositeItemWriterBuilder` to construct an +instance of the `ClassifierCompositeItemWriter`. + +[[simpleMailMessageItemWriter]] +===== SimpleMailMessageItemWriter +The SimpleMailMessageItemWriter is an `ItemWriter` that can send mail messages. +It delegates the actual sending of messages to an instance of `MailSender`. +Spring Batch provides a `SimpleMailMessageItemWriterBuilder` to construct an +instance of the `SimpleMailMessageItemWriter`. + + +[[gemfireItemWriter]] +===== GemfireItemWriter +The GemfireItemWriter is an `ItemWriter` that uses an `GemfireTemplate` that +stores items in GemFire as key/value pairs. +Spring Batch provides a `GemfireItemWriterBuilder` to construct an +instance of the `GemfireItemWriter`. + +[[specializedProcessors]] +==== Specialized Processors +Here are some specialized processors offered by Spring Batch out of the box. + +[[scriptItemProcessor]] +===== ScriptItemProcessor +The `ScriptItemProcessor` is an `ItemProcessor` that passes the current item to +process to the provided script and the result of the script is returned by the processor. +Spring Batch provides a `ScriptItemProcessorBuilder` to construct an +instance of the `ScriptItemProcessor`. + +[[classifierCompositeItemProcessor]] +===== ClassifierCompositeItemProcessor +The `ClassifierCompositeItemProcessor` is an `ItemProcessor` that calls one of a collection +of ItemProcessors, based on a router pattern implemented through the provided +`Classifier`. +Spring Batch provides a `ClassifierCompositeItemProcessorBuilder` to construct an +instance of the `ClassifierCompositeItemProcessor`. diff --git a/spring-batch-docs/asciidoc/repeat.adoc b/spring-batch-docs/asciidoc/repeat.adoc new file mode 100644 index 000000000..8183b9a21 --- /dev/null +++ b/spring-batch-docs/asciidoc/repeat.adoc @@ -0,0 +1,308 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[repeat]] + +== Repeat + +[[repeatTemplate]] + + +=== RepeatTemplate + +Batch processing is about repetitive actions - either as a simple + optimization, or as part of a job. To strategize and generalize the + repetition as well as to provide what amounts to an iterator framework, + Spring Batch has the `RepeatOperations` interface. + The `RepeatOperations` interface looks like + this: + + +[source, java] +---- +public interface RepeatOperations { + + RepeatStatus iterate(RepeatCallback callback) throws RepeatException; + +} +---- + +The callback is a simple interface that allows you to insert + some business logic to be repeated: + + +[source, java] +---- +public interface RepeatCallback { + + RepeatStatus doInIteration(RepeatContext context) throws Exception; + +} +---- + +The callback is executed repeatedly until the implementation + decides that the iteration should end. The return value in these + interfaces is an enumeration that can either be + `RepeatStatus.CONTINUABLE` or + `RepeatStatus.FINISHED`. A `RepeatStatus` + conveys information to the caller of the repeat operations about whether + there is any more work to do. Generally speaking, implementations of + `RepeatOperations` should inspect the + `RepeatStatus` and use it as part of the decision to + end the iteration. Any callback that wishes to signal to the caller that + there is no more work to do can return + `RepeatStatus.FINISHED`. + +The simplest general purpose implementation of + `RepeatOperations` is + `RepeatTemplate`. It could be used like this: + + +[source, java] +---- +RepeatTemplate template = new RepeatTemplate(); + +template.setCompletionPolicy(new FixedChunkSizeCompletionPolicy(2)); + +template.iterate(new RepeatCallback() { + + public ExitStatus doInIteration(RepeatContext context) { + // Do stuff in batch... + return ExitStatus.CONTINUABLE; + } + +}); +---- + +In the example we return `RepeatStatus.CONTINUABLE` to + show that there is more work to do. The callback can also return + `ExitStatus.FINISHED` if it wants to signal to the caller that + there is no more work to do. Some iterations can be terminated by + considerations intrinsic to the work being done in the callback, others + are effectively infinite loops as far as the callback is concerned and the + completion decision is delegated to an external policy as in the case + above. + +[[repeatContext]] + + +==== RepeatContext + +The method parameter for the `RepeatCallback` + is a `RepeatContext`. Many callbacks will simply + ignore the context, but if necessary it can be used as an attribute bag + to store transient data for the duration of the iteration. After the + `iterate` method returns, the context will no + longer exist. + +A `RepeatContext` will have a parent context + if there is a nested iteration in progress. The parent context is + occasionally useful for storing data that need to be shared between + calls to `iterate`. This is the case for instance + if you want to count the number of occurrences of an event in the + iteration and remember it across subsequent calls. + +[[repeatStatus]] + + +==== RepeatStatus + +`RepeatStatus` is an enumeration used by + Spring Batch to indicate whether processing has finished. These are + possible `RepeatStatus` values: + +.ExitStatus Properties + +|=============== +|__Value__|__Description__ +|CONTINUABLE|There is more work to do. +|FINISHED|No more repetitions should take place. + +|=============== + + +`RepeatStatus` values can also be combined + with a logical AND operation using the `and()` + method in `RepeatStatus`. The effect of this is to + do a logical AND on the continuable flag. In other words, if either + status is `FINISHED`, then the result will be + `FINISHED`. + +[[completionPolicies]] + + +=== Completion Policies + +Inside a `RepeatTemplate` the termination of + the loop in the `iterate` method is determined by a + `CompletionPolicy` which is also a factory for the + `RepeatContext`. The + `RepeatTemplate` has the responsibility to use the + current policy to create a `RepeatContext` and pass + that in to the `RepeatCallback` at every stage in the + iteration. After a callback completes its + `doInIteration`, the + `RepeatTemplate` has to make a call to the + `CompletionPolicy` to ask it to update its state + (which will be stored in the `RepeatContext`). Then + it asks the policy if the iteration is complete. + +Spring Batch provides some simple general purpose implementations of + `CompletionPolicy`. The + `SimpleCompletionPolicy` just allows an execution up + to a fixed number of times (with `RepeatStatus.FINISHED` + forcing early completion at any time). + +Users might need to implement their own completion policies for more + complicated decisions. For example, a batch processing window that + prevents batch jobs from executing once the online systems are in use + would require a custom policy. + +[[repeatExceptionHandling]] + + +=== Exception Handling + +If there is an exception thrown inside a + `RepeatCallback`, the + `RepeatTemplate` consults an + `ExceptionHandler` which can decide whether or not to + re-throw the exception. + + +[source, java] +---- +public interface ExceptionHandler { + + void handleException(RepeatContext context, Throwable throwable) + throws RuntimeException; + +} +---- + +A common use case is to count the number of exceptions of a + given type, and fail when a limit is reached. For this purpose Spring + Batch provides the `SimpleLimitExceptionHandler` and + slightly more flexible + `RethrowOnThresholdExceptionHandler`. The + `SimpleLimitExceptionHandler` has a limit property + and an exception type that should be compared with the current exception - + all subclasses of the provided type are also counted. Exceptions of the + given type are ignored until the limit is reached, and then rethrown. + Those of other types are always rethrown. + +An important optional property of the + `SimpleLimitExceptionHandler` is the boolean flag + `useParent`. It is false by default, so the limit is only + accounted for in the current `RepeatContext`. When + set to true, the limit is kept across sibling contexts in a nested + iteration (e.g. a set of chunks inside a step). + +[[repeatListeners]] + + +=== Listeners + +Often it is useful to be able to receive additional callbacks for + cross cutting concerns across a number of different iterations. For this + purpose Spring Batch provides the `RepeatListeners` + interface. The `RepeatTemplate` allows users to + register `RepeatListeners`, and they will be given + callbacks with the `RepeatContext` and + `RepeatStatus` where available during the + iteration. + +The interface looks like this: + + +[source, java] +---- +public interface RepeatListener { + void before(RepeatContext context); + void after(RepeatContext context, RepeatStatus result); + void open(RepeatContext context); + void onError(RepeatContext context, Throwable e); + void close(RepeatContext context); +} +---- + +The `open` and `close` callbacks come before and after the entire + iteration. `before`, `after` + and `onError` apply to the individual + `RepeatCallback` calls. + +Note that when there is more than one listener, they are in a list, + so there is an order. In this case `open` and + `before` are called in the same order while + `after`, `onError` and + `close` are called in reverse order. + +[[repeatParallelProcessing]] + + +=== Parallel Processing + +Implementations of `RepeatOperations` are not + restricted to executing the callback sequentially. It is quite important + that some implementations are able to execute their callbacks in parallel. + To this end, Spring Batch provides the + `TaskExecutorRepeatTemplate`, which uses the Spring + `TaskExecutor` strategy to run the + `RepeatCallback`. The default is to use a + `SynchronousTaskExecutor`, which has the effect of + executing the whole iteration in the same thread (the same as a normal + `RepeatTemplate`). + +[[declarativeIteration]] + + +=== Declarative Iteration + +Sometimes there is some business processing that you know you want + to repeat every time it happens. The classic example of this is the + optimization of a message pipeline - it is more efficient to process a + batch of messages, if they are arriving frequently, than to bear the cost + of a separate transaction for every message. Spring Batch provides an AOP + interceptor that wraps a method call in a + `RepeatOperations` for just this purpose. The + `RepeatOperationsInterceptor` executes the + intercepted method and repeats according to the + `CompletionPolicy` in the provided + `RepeatTemplate`. + +Here is an example of declarative iteration using the Spring AOP + namespace to repeat a service call to a method called + processMessage (for more detail on how to + configure AOP interceptors see the Spring User Guide): + + +[source, xml] +---- + + + + + + +---- + +The example above uses a default + `RepeatTemplate` inside the interceptor. To change + the policies, listeners etc. you only need to inject an instance of + `RepeatTemplate` into the interceptor. + +If the intercepted method returns `void` then the + interceptor always returns `ExitStatus.CONTINUABLE` (so there is a danger of + an infinite loop if the `CompletionPolicy` does not + have a finite end point). Otherwise it returns + `ExitStatus.CONTINUABLE` until the return value from the + intercepted method is null, at which point it returns + `ExitStatus.FINISHED`. So the business logic inside the target + method can signal that there is no more work to do by returning + `null`, or by throwing an exception that is re-thrown by the + `ExceptionHandler` in the provided + `RepeatTemplate`. + diff --git a/spring-batch-docs/asciidoc/retry.adoc b/spring-batch-docs/asciidoc/retry.adoc new file mode 100644 index 000000000..06068b458 --- /dev/null +++ b/spring-batch-docs/asciidoc/retry.adoc @@ -0,0 +1,425 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[retry]] + +== Retry + +[[retryTemplate]] + + +=== RetryTemplate + + +[NOTE] +==== +The retry functionality was pulled out of Spring Batch as of 2.2.0. + It is now part of a new library, Spring Retry. +==== + + +To make processing more robust and less prone to failure, sometimes + it helps to automatically retry a failed operation in case it might + succeed on a subsequent attempt. Errors that are susceptible to this kind + of treatment are transient in nature. For example a remote call to a web + service or RMI service that fails because of a network glitch or a + `DeadLockLoserException` in a database update may + resolve themselves after a short wait. To automate the retry of such + operations Spring Batch has the `RetryOperations` + strategy. The `RetryOperations` interface looks like + this: + + +[source, java] +---- +public interface RetryOperations { + + T execute(RetryCallback retryCallback) throws Exception; + + T execute(RetryCallback retryCallback, RecoveryCallback recoveryCallback) + throws Exception; + + T execute(RetryCallback retryCallback, RetryState retryState) + throws Exception, ExhaustedRetryException; + + T execute(RetryCallback retryCallback, RecoveryCallback recoveryCallback, + RetryState retryState) throws Exception; + +} +---- + +The basic callback is a simple interface that allows you to + insert some business logic to be retried: + + +[source, java] +---- +public interface RetryCallback { + + T doWithRetry(RetryContext context) throws Throwable; + +} +---- + +The callback is executed and if it fails (by throwing an + `Exception`), it will be retried until either it is + successful, or the implementation decides to abort. There are a number of + overloaded `execute` methods in the + `RetryOperations` interface dealing with various use + cases for recovery when all retry attempts are exhausted, and also with + retry state, which allows clients and implementations to store information + between calls (more on this later). + +The simplest general purpose implementation of + `RetryOperations` is + `RetryTemplate`. It could be used like this + + +[source, java] +---- +RetryTemplate template = new RetryTemplate(); + +TimeoutRetryPolicy policy = new TimeoutRetryPolicy(); +policy.setTimeout(30000L); + +template.setRetryPolicy(policy); + +Foo result = template.execute(new RetryCallback() { + + public Foo doWithRetry(RetryContext context) { + // Do stuff that might fail, e.g. webservice operation + return result; + } + +}); +---- + +In the example we execute a web service call and return the result + to the user. If that call fails then it is retried until a timeout is + reached. + +[[retryContext]] + + +==== RetryContext + +The method parameter for the `RetryCallback` + is a `RetryContext`. Many callbacks will simply + ignore the context, but if necessary it can be used as an attribute bag + to store data for the duration of the iteration. + +A `RetryContext` will have a parent context + if there is a nested retry in progress in the same thread. The parent + context is occasionally useful for storing data that need to be shared + between calls to `execute`. + +[[recoveryCallback]] + + +==== RecoveryCallback + +When a retry is exhausted the + `RetryOperations` can pass control to a different + callback, the `RecoveryCallback`. To use this + feature clients just pass in the callbacks together to the same method, + for example: + + +[source, java] +---- +Foo foo = template.execute(new RetryCallback() { + public Foo doWithRetry(RetryContext context) { + // business logic here + }, + new RecoveryCallback() { + Foo recover(RetryContext context) throws Exception { + // recover logic here + } +}); +---- + +If the business logic does not succeed before the template + decides to abort, then the client is given the chance to do some + alternate processing through the recovery callback. + +[[statelessRetry]] + + +==== Stateless Retry + +In the simplest case, a retry is just a while loop: the + `RetryTemplate` can just keep trying until it + either succeeds or fails. The `RetryContext` + contains some state to determine whether to retry or abort, but this + state is on the stack and there is no need to store it anywhere + globally, so we call this stateless retry. The distinction between + stateless and stateful retry is contained in the implementation of the + `RetryPolicy` (the + `RetryTemplate` can handle both). In a stateless + retry, the callback is always executed in the same thread on retry as + when it failed. + +[[statefulRetry]] + + +==== Stateful Retry + +Where the failure has caused a transactional resource to become + invalid, there are some special considerations. This does not apply to a + simple remote call because there is no transactional resource (usually), + but it does sometimes apply to a database update, especially when using + Hibernate. In this case it only makes sense to rethrow the exception + that called the failure immediately so that the transaction can roll + back and we can start a new valid one. + +In these cases a stateless retry is not good enough because the + re-throw and roll back necessarily involve leaving the + `RetryOperations.execute()` method and potentially losing the + context that was on the stack. To avoid losing it we have to introduce a + storage strategy to lift it off the stack and put it (at a minimum) in + heap storage. For this purpose Spring Batch provides a storage strategy + `RetryContextCache` which can be injected into the + `RetryTemplate`. The default implementation of the + `RetryContextCache` is in memory, using a simple + `Map`. Advanced usage with multiple processes in a + clustered environment might also consider implementing the + `RetryContextCache` with a cluster cache of some + sort (though, even in a clustered environment this might be + overkill). + +Part of the responsibility of the + `RetryOperations` is to recognize the failed + operations when they come back in a new execution (and usually wrapped + in a new transaction). To facilitate this, Spring Batch provides the + `RetryState` abstraction. This works in conjunction + with a special `execute` methods in the + `RetryOperations`. + +The way the failed operations are recognized is by identifying the + state across multiple invocations of the retry. To identify the state, + the user can provide an `RetryState` object that is + responsible for returning a unique key identifying the item. The + identifier is used as a key in the + `RetryContextCache`. + + +[WARNING] +==== +Be very careful with the implementation of + `Object.equals()` and `Object.hashCode()` in the + key returned by `RetryState`. The best advice is + to use a business key to identify the items. In the case of a JMS + message the message ID can be used. +==== + + +When the retry is exhausted there is also the option to handle the + failed item in a different way, instead of calling the + `RetryCallback` (which is presumed now to be likely + to fail). Just like in the stateless case, this option is provided by + the `RecoveryCallback`, which can be provided by + passing it in to the `execute` method of + `RetryOperations`. + +The decision to retry or not is actually delegated to a regular + `RetryPolicy`, so the usual concerns about limits + and timeouts can be injected there (see below). + +[[retryPolicies]] + + +=== Retry Policies + +Inside a `RetryTemplate` the decision to retry + or fail in the `execute` method is determined by a + `RetryPolicy` which is also a factory for the + `RetryContext`. The + `RetryTemplate` has the responsibility to use the + current policy to create a `RetryContext` and pass + that in to the `RetryCallback` at every attempt. + After a callback fails the `RetryTemplate` has to + make a call to the `RetryPolicy` to ask it to update + its state (which will be stored in the + `RetryContext`), and then it asks the policy if + another attempt can be made. If another attempt cannot be made (e.g. a + limit is reached or a timeout is detected) then the policy is also + responsible for handling the exhausted state. Simple implementations will + just throw `RetryExhaustedException` which will cause + any enclosing transaction to be rolled back. More sophisticated + implementations might attempt to take some recovery action, in which case + the transaction can remain intact. + + +[TIP] +==== +Failures are inherently either retryable or not - if the same + exception is always going to be thrown from the business logic, it + doesn't help to retry it. So don't retry on all exception types - try to + focus on only those exceptions that you expect to be retryable. It's not + usually harmful to the business logic to retry more aggressively, but + it's wasteful because if a failure is deterministic there will be time + spent retrying something that you know in advance is fatal. +==== + + +Spring Batch provides some simple general purpose implementations of + stateless `RetryPolicy`, for example a + `SimpleRetryPolicy`, and the + `TimeoutRetryPolicy` used in the example + above. + +The `SimpleRetryPolicy` just allows a retry on + any of a named list of exception types, up to a fixed number of times. It + also has a list of "fatal" exceptions that should never be retried, and + this list overrides the retryable list so that it can be used to give + finer control over the retry behavior: + + +[source, java] +---- +SimpleRetryPolicy policy = new SimpleRetryPolicy(); +// Set the max retry attempts +policy.setMaxAttempts(5); +// Retry on all exceptions (this is the default) +policy.setRetryableExceptions(new Class[] {Exception.class}); +// ... but never retry IllegalStateException +policy.setFatalExceptions(new Class[] {IllegalStateException.class}); + +// Use the policy... +RetryTemplate template = new RetryTemplate(); +template.setRetryPolicy(policy); +template.execute(new RetryCallback() { + public Foo doWithRetry(RetryContext context) { + // business logic here + } +}); +---- + +There is also a more flexible implementation called + `ExceptionClassifierRetryPolicy`, which allows the + user to configure different retry behavior for an arbitrary set of + exception types though the `ExceptionClassifier` + abstraction. The policy works by calling on the classifier to convert an + exception into a delegate `RetryPolicy`, so for + example, one exception type can be retried more times before failure than + another by mapping it to a different policy. + +Users might need to implement their own retry policies for more + customized decisions. For instance, if there is a well-known, + solution-specific, classification of exceptions into retryable and not + retryable. + +[[backoffPolicies]] + + +=== Backoff Policies + +When retrying after a transient failure it often helps to wait a bit + before trying again, because usually the failure is caused by some problem + that will only be resolved by waiting. If a + `RetryCallback` fails, the + `RetryTemplate` can pause execution according to the + `BackoffPolicy` in place. + + +[source, java] +---- +public interface BackoffPolicy { + + BackOffContext start(RetryContext context); + + void backOff(BackOffContext backOffContext) + throws BackOffInterruptedException; + +} +---- + +A `BackoffPolicy` is free to implement + the backOff in any way it chooses. The policies provided by Spring Batch + out of the box all use `Object.wait()`. A common use case is to + backoff with an exponentially increasing wait period, to avoid two retries + getting into lock step and both failing - this is a lesson learned from + the ethernet. For this purpose Spring Batch provides the + `ExponentialBackoffPolicy`. + +[[retryListeners]] + + +=== Listeners + +Often it is useful to be able to receive additional callbacks for + cross cutting concerns across a number of different retries. For this + purpose Spring Batch provides the `RetryListener` + interface. The `RetryTemplate` allows users to + register `RetryListeners`, and they will be given + callbacks with the `RetryContext` and + `Throwable` where available during the + iteration. + +The interface looks like this: + + +[source, java] +---- +public interface RetryListener { + + void open(RetryContext context, RetryCallback callback); + + void onError(RetryContext context, RetryCallback callback, Throwable e); + + void close(RetryContext context, RetryCallback callback, Throwable e); +} +---- + +The `open` and + `close` callbacks come before and after the entire + retry in the simplest case and `onError` applies to + the individual `RetryCallback` calls. The + `close` method might also receive a + `Throwable`; if there has been an error it is the + last one thrown by the `RetryCallback`. + +Note that when there is more than one listener, they are in a list, + so there is an order. In this case `open` will be + called in the same order while `onError` and + `close` will be called in reverse order. + +[[declarativeRetry]] + + +=== Declarative Retry + +Sometimes there is some business processing that you know you want + to retry every time it happens. The classic example of this is the remote + service call. Spring Batch provides an AOP interceptor that wraps a method + call in a `RetryOperations` for just this purpose. + The `RetryOperationsInterceptor` executes the + intercepted method and retries on failure according to the + `RetryPolicy` in the provided + `RepeatTemplate`. + +Here is an example of declarative iteration using the Spring AOP + namespace to repeat a service call to a method called + `remoteCall` (for more detail on how to configure + AOP interceptors see the Spring User Guide): + + +[source, xml] +---- + + + + + + +---- + +The example above uses a default + `RetryTemplate` inside the interceptor. To change the + policies or listeners, you only need to inject an instance of + `RetryTemplate` into the interceptor. + diff --git a/spring-batch-docs/asciidoc/scalability.adoc b/spring-batch-docs/asciidoc/scalability.adoc new file mode 100644 index 000000000..cdad620be --- /dev/null +++ b/spring-batch-docs/asciidoc/scalability.adoc @@ -0,0 +1,401 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[scalability]] + +== Scaling and Parallel Processing + +Many batch processing problems can be solved with single threaded, + single process jobs, so it is always a good idea to properly check if that + meets your needs before thinking about more complex implementations. Measure + the performance of a realistic job and see if the simplest implementation + meets your needs first: you can read and write a file of several hundred + megabytes in well under a minute, even with standard hardware. + +When you are ready to start implementing a job with some parallel + processing, Spring Batch offers a range of options, which are described in + this chapter, although some features are covered elsewhere. At a high level + there are two modes of parallel processing: single process, multi-threaded; + and multi-process. These break down into categories as well, as + follows: + + +* Multi-threaded Step (single process) + + +* Parallel Steps (single process) + + +* Remote Chunking of Step (multi process) + + +* Partitioning a Step (single or multi process) + +Next we review the single-process options first, and then the + multi-process options. + +[[multithreadedStep]] + + +=== Multi-threaded Step + +The simplest way to start parallel processing is to add a + `TaskExecutor` to your Step configuration, e.g. as an + attribute of the `tasklet`: + + +[source, xml] +---- + + ... + +---- + +In this example the taskExecutor is a reference to another bean + definition, implementing the `TaskExecutor` + interface. `TaskExecutor` is a standard Spring + interface, so consult the Spring User Guide for details of available + implementations. The simplest multi-threaded + `TaskExecutor` is a + `SimpleAsyncTaskExecutor`. + +The result of the above configuration will be that the Step + executes by reading, processing and writing each chunk of items + (each commit interval) in a separate thread of execution. Note + that this means there is no fixed order for the items to be + processed, and a chunk might contain items that are + non-consecutive compared to the single-threaded case. In addition + to any limits placed by the task executor (e.g. if it is backed by + a thread pool), there is a throttle limit in the tasklet + configuration which defaults to 4. You may need to increase this + to ensure that a thread pool is fully utilised, e.g. + + +[source, xml] +---- + ... + +---- + +Note also that there may be limits placed on concurrency by + any pooled resources used in your step, such as + a `DataSource`. Be sure to make the pool in + those resources at least as large as the desired number of + concurrent threads in the step. + +There are some practical limitations of using multi-threaded Steps + for some common Batch use cases. Many participants in a Step (e.g. readers + and writers) are stateful, and if the state is not segregated by thread, + then those components are not usable in a multi-threaded Step. In + particular most of the off-the-shelf readers and writers from Spring Batch + are not designed for multi-threaded use. It is, however, possible to work + with stateless or thread safe readers and writers, and there is a sample + (parallelJob) in the Spring Batch Samples that show the use of a process + indicator (see <>) to keep + track of items that have been processed in a database input table. + +Spring Batch provides some implementations of + ItemWriter and + `ItemReader`. Usually they say in the + Javadocs if they are thread safe or not, or what you have to do to + avoid problems in a concurrent environment. If there is no + information in Javadocs, you can check the implementation to see + if there is any state. If a reader is not thread safe, it may + still be efficient to use it in your own synchronizing delegator. + You can synchronize the call to `read()` and as + long as the processing and writing is the most expensive part of + the chunk your step may still complete much faster than in a + single threaded configuration. + + +[[scalabilityParallelSteps]] + + +=== Parallel Steps + +As long as the application logic that needs to be parallelized can + be split into distinct responsibilities, and assigned to individual steps + then it can be parallelized in a single process. Parallel Step execution + is easy to configure and use, for example, to execute steps + `(step1,step2)` in parallel with + `step3`, you could configure a flow like this: + + +[source, xml] +---- + + + + + + + + + + + + + + +---- + +The configurable "task-executor" attribute is used to specify which + `TaskExecutor` implementation should be used to execute the individual + flows. The default is `SyncTaskExecutor`, but an + asynchronous `TaskExecutor` is required to run the steps in parallel. Note + that the job will ensure that every flow in the split completes before + aggregating the exit statuses and transitioning. + +See the section on <> for more + detail. + +[[remoteChunking]] + + +=== Remote Chunking + +In Remote Chunking the Step processing is split across multiple + processes, communicating with each other through some middleware. Here is + a picture of the pattern in action: + +.Remote Chunking +image::{batch-asciidoc}images/remote-chunking.png[Remote Chunking, scaledwidth="60%"] + +The Master component is a single process, and the Slaves are + multiple remote processes. Clearly this pattern works best if the Master + is not a bottleneck, so the processing must be more expensive than the + reading of items (this is often the case in practice). + +The Master is just an implementation of a Spring Batch + Step, with the `ItemWriter` replaced with a generic + version that knows how to send chunks of items to the middleware as + messages. The Slaves are standard listeners for whatever middleware is + being used (e.g. with JMS they would be + `MesssageListeners`), and their role is to process + the chunks of items using a standard `ItemWriter` or + `ItemProcessor` plus + `ItemWriter`, through the + `ChunkProcessor` interface. One of the advantages of + using this pattern is that the reader, processor and writer components are + off-the-shelf (the same as would be used for a local execution of the + step). The items are divided up dynamically and work is shared through the + middleware, so if the listeners are all eager consumers, then load + balancing is automatic. + +The middleware has to be durable, with guaranteed delivery and + single consumer for each message. JMS is the obvious candidate, but other + options exist in the grid computing and shared memory product space (e.g. + Java Spaces). + +[[partitioning]] + + +=== Partitioning + +Spring Batch also provides an SPI for partitioning a `Step` execution + and executing it remotely. In this case the remote participants are simply + `Step` instances that could just as easily have been configured and used for + local processing. Here is a picture of the pattern in action: + +.Partitioning +image::{batch-asciidoc}images/partitioning-overview.png[Partitioning Overview, scaledwidth="60%"] + +The `Job` is executing on the left hand side as a sequence of `Steps`, + and one of the `Steps` is labelled as a Master. The Slaves in this picture + are all identical instances of a `Step`, which could in fact take the place + of the Master resulting in the same outcome for the `Job`. The Slaves are + typically going to be remote services, but could also be local threads of + execution. The messages sent by the Master to the Slaves in this pattern + do not need to be durable, or have guaranteed delivery: Spring Batch + meta-data in the JobRepository will ensure that + each Slave is executed once and only once for each `Job` execution. + +The SPI in Spring Batch consists of a special implementation of `Step` + (the `PartitionStep`), and two strategy interfaces + that need to be implemented for the specific environment. The strategy + interfaces are `PartitionHandler` and + `StepExecutionSplitter`, and their role is show in + the sequence diagram below: + +.Partitioning SPI +image::{batch-asciidoc}images/partitioning-spi.png[Partitioning SPI, scaledwidth="60%"] + +The `Step` on the right in this case is the "remote" Slave, so + potentially there are many objects and or processes playing this role, and + the `PartitionStep` is shown driving the execution. The `PartitionStep` + configuration looks like this: + + +[source, xml] +---- + + + + + +---- + +Similar to the multi-threaded step's throttle-limit + attribute, the grid-size attribute prevents the task executor from + being saturated with requests from a single step. + +There is a simple example which can be copied and extended in the + unit test suite for Spring Batch Samples (see + `*PartitionJob.xml` configuration). + +Spring Batch creates step executions for the partitions called + "step1:partition0", etc., so many people prefer to call the master step + "step1:master" for consistency. With Spring 3.0 you can do this using an + alias for the step (specifying the `name` attribute + instead of the `id`). + +[[partitionHandler]] + + +==== PartitionHandler + +The `PartitionHandler` is the component that + knows about the fabric of the remoting or grid environment. It is able + to send `StepExecution` requests to the remote + `Steps`, wrapped in some fabric-specific format, like a DTO. It does not + have to know how to split up the input data, or how to aggregate the + result of multiple `Step` executions. Generally speaking it probably also + doesn't need to know about resilience or failover, since those are + features of the fabric in many cases, and anyway Spring Batch always + provides restartability independent of the fabric: a failed `Job` can + always be restarted and only the failed `Steps` will be + re-executed. + +The `PartitionHandler` interface can have + specialized implementations for a variety of fabric types: e.g. simple + RMI remoting, EJB remoting, custom web service, JMS, Java Spaces, shared + memory grids (like Terracotta or Coherence), grid execution fabrics + (like GridGain). Spring Batch does not contain implementations for any + proprietary grid or remoting fabrics. + +Spring Batch does however provide a useful implementation of + `PartitionHandler` that executes `Steps` locally in + separate threads of execution, using the + `TaskExecutor` strategy from Spring. The + implementation is called + `TaskExecutorPartitionHandler`, and it is the + default for a step configured with the XML namespace as above. It can + also be configured explicitly like this: + + +[source, xml] +---- + + + + + + + + + +---- + +The `gridSize` determines the number of separate + step executions to create, so it can be matched to the size of the + thread pool in the `TaskExecutor`, or else it can + be set to be larger than the number of threads available, in which case + the blocks of work are smaller. + +The `TaskExecutorPartitionHandler` is quite + useful for IO intensive `Steps`, like copying large numbers of files or + replicating filesystems into content management systems. It can also be + used for remote execution by providing a `Step` implementation that is a + proxy for a remote invocation (e.g. using Spring Remoting). + +[[stepExecutionSplitter]] + + +==== Partitioner + +The `Partitioner` has a simpler responsibility: to generate + execution contexts as input parameters for new step executions only (no + need to worry about restarts). It has a single method: + + +[source, java] +---- +public interface Partitioner { + Map partition(int gridSize); +} +---- + +The return value from this method associates a unique name for + each step execution (the `String`), with input + parameters in the form of an `ExecutionContext`. + The names show up later in the Batch meta data as the step name in the + partitioned `StepExecutions`. The + `ExecutionContext` is just a bag of name-value + pairs, so it might contain a range of primary keys, or line numbers, or + the location of an input file. The remote `Step` + then normally binds to the context input using `#{...}` + placeholders (late binding in step scope), as illustrated in the next + section. + +The names of the step executions (the keys in the + `Map` returned by + `Partitioner`) need to be unique amongst the step + executions of a `Job`, but do not have any other specific requirements. + The easiest way to do this, and to make the names meaningful for users, + is to use a prefix+suffix naming convention, where the prefix is the + name of the step that is being executed (which itself is unique in the + `Job`), and the suffix is just a counter. There is + a `SimplePartitioner` in the framework that uses + this convention. + +An optional interface + `PartitioneNameProvider` can be used to + provide the partition names separately from the partitions + themselves. If a Partitioner implements + this interface then on a restart only the names will be queried. + If partitioning is expensive this can be a useful optimisation. + Obviously the names provided by the + `PartitioneNameProvider` must match those + provided by the `Partitioner`. + +[[bindingInputDataToSteps]] + + +==== Binding Input Data to Steps + +It is very efficient for the steps that are executed by the + `PartitionHandler` to have identical configuration, and for their input + parameters to be bound at runtime from the `ExecutionContext`. This is + easy to do with the StepScope feature of Spring Batch (covered in more + detail in the section on <>). For example + if the `Partitioner` creates + `ExecutionContext` instances with an attribute key + `fileName`, pointing to a different file (or + directory) for each step invocation, the + `Partitioner` output might look like this: + +.Example step execution name to execution context provided by `Partitioner` targeting directory processing + +|=============== +|__Step Execution Name (key)__|__ExecutionContext (value)__ +|filecopy:partition0|fileName=/home/data/one +|filecopy:partition1|fileName=/home/data/two +|filecopy:partition2|fileName=/home/data/three +|=============== + + +Then the file name can be bound to a step using late binding to + the execution context: + + +[source, xml] +---- + + + +---- + diff --git a/spring-batch-docs/asciidoc/schema-appendix.adoc b/spring-batch-docs/asciidoc/schema-appendix.adoc new file mode 100644 index 000000000..50906b6f5 --- /dev/null +++ b/spring-batch-docs/asciidoc/schema-appendix.adoc @@ -0,0 +1,578 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[metaDataSchema]] + +[appendix] +== Meta-Data Schema + +[[metaDataSchemaOverview]] + + +=== Overview + +The Spring Batch Meta-Data tables very closely match the Domain + objects that represent them in Java. For example, + `JobInstance`, `JobExecution`, + `JobParameters`, and + `StepExecution` map to BATCH_JOB_INSTANCE, + BATCH_JOB_EXECUTION, BATCH_JOB_EXECUTION_PARAMS, and BATCH_STEP_EXECUTION, + respectively. `ExecutionContext` maps to both + BATCH_JOB_EXECUTION_CONTEXT and BATCH_STEP_EXECUTION_CONTEXT. The + `JobRepository` is responsible for saving and storing + each Java object into its correct table. The following appendix describes + the meta-data tables in detail, along with many of the design decisions + that were made when creating them. When viewing the various table creation + statements below, it is important to realize that the data types used are + as generic as possible. Spring Batch provides many schemas as examples, + which all have varying data types due to variations in individual database + vendors' handling of data types. Below is an ERD model of all 6 tables and + their relationships to one another: + +.Spring Batch Meta-Data ERD +image::{batch-asciidoc}images/meta-data-erd.png[Spring Batch Meta-Data ERD, scaledwidth="60%"] + + +[[exampleDDLScripts]] + + +==== Example DDL Scripts + +The Spring Batch Core JAR file contains example + scripts to create the relational tables for a number of database + platforms (which are in turn auto-detected by the job repository factory + bean or namespace equivalent). These scripts can be used as is, or + modified with additional indexes and constraints as desired. The file + names are in the form `schema-\*.sql`, where "*" is the + short name of the target database platform. The scripts are in + the package `org.springframework.batch.core`. + +[[metaDataVersion]] + + +==== Version + +Many of the database tables discussed in this appendix contain a + version column. This column is important because Spring Batch employs an + optimistic locking strategy when dealing with updates to the database. + This means that each time a record is 'touched' (updated) the value in + the version column is incremented by one. When the repository goes back + to try and save the value, if the version number has change it will + throw `OptimisticLockingFailureException`, + indicating there has been an error with concurrent access. This check is + necessary since, even though different batch jobs may be running in + different machines, they are all using the same database tables. + +[[metaDataIdentity]] + + +==== Identity + +BATCH_JOB_INSTANCE, BATCH_JOB_EXECUTION, and BATCH_STEP_EXECUTION + each contain columns ending in _ID. These fields act as primary keys for + their respective tables. However, they are not database generated keys, + but rather they are generated by separate sequences. This is necessary + because after inserting one of the domain objects into the database, the + key it is given needs to be set on the actual object so that they can be + uniquely identified in Java. Newer database drivers (Jdbc 3.0 and up) + support this feature with database generated keys, but rather than + requiring it, sequences were used. Each variation of the schema will + contain some form of the following: + + +[source, sql] +---- +CREATE SEQUENCE BATCH_STEP_EXECUTION_SEQ; +CREATE SEQUENCE BATCH_JOB_EXECUTION_SEQ; +CREATE SEQUENCE BATCH_JOB_SEQ; +---- + +Many database vendors don't support sequences. In these cases, + work-arounds are used, such as the following for MySQL: + + +[source, sql] +---- +CREATE TABLE BATCH_STEP_EXECUTION_SEQ (ID BIGINT NOT NULL) type=InnoDB; +INSERT INTO BATCH_STEP_EXECUTION_SEQ values(0); +CREATE TABLE BATCH_JOB_EXECUTION_SEQ (ID BIGINT NOT NULL) type=InnoDB; +INSERT INTO BATCH_JOB_EXECUTION_SEQ values(0); +CREATE TABLE BATCH_JOB_SEQ (ID BIGINT NOT NULL) type=InnoDB; +INSERT INTO BATCH_JOB_SEQ values(0); +---- + +In the above case, a table is used in place of each sequence. The + Spring core class `MySQLMaxValueIncrementer` will + then increment the one column in this sequence in order to give similar + functionality. + +[[metaDataBatchJobInstance]] + + +=== BATCH_JOB_INSTANCE + +The BATCH_JOB_INSTANCE table holds all information relevant to a + `JobInstance`, and serves as the top of the overall + hierarchy. The following generic DDL statement is used to create + it: + + +[source, sql] +---- +CREATE TABLE BATCH_JOB_INSTANCE ( + JOB_INSTANCE_ID BIGINT PRIMARY KEY , + VERSION BIGINT, + JOB_NAME VARCHAR(100) NOT NULL , + JOB_KEY VARCHAR(2500) +); +---- + +Below are descriptions of each column in the table: + + +* JOB_INSTANCE_ID: The unique id that will identify the instance, + which is also the primary key. The value of this column should be + obtainable by calling the `getId` method on + `JobInstance`. + + +* VERSION: See above section. + + +* JOB_NAME: Name of the job obtained from the + `Job` object. Because it is required to identify + the instance, it must not be null. + + +* JOB_KEY: A serialization of the + `JobParameters` that uniquely identifies separate + instances of the same job from one another. + (`JobInstances` with the same job name must have + different `JobParameters`, and thus, different + JOB_KEY values). + +[[metaDataBatchJobParams]] + + +=== BATCH_JOB_EXECUTION_PARAMS + +The BATCH_JOB_EXECUTION_PARAMS table holds all information relevant to the + `JobParameters` object. It contains 0 or more + key/value pairs passed to a `Job` and serve as a record of the parameters + a job was run with. For each parameter that contributes to the generation of a job's identity, + the IDENTIFYING flag is set to true. It should be noted that the table has been + denormalized. Rather than creating a separate table for each type, there + is one table with a column indicating the type: + + +[source, sql] +---- +CREATE TABLE BATCH_JOB_EXECUTION_PARAMS ( + JOB_EXECUTION_ID BIGINT NOT NULL , + TYPE_CD VARCHAR(6) NOT NULL , + KEY_NAME VARCHAR(100) NOT NULL , + STRING_VAL VARCHAR(250) , + DATE_VAL DATETIME DEFAULT NULL , + LONG_VAL BIGINT , + DOUBLE_VAL DOUBLE PRECISION , + IDENTIFYING CHAR(1) NOT NULL , + constraint JOB_EXEC_PARAMS_FK foreign key (JOB_EXECUTION_ID) + references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) +); +---- + +Below are descriptions for each column: + + +* JOB_EXECUTION_ID: Foreign Key from the BATCH_JOB_EXECUTION table + that indicates the job execution the parameter entry belongs to. It + should be noted that multiple rows (i.e key/value pairs) may exist for + each execution. + + +* TYPE_CD: String representation of the type of value stored, + which can be either a string, date, long, or double. Because the type + must be known, it cannot be null. + + +* KEY_NAME: The parameter key. + + +* STRING_VAL: Parameter value, if the type is string. + + +* DATE_VAL: Parameter value, if the type is date. + + +* LONG_VAL: Parameter value, if the type is a long. + + +* DOUBLE_VAL: Parameter value, if the type is double. + + +* IDENTIFYING: Flag indicating if the parameter contributed to the identity of the related `JobInstance`. + +It is worth noting that there is no primary key for this table. This + is simply because the framework has no use for one, and thus doesn't + require it. If a user so chooses, one may be added with a database + generated key, without causing any issues to the framework itself. + +[[metaDataBatchJobExecution]] + + +=== BATCH_JOB_EXECUTION + +The BATCH_JOB_EXECUTION table holds all information relevant to the + `JobExecution` object. Every time a + `Job` is run there will always be a new + `JobExecution`, and a new row in this table: + + +[source, sql] +---- +CREATE TABLE BATCH_JOB_EXECUTION ( + JOB_EXECUTION_ID BIGINT PRIMARY KEY , + VERSION BIGINT, + JOB_INSTANCE_ID BIGINT NOT NULL, + CREATE_TIME TIMESTAMP NOT NULL, + START_TIME TIMESTAMP DEFAULT NULL, + END_TIME TIMESTAMP DEFAULT NULL, + STATUS VARCHAR(10), + EXIT_CODE VARCHAR(20), + EXIT_MESSAGE VARCHAR(2500), + LAST_UPDATED TIMESTAMP, + JOB_CONFIGURATION_LOCATION VARCHAR(2500) NULL, + constraint JOB_INSTANCE_EXECUTION_FK foreign key (JOB_INSTANCE_ID) + references BATCH_JOB_INSTANCE(JOB_INSTANCE_ID) +) ; +---- + +Below are descriptions for each column: + + +* JOB_EXECUTION_ID: Primary key that uniquely identifies this + execution. The value of this column is obtainable by calling the + `getId` method of the + `JobExecution` object. + + +* VERSION: See above section. + + +* JOB_INSTANCE_ID: Foreign key from the BATCH_JOB_INSTANCE table + indicating the instance to which this execution belongs. There may be + more than one execution per instance. + + +* CREATE_TIME: Timestamp representing the time that the execution + was created. + + +* START_TIME: Timestamp representing the time the execution was + started. + + +* END_TIME: Timestamp representing the time the execution was + finished, regardless of success or failure. An empty value in this + column even though the job is not currently running indicates that + there has been some type of error and the framework was unable to + perform a last save before failing. + + +* STATUS: Character string representing the status of the + execution. This may be COMPLETED, STARTED, etc. The object + representation of this column is the + `BatchStatus` enumeration. + + +* EXIT_CODE: Character string representing the exit code of the + execution. In the case of a command line job, this may be converted + into a number. + + +* EXIT_MESSAGE: Character string representing a more detailed + description of how the job exited. In the case of failure, this might + include as much of the stack trace as is possible. + + +* LAST_UPDATED: Timestamp representing the last time this + execution was persisted. + +[[metaDataBatchStepExecution]] + + +=== BATCH_STEP_EXECUTION + +The BATCH_STEP_EXECUTION table holds all information relevant to the + `StepExecution` object. This table is very similar in + many ways to the BATCH_JOB_EXECUTION table and there will always be at + least one entry per `Step` for each + `JobExecution` created: + + +[source, sql] +---- +CREATE TABLE BATCH_STEP_EXECUTION ( + STEP_EXECUTION_ID BIGINT PRIMARY KEY , + VERSION BIGINT NOT NULL, + STEP_NAME VARCHAR(100) NOT NULL, + JOB_EXECUTION_ID BIGINT NOT NULL, + START_TIME TIMESTAMP NOT NULL , + END_TIME TIMESTAMP DEFAULT NULL, + STATUS VARCHAR(10), + COMMIT_COUNT BIGINT , + READ_COUNT BIGINT , + FILTER_COUNT BIGINT , + WRITE_COUNT BIGINT , + READ_SKIP_COUNT BIGINT , + WRITE_SKIP_COUNT BIGINT , + PROCESS_SKIP_COUNT BIGINT , + ROLLBACK_COUNT BIGINT , + EXIT_CODE VARCHAR(20) , + EXIT_MESSAGE VARCHAR(2500) , + LAST_UPDATED TIMESTAMP, + constraint JOB_EXECUTION_STEP_FK foreign key (JOB_EXECUTION_ID) + references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) +) ; +---- + +Below are descriptions for each column: + + +* STEP_EXECUTION_ID: Primary key that uniquely identifies this + execution. The value of this column should be obtainable by calling + the `getId` method of the + `StepExecution` object. + + +* VERSION: See above section. + + +* STEP_NAME: The name of the step to which this execution + belongs. + + +* JOB_EXECUTION_ID: Foreign key from the BATCH_JOB_EXECUTION table + indicating the `JobExecution` to which this `StepExecution` belongs. There + may be only one `StepExecution` for a given + `JobExecution` for a given + `Step` name. + + +* START_TIME: Timestamp representing the time the execution was + started. + + +* END_TIME: Timestamp representing the time the execution was + finished, regardless of success or failure. An empty value in this + column even though the job is not currently running indicates that + there has been some type of error and the framework was unable to + perform a last save before failing. + + +* STATUS: Character string representing the status of the + execution. This may be COMPLETED, STARTED, etc. The object + representation of this column is the + `BatchStatus` enumeration. + + +* COMMIT_COUNT: The number of times in which the step has + committed a transaction during this execution. + + +* READ_COUNT: The number of items read during this + execution. + + +* FILTER_COUNT: The number of items filtered out of this + execution. + + +* WRITE_COUNT: The number of items written and committed during + this execution. + + +* READ_SKIP_COUNT: The number of items skipped on read during this + execution. + + +* WRITE_SKIP_COUNT: The number of items skipped on write during + this execution. + + +* PROCESS_SKIP_COUNT: The number of items skipped during + processing during this execution. + + +* ROLLBACK_COUNT: The number of rollbacks during this execution. + Note that this count includes each time rollback occurs, including + rollbacks for retry and those in the skip recovery procedure. + + +* EXIT_CODE: Character string representing the exit code of the + execution. In the case of a command line job, this may be converted + into a number. + + +* EXIT_MESSAGE: Character string representing a more detailed + description of how the job exited. In the case of failure, this might + include as much of the stack trace as is possible. + + +* LAST_UPDATED: Timestamp representing the last time this + execution was persisted. + +[[metaDataBatchJobExecutionContext]] + + +=== BATCH_JOB_EXECUTION_CONTEXT + +The BATCH_JOB_EXECUTION_CONTEXT table holds all information relevant + to an `Job's` + `ExecutionContext`. There is exactly one + `Job` `ExecutionContext` per + `JobExecution`, and it contains all of the job-level + data that is needed for a particular job execution. This data typically + represents the state that must be retrieved after a failure so that a + `JobInstance` can 'start from where it left + off'. + + +[source, sql] +---- +CREATE TABLE BATCH_JOB_EXECUTION_CONTEXT ( + JOB_EXECUTION_ID BIGINT PRIMARY KEY, + SHORT_CONTEXT VARCHAR(2500) NOT NULL, + SERIALIZED_CONTEXT CLOB, + constraint JOB_EXEC_CTX_FK foreign key (JOB_EXECUTION_ID) + references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) +) ; +---- + +Below are descriptions for each column: + + +* JOB_EXECUTION_ID: Foreign key representing the + `JobExecution` to which the context belongs. + There may be more than one row associated to a given execution. + + +* SHORT_CONTEXT: A string version of the + SERIALIZED_CONTEXT. + + +* SERIALIZED_CONTEXT: The entire context, serialized. + +[[metaDataBatchStepExecutionContext]] + + +=== BATCH_STEP_EXECUTION_CONTEXT + +The BATCH_STEP_EXECUTION_CONTEXT table holds all information + relevant to an `Step's` + `ExecutionContext`. There is exactly one + `ExecutionContext` per + `StepExecution`, and it contains all of the data that + needs to persisted for a particular step execution. This data typically + represents the state that must be retrieved after a failure so that a + `JobInstance` can 'start from where it left + off'. + + +[source, sql] +---- +CREATE TABLE BATCH_STEP_EXECUTION_CONTEXT ( + STEP_EXECUTION_ID BIGINT PRIMARY KEY, + SHORT_CONTEXT VARCHAR(2500) NOT NULL, + SERIALIZED_CONTEXT CLOB, + constraint STEP_EXEC_CTX_FK foreign key (STEP_EXECUTION_ID) + references BATCH_STEP_EXECUTION(STEP_EXECUTION_ID) +) ; +---- + +Below are descriptions for each column: + + +* STEP_EXECUTION_ID: Foreign key representing the + `StepExecution` to which the context belongs. + There may be more than one row associated to a given execution. + + +* SHORT_CONTEXT: A string version of the + SERIALIZED_CONTEXT. + + +* SERIALIZED_CONTEXT: The entire context, serialized. + +[[metaDataArchiving]] + + +=== Archiving + +Because there are entries in multiple tables every time a batch job + is run, it is common to create an archive strategy for the meta-data + tables. The tables themselves are designed to show a record of what + happened in the past, and generally won't affect the run of any job, with + a couple of notable exceptions pertaining to restart: + + +* The framework will use the meta-data tables to determine if a + particular `JobInstance` has been run before. If it has been run, and + the job is not restartable, then an exception will be thrown. + + +* If an entry for a `JobInstance` is removed without having + completed successfully, the framework will think that the job is new, + rather than a restart. + + +* If a job is restarted, the framework will use any data that has + been persisted to the `ExecutionContext` to restore the `Job's` state. + Therefore, removing any entries from this table for jobs that haven't + completed successfully will prevent them from starting at the correct + point if run again. + +[[multiByteCharacters]] + + +=== International and Multi-byte Characters + +If you are using multi-byte character sets (e.g. Chines or Cyrillic) + in your business processing, then those characters might need to be + persisted in the Spring Batch schema. Many users find that + simply changing the schema to double the length of the `VARCHAR` + columns is enough. Others prefer to configure the <> with `max-varchar-length` half the value of the `VARCHAR` column length is enough. Some users have also reported that + they use `NVARCHAR` in place of `VARCHAR` + in their schema definitions. The best result will depend on the database + platform and the way the database server has been configured locally. + +[[recommendationsForIndexingMetaDataTables]] + + +=== Recommendations for Indexing Meta Data Tables + +Spring Batch provides DDL samples for the meta-data tables in the + Core jar file for several common database platforms. Index declarations + are not included in that DDL because there are too many variations in how + users may want to index depending on their precise platform, local + conventions and also the business requirements of how the jobs will be + operated. The table below provides some indication as to which columns are + going to be used in a WHERE clause by the Dao implementations provided by + Spring Batch, and how frequently they might be used, so that individual + projects can make up their own minds about indexing. + +.Where clauses in SQL statements (excluding primary keys) and their approximate frequency of use. + +|=============== +|Default Table Name|Where Clause|Frequency +|BATCH_JOB_INSTANCE|JOB_NAME = ? and JOB_KEY = ?|Every time a job is launched +|BATCH_JOB_EXECUTION|JOB_INSTANCE_ID = ?|Every time a job is restarted +|BATCH_EXECUTION_CONTEXT|EXECUTION_ID = ? and KEY_NAME = ?|On commit interval, a.k.a. chunk +|BATCH_STEP_EXECUTION|VERSION = ?|On commit interval, a.k.a. chunk (and at start and end of + step) +|BATCH_STEP_EXECUTION|STEP_NAME = ? and JOB_EXECUTION_ID = ?|Before each step execution + +|=============== + + diff --git a/spring-batch-docs/asciidoc/spring-batch-integration.adoc b/spring-batch-docs/asciidoc/spring-batch-integration.adoc new file mode 100644 index 000000000..2aeeb93bd --- /dev/null +++ b/spring-batch-docs/asciidoc/spring-batch-integration.adoc @@ -0,0 +1,817 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[springBatchIntegration]] + +== Spring Batch Integration + +[[spring-batch-integration-introduction]] + +=== Spring Batch Integration Introduction + +Many users of Spring Batch may encounter requirements that are +outside the scope of Spring Batch, yet may be efficiently and +concisely implemented using Spring Integration. Conversely, Spring +Batch users may encounter Spring Batch requirements and need a way +to efficiently integrate both frameworks. In this context several +patterns and use-cases emerge and Spring Batch Integration will +address those requirements. + +The line between Spring Batch and Spring Integration is not always +clear, but there are guidelines that one can follow. Principally, +these are: think about granularity, and apply common patterns. Some +of those common patterns are described in this reference manual +section. + +Adding messaging to a batch process enables automation of +operations, and also separation and strategizing of key concerns. +For example a message might trigger a job to execute, and then the +sending of the message can be exposed in a variety of ways. Or when +a job completes or fails that might trigger a message to be sent, +and the consumers of those messages might have operational concerns +that have nothing to do with the application itself. Messaging can +also be embedded in a job, for example reading or writing items for +processing via channels. Remote partitioning and remote chunking +provide methods to distribute workloads over an number of workers. + + +Some key concepts that we will cover are: + +* <> + + + +* <> + + + +* <> + + + +* <> + + + +* <> + + +[[namespace-support]] + +==== Namespace Support + +Since Spring Batch Integration 1.3, dedicated XML Namespace +support was added, with the aim to provide an easier configuration +experience. In order to activate the namespace, add the following +namespace declarations to your Spring XML Application Context +file: + +[source, xml] +---- + + + ... + + +---- + +A fully configured Spring XML Application Context file for Spring +Batch Integration may look like the following: + +[source, xml] +---- + + + ... + + +---- + +Appending version numbers to the referenced XSD file is also +allowed but, as a version-less declaration will always use the +latest schema, we generally don't recommend appending the version +number to the XSD name. Adding a version number, for instance, +would create possibly issues when updating the Spring Batch +Integration dependencies as they may require more recent versions +of the XML schema. + + +[[launching-batch-jobs-through-messages]] + +==== Launching Batch Jobs through Messages + + +When starting batch jobs using the core Spring Batch API you +basically have 2 options: + +* Command line via the `CommandLineJobRunner` +* Programatically via either `JobOperator.start()` or `JobLauncher.run()`. + + + +For example, you may want to use the +`CommandLineJobRunner` when invoking Batch Jobs +using a shell script. Alternatively, you may use the +JobOperator directly, for example when using +Spring Batch as part of a web application. However, what about +more complex use-cases? Maybe you need to poll a remote (S)FTP +server to retrieve the data for the Batch Job. Or your application +has to support multiple different data sources simultaneously. For +example, you may receive data files not only via the web, but also +FTP etc. Maybe additional transformation of the input files is +needed before invoking Spring Batch. + + + +Therefore, it would be much more powerful to execute the batch job +using Spring Integration and its numerous adapters. For example, +you can use a __File Inbound Channel Adapter__ to +monitor a directory in the file-system and start the Batch Job as +soon as the input file arrives. Additionally you can create Spring +Integration flows that use multiple different adapters to easily +ingest data for your Batch Jobs from multiple sources +simultaneously using configuration only. Implementing all these +scenarios with Spring Integration is easy as it allow for an +decoupled event-driven execution of the +`JobLauncher`. + + + +Spring Batch Integration provides the +`JobLaunchingMessageHandler` class that you can +use to launch batch jobs. The input for the +`JobLaunchingMessageHandler` is provided by a +Spring Integration message, which payload is of type +JobLaunchRequest. This class is a wrapper around the Job + that needs to be launched as well as the JobParameters +necessary to launch the Batch job. + + + +The following image illustrates the typical Spring Integration +message flow in order to start a Batch job. The +link:$$http://www.eaipatterns.com/toc.html$$[EIP (Enterprise IntegrationPatterns) website] +provides a full overview of messaging icons and their descriptions. + +.Launch Batch Job +image::{batch-asciidoc}images/launch-batch-job.png[Launch Batch Job, scaledwidth="60%"] + + +[[transforming-a-file-into-a-joblaunchrequest]] + +===== Transforming a file into a JobLaunchRequest + + +[source, java] +---- +package io.spring.sbi; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobParametersBuilder; +import org.springframework.batch.integration.launch.JobLaunchRequest; +import org.springframework.integration.annotation.Transformer; +import org.springframework.messaging.Message; + +import java.io.File; + +public class FileMessageToJobRequest { + private Job job; + private String fileParameterName; + + public void setFileParameterName(String fileParameterName) { + this.fileParameterName = fileParameterName; + } + + public void setJob(Job job) { + this.job = job; + } + + @Transformer + public JobLaunchRequest toRequest(Message message) { + JobParametersBuilder jobParametersBuilder = + new JobParametersBuilder(); + + jobParametersBuilder.addString(fileParameterName, + message.getPayload().getAbsolutePath()); + + return new JobLaunchRequest(job, jobParametersBuilder.toJobParameters()); + } +} +---- + +[[the-jobexecution-response]] + +===== The JobExecution Response + +When a Batch Job is being executed, a +`JobExecution` instance is returned. This +instance can be used to determine the status of an execution. If +a `JobExecution` was able to be created +successfully, it will always be returned, regardless of whether +or not the actual execution was successful. + + + +The exact behavior on how the `JobExecution` +instance is returned depends on the provided +`TaskExecutor`. If a +`synchronous` (single-threaded) +`TaskExecutor` implementation is used, the +`JobExecution` response is only returned +`after` the job completes. When using an +`asynchronous` +`TaskExecutor`, the +`JobExecution` instance is returned +immediately. Users can then take the `id` of +`JobExecution` instance +(`JobExecution.getJobId()`) and query the +`JobRepository` for the job's updated status +using the `JobExplorer`. For more +information, please refer to the Spring +Batch reference documentation on +link:$$http://docs.spring.io/spring-batch/reference/html/configureJob.html#queryingRepository$$[Querying the Repository]. + + + +The following configuration will create a file +`inbound-channel-adapter` to listen for CSV +files in the provided directory, hand them off to our +transformer (`FileMessageToJobRequest`), +launch the job via the __Job Launching Gateway__ then simply log the output of the +`JobExecution` via the +`logging-channel-adapter`. + + +[[spring-batch-integration-configuration]] + +===== Spring Batch Integration Configuration + + +[source, xml] +---- + + + + + + + + + + + + + + + + + + +---- + + +Now that we are polling for files and launching jobs, we need to +configure for example our Spring Batch +`ItemReader` to utilize found file +represented by the job parameter "input.file.name": + +[[example-itemreader-configuration]] + +===== Example ItemReader Configuration + + +[source, xml] +---- + + + ... + +---- + + +The main points of interest here are injecting the value of +`#{jobParameters['input.file.name']}` +as the Resource property value and setting the `ItemReader` bean +to be of __Step scope__ to take advantage of +the late binding support which allows access to the +`jobParameters` variable. + + +[[availableAttributesOfTheJobLaunchingGateway]] +=== Available Attributes of the Job-Launching Gateway + +* `id` Identifies the underlying Spring bean definition, which is an instance of either: +** `EventDrivenConsumer` +** `PollingConsumer` + +The exact implementation depends on whether the component's input channel is a: +`SubscribableChannel` or `PollableChannel` + +* `auto-startup` Boolean flag to indicate that the endpoint should start automatically on +startup. The default is __true__. +* `request-channel` The input `MessageChannel` of this endpoint. +* `reply-channel` `Message Channel` to which the resulting `JobExecution` payload will be sent. +* `reply-timeout` Allows you to specify how long this gateway will wait for the reply message +to be sent successfully to the reply channel before throwing +an exception. This attribute only applies when the channel +might block, for example when using a bounded queue channel +that is currently full. Also, keep in mind that when sending to a +`DirectChannel`, the invocation will occur +in the sender's thread. Therefore, the failing of the send +operation may be caused by other components further downstream. +The `reply-timeout` attribute maps to the +`sendTimeout` property of the underlying +`MessagingTemplate` instance. The attribute +will default, if not specified, to-1, +meaning that by default, the `Gateway` will wait indefinitely. +The value is specified in milliseconds. +* `job-launcher` Pass in a +custom +`JobLauncher` +bean reference. This +attribute is optional. If not specified the adapter will +re-use the instance that is registered under the id +`jobLauncher`. If no default instance +exists an exception is thrown. +* `order` Specifies the order for invocation when this endpoint is connected as a subscriber +to a `SubscribableChannel`. + +=== Sub-Elements +When this `Gateway` is receiving messages from a +`PollableChannel`, you must either provide +a global default Poller or provide a Poller sub-element to the +`Job Launching Gateway`: +[source, xml] +---- + + + +---- + +[[providing-feedback-with-informational-messages]] + +==== Providing Feedback with Informational Messages + + +As Spring Batch jobs can run for long times, providing progress +information will be critical. For example, stake-holders may want +to be notified if a some or all parts of a Batch Job has failed. +Spring Batch provides support for this information being gathered +through: + + + +* Active polling or + +* Event-driven, using listeners. + + +When starting a Spring Batch job asynchronously, e.g. by using the +`Job Launching Gateway`, a +`JobExecution` instance is returned. Thus, +`JobExecution.getJobId()` can be used to +continuously poll for status updates by retrieving updated +instances of the `JobExecution` from the +`JobRepository` using the +`JobExplorer`. However, this is considered +sub-optimal and an event-driven approach should be preferred. + + +Therefore, Spring Batch provides listeners such as: + +* StepListener +* ChunkListener +* JobExecutionListener + +In the following example, a Spring Batch job was configured with a +`StepExecutionListener`. Thus, Spring +Integration will receive and process any step before/after step +events. For example, the received +`StepExecution` can be inspected using a +`Router`. Based on the results of that +inspection, various things can occur for example routing a message +to a Mail Outbound Channel Adapter, so that an Email notification +can be sent out based on some condition. + +.Handling Informational Messages +image::{batch-asciidoc}images/handling-informational-messages.png[Handling Informational Messages, scaledwidth="60%"] + + +Below is an example of how a listener is configured to send a +message to a `Gateway` for +`StepExecution` events and log its output to a +`logging-channel-adapter`: + +First create the notifications integration beans: + +[source, xml] +---- + + + + + +---- + + +Then modify your job to add a step level listener: + +[source, xml] +---- + + + + + + + + + ... + + +---- + +[[asynchronous-processors]] + +==== Asynchronous Processors + + +Asynchronous Processors help you to to scale the processing of +items. In the asynchronous processor use-case, an +`AsyncItemProcessor` serves as a dispatcher, +executing the `ItemProcessor's` logic for an +item on a new thread. The `Future` is passed to +the AsynchItemWriter to be written once the +processor completes. + + + +Therefore, you can increase performance by using asynchronous item +processing, basically allowing you to implement +__fork-join__ scenarios. The +`AsyncItemWriter` will gather the results and +write back the chunk as soon as all the results become available. + + + +Configuration of both the `AsyncItemProcessor` +and `AsyncItemWriter` are simple, first the +`AsyncItemProcessor`: + + + +[source, xml] +---- + + + + + + + + +---- + + +The property "`delegate`" is actually +a reference to your `ItemProcessor` bean and +the "taskExecutor" property is a +reference to the `TaskExecutor` of your choice. + +Then we configure the `AsyncItemWriter`: + +[source, xml] +---- + + + + + +---- + + +Again, the property "`delegate`" is +actually a reference to your `ItemWriter` bean. + + +[[externalizing-batch-process-execution]] + +==== Externalizing Batch Process Execution + + +The integration approaches discussed so far suggest use-cases +where Spring Integration wraps Spring Batch like an outer-shell. +However, Spring Batch can also use Spring Integration internally. +Using this approach, Spring Batch users can delegate the +processing of items or even chunks to outside processes. This +allows you to offload complex processing. Spring Batch Integration +provides dedicated support for: + + + +* Remote Chunking + + + +* Remote Partitioning + + +[[remote-chunking]] + +===== Remote Chunking + +.Remote Chunking +image::{batch-asciidoc}images/remote-chunking-sbi.png[Remote Chunking, scaledwidth="60%"] + +Taking things one step further, one can also externalize the +chunk processing using the +`ChunkMessageChannelItemWriter` which is +provided by Spring Batch Integration which will send items out +and collect the result. Once sent, Spring Batch will continue the +process of reading and grouping items, without waiting for the results. +Rather it is the responsibility of the `ChunkMessageChannelItemWriter` +to gather the results and integrate them back into the Spring Batch process. + + +Using Spring Integration you have full +control over the concurrency of your processes, for instance by +using a `QueueChannel` instead of a +`DirectChannel`. Furthermore, by relying on +Spring Integration's rich collection of Channel Adapters (E.g. +JMS or AMQP), you can distribute chunks of a Batch job to +external systems for processing. + +A simple job with a step to be remotely chunked would have a +configuration similar to the following: + +[source, xml] +---- + + + + + + ... + + +---- + +The `ItemReader` reference would point to the bean you would like +to use for reading data on the master. The `ItemWriter` reference +points to a special `ItemWriter` +"`ChunkMessageChannelItemWriter`" +as described above. The processor (if any) is left off the +master configuration as it is configured on the slave. The +following configuration provides a basic master setup. It's +advised to check any additional component properties such as +throttle limits and so on when implementing your use case. + +[source, xml] +---- + + + + + + + + + + + + + + + + + + + + + + + + + + +---- + + +This configuration provides us with a number of beans. We +configure our messaging middleware using ActiveMQ and +inbound/outbound JMS adapters provided by Spring Integration. As +shown, our `itemWriter` bean which is +referenced by our job step utilizes the +`ChunkMessageChannelItemWriter` for writing chunks over the +configured middleware. + +Now lets move on to the slave configuration: + + + +[source, xml] +---- + + + + + + + + + + + + + + + + + + + + + + + + + + +---- + + +Most of these configuration items should look familiar from the +master configuration. Slaves do not need access to things like +the Spring Batch `JobRepository` nor access +to the actual job configuration file. The main bean of interest +is the "`chunkProcessorChunkHandler`". The +`chunkProcessor` property of `ChunkProcessorChunkHandler` takes a +configured `SimpleChunkProcessor` which is where you would provide a reference to your +`ItemWriter` and optionally your +`ItemProcessor` that will run on the slave +when it receives chunks from the master. + +For more information, please also consult the Spring Batch +manual, specifically the chapter on +link:$$http://docs.spring.io/spring-batch/reference/html/scalability.html#remoteChunking$$[Remote Chunking]. + + +[[remote-partitioning]] + +===== Remote Partitioning + +.Remote Partitioning +image::{batch-asciidoc}images/remote-partitioning.png[Remote Partitioning, scaledwidth="60%"] + + +Remote Partitioning, on the other hand, is useful when the +problem is not the processing of items, but the associated I/O +represents the bottleneck. Using Remote Partitioning, work can +be farmed out to slaves that execute complete Spring Batch +steps. Thus, each slave has its own `ItemReader`, `ItemProcessor` and +`ItemWriter`. For this purpose, Spring Batch +Integration provides the `MessageChannelPartitionHandler`. + + + +This implementation of the `PartitionHandler` +interface uses MessageChannel instances to +send instructions to remote workers and receive their responses. +This provides a nice abstraction from the transports (E.g. JMS +or AMQP) being used to communicate with the remote workers. + + + +The reference manual section +link:$$http://docs.spring.io/spring-batch/reference/html/scalability.html#partitioning$$[Remote Partitioning] provides an overview of the concepts and +components needed to configure Remote Partitioning and shows an +example of using the default +`TaskExecutorPartitionHandler` to partition +in separate local threads of execution. For Remote Partitioning +to multiple JVM's, two additional components are required: + +* Remoting fabric or grid environment +* A `PartitionHandler` implementation that supports the desired +remoting fabric or grid environment + + + +Similar to Remote Chunking JMS can be used as the "remoting +fabric" and the `PartitionHandler` implementation to be used +as described above is the +`MessageChannelPartitionHandler`. The example +shown below assumes an existing partitioned job and focuses on +the `MessageChannelPartitionHandler` and JMS +configuration: + + + +[source, xml] +---- + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +---- + +Also ensure the partition `handler` attribute maps to the `partitionHandler` bean: + +[source, xml] +---- + + + + ... + + +---- + diff --git a/spring-batch-docs/asciidoc/spring-batch-intro.adoc b/spring-batch-docs/asciidoc/spring-batch-intro.adoc new file mode 100644 index 000000000..674f2236e --- /dev/null +++ b/spring-batch-docs/asciidoc/spring-batch-intro.adoc @@ -0,0 +1,465 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[spring-batch-intro]] + +== Spring Batch Introduction + +Many applications within the enterprise domain require bulk processing + to perform business operations in mission critical environments. These + business operations include automated, complex processing of large volumes + of information that is most efficiently processed without user interaction. + These operations typically include time based events (e.g. month-end + calculations, notices or correspondence), periodic application of complex + business rules processed repetitively across very large data sets (e.g. + Insurance benefit determination or rate adjustments), or the integration of + information that is received from internal and external systems that + typically requires formatting, validation and processing in a transactional + manner into the system of record. Batch processing is used to process + billions of transactions every day for enterprises. + +Spring Batch is a lightweight, comprehensive batch framework designed + to enable the development of robust batch applications vital for the daily + operations of enterprise systems. Spring Batch builds upon the productivity, + POJO-based development approach, and general ease of use capabilities people + have come to know from the Spring Framework, while making it easy for + developers to access and leverage more advance enterprise services when + necessary. Spring Batch is not a scheduling framework. There are many good + enterprise schedulers available in both the commercial and open source + spaces such as Quartz, Tivoli, Control-M, etc. It is intended to work in + conjunction with a scheduler, not replace a scheduler. + +Spring Batch provides reusable functions that are essential in + processing large volumes of records, including logging/tracing, transaction + management, job processing statistics, job restart, skip, and resource + management. It also provides more advance technical services and features + that will enable extremely high-volume and high performance batch jobs + though optimization and partitioning techniques. Simple as well as complex, + high-volume batch jobs can leverage the framework in a highly scalable + manner to process significant volumes of information. + +[[springBatchBackground]] + + +=== Background + +While open source software projects and associated communities have + focused greater attention on web-based and SOA messaging-based + architecture frameworks, there has been a notable lack of focus on + reusable architecture frameworks to accommodate Java-based batch + processing needs, despite continued needs to handle such processing within + enterprise IT environments. The lack of a standard, reusable batch + architecture has resulted in the proliferation of many one-off, in-house + solutions developed within client enterprise IT functions. + +SpringSource and Accenture have collaborated to change this. + Accenture's hands-on industry and technical experience in implementing + batch architectures, SpringSource's depth of technical experience, and + Spring's proven programming model together mark a natural and powerful + partnership to create high-quality, market relevant software aimed at + filling an important gap in enterprise Java. Both companies are also + currently working with a number of clients solving similar problems + developing Spring-based batch architecture solutions. This has provided + some useful additional detail and real-life constraints helping to ensure + the solution can be applied to the real-world problems posed by clients. + For these reasons and many more, SpringSource and Accenture have teamed to + collaborate on the development of Spring Batch. + +Accenture has contributed previously proprietary batch processing + architecture frameworks, based upon decades worth of experience in + building batch architectures with the last several generations of + platforms, (i.e., COBOL/Mainframe, C++/Unix, and now Java/anywhere) to the + Spring Batch project along with committer resources to drive support, + enhancements, and the future roadmap. + +The collaborative effort between Accenture and SpringSource aims to + promote the standardization of software processing approaches, frameworks, + and tools that can be consistently leveraged by enterprise users when + creating batch applications. Companies and government agencies desiring to + deliver standard, proven solutions to their enterprise IT environments + will benefit from Spring Batch. + +[[springBatchUsageScenarios]] + + +=== Usage Scenarios + +A typical batch program generally reads a large number of records + from a database, file, or queue, processes the data in some fashion, and + then writes back data in a modified form. Spring Batch automates this + basic batch iteration, providing the capability to process similar + transactions as a set, typically in an offline environment without any + user interaction. Batch jobs are part of most IT projects and Spring Batch + is the only open source framework that provides a robust, enterprise-scale + solution. + +Business Scenarios + +* Commit batch process periodically + + +* Concurrent batch processing: parallel processing of a + job + + +* Staged, enterprise message-driven processing + + +* Massively parallel batch processing + + +* Manual or scheduled restart after failure + + +* Sequential processing of dependent steps (with extensions to + workflow-driven batches) + + +* Partial processing: skip records (e.g. on rollback) + + +* Whole-batch transaction: for cases with a small batch size or + existing stored procedures/scripts + + + +Technical Objectives + +* Batch developers use the Spring programming model: concentrate + on business logic; let the framework take care of + infrastructure. + + +* Clear separation of concerns between the infrastructure, the + batch execution environment, and the batch application. + + +* Provide common, core execution services as interfaces that all + projects can implement. + + +* Provide simple and default implementations of the core + execution interfaces that can be used 'out of the box'. + + +* Easy to configure, customize, and extend services, by + leveraging the spring framework in all layers. + + +* All existing core services should be easy to replace or + extend, without any impact to the infrastructure layer. + + +* Provide a simple deployment model, with the architecture JARs + completely separate from the application, built using Maven. + + + +[[springBatchArchitecture]] + + +=== Spring Batch Architecture + + + +Spring Batch is designed with extensibility and a diverse group of + end users in mind. The figure below shows a sketch of the layered + architecture that supports the extensibility and ease of use for end-user + developers. + +.Spring Batch Layered Architecture +image::{batch-asciidoc}images/spring-batch-layers.png[Figure 1.1: Spring Batch Layered Architecture, scaledwidth="60%"] + + + +This layered architecture highlights three major high level + components: Application, Core, and Infrastructure. The application + contains all batch jobs and custom code written by developers using Spring + Batch. The Batch Core contains the core runtime classes necessary to + launch and control a batch job. It includes things such as a + JobLauncher, Job, and + Step implementations. Both Application and Core are + built on top of a common infrastructure. This infrastructure contains + common readers and writers, and services such as the + RetryTemplate, which are used both by application + developers(`ItemReader` and + `ItemWriter`) and the core framework itself. + (retry) + +[[batchArchitectureConsiderations]] + + +=== General Batch Principles and Guidelines + +The following are a number of key principles, guidelines, and general considerations to take into consideration when building a batch solution. + + +* A batch architecture typically affects on-line architecture and vice versa. Design with both architectures and environments in mind using common building blocks when possible. + + +* Simplify as much as possible and avoid building complex logical structures in single batch applications. + + +* Process data as close to where the data physically resides as possible or vice versa (i.e., keep your data where your processing occurs). + + +* Minimize system resource use, especially I/O. Perform as many operations as possible in internal memory. + + +* Review application I/O (analyze SQL statements) to ensure that unnecessary physical I/O is avoided. In particular, the following four common flaws need to be looked for: + +* Reading data for every transaction when the data could be read once and kept cached or in the working storage; + + +* Rereading data for a transaction where the data was read earlier in the same transaction; + + +* Causing unnecessary table or index scans; + + +* Not specifying key values in the WHERE clause of an SQL statement. + + + + + +* Do not do things twice in a batch run. For instance, if you need data summarization for reporting purposes, increment stored totals if possible when data is being initially processed, so your reporting application does not have to reprocess the same data. + + +* Allocate enough memory at the beginning of a batch application to avoid time-consuming reallocation during the process. + + +* Always assume the worst with regard to data integrity. Insert adequate checks and record validation to maintain data integrity. + + +* Implement checksums for internal validation where possible. For example, flat files should have a trailer record telling the total of records in the file and an aggregate of the key fields. + + +* Plan and execute stress tests as early as possible in a production-like environment with realistic data volumes. + + +* In large batch systems backups can be challenging, especially if the system is running concurrent with on-line on a 24-7 basis. Database backups are typically well taken care of in the on-line design, but file backups should be considered to be just as important. If the system depends on flat files, file backup procedures should not only be in place and documented, but regularly tested as well. + +[[batchProcessingStrategy]] + + +=== Batch Processing Strategies + +To help design and implement batch systems, basic batch application building blocks and patterns should be provided to the designers and programmers in form of sample structure charts and code shells. When starting to design a batch job, the business logic should be decomposed into a series of steps which can be implemented using the following standard building blocks: + + +* __Conversion Applications:__ For each type of file supplied by or generated to an external system, a conversion application will need to be created to convert the transaction records supplied into a standard format required for processing. This type of batch application can partly or entirely consist of translation utility modules (see Basic Batch Services). + + +* __Validation Applications:__ Validation applications ensure that all input/output records are correct and consistent. Validation is typically based on file headers and trailers, checksums and validation algorithms as well as record level cross-checks. + + +* __Extract Applications:__ An application that reads a set of records from a database or input file, selects records based on predefined rules, and writes the records to an output file. + + +* __Extract/Update Applications:__ An application that reads records from a database or an input file, and makes changes to a database or an output file driven by the data found in each input record. + + +* __Processing and Updating Applications:__ An application that performs processing on input transactions from an extract or a validation application. The processing will usually involve reading a database to obtain data required for processing, potentially updating the database and creating records for output processing. + + +* __Output/Format Applications:__ Applications reading an input file, restructures data from this record according to a standard format, and produces an output file for printing or transmission to another program or system. + +Additionally a basic application shell should be provided for business logic that cannot be built using the previously mentioned building blocks. + +In addition to the main building blocks, each application may use one or more of standard utility steps, such as: + + +* Sort - A Program that reads an input file and produces an output file where records have been re-sequenced according to a sort key field in the records. Sorts are usually performed by standard system utilities. + + +* Split - A program that reads a single input file, and writes each record to one of several output files based on a field value. Splits can be tailored or performed by parameter-driven standard system utilities. + + +* Merge - A program that reads records from multiple input files and produces one output file with combined data from the input files. Merges can be tailored or performed by parameter-driven standard system utilities. + +Batch applications can additionally be categorized by their input source: + + +* Database-driven applications are driven by rows or values retrieved from the database. + + +* File-driven applications are driven by records or values retrieved from a file. + + +* Message-driven applications are driven by messages retrieved from a message queue. + +The foundation of any batch system is the processing strategy. Factors affecting the selection of the strategy include: estimated batch system volume, concurrency with on-line or with another batch systems, available batch windows (and with more enterprises wanting to be up and running 24x7, this leaves no obvious batch windows). + +Typical processing options for batch are: + + +* Normal processing in a batch window during off-line + + +* Concurrent batch / on-line processing + + +* Parallel processing of many different batch runs or jobs at the same time + + +* Partitioning (i.e. processing of many instances of the same job at the same time) + + +* A combination of these + +The order in the list above reflects the implementation complexity, processing in a batch window being the easiest and partitioning the most complex to implement. + +Some or all of these options may be supported by a commercial scheduler. + +In the following section these processing options are discussed in more detail. It is important to notice that the commit and locking strategy adopted by batch processes will be dependent on the type of processing performed, and as a rule of thumb and the on-line locking strategy should also use the same principles. Therefore, the batch architecture cannot be simply an afterthought when designing an overall architecture. + +The locking strategy can use only normal database locks, or an additional custom locking service can be implemented in the architecture. The locking service would track database locking (for example by storing the necessary information in a dedicated db-table) and give or deny permissions to the application programs requesting a db operation. Retry logic could also be implemented by this architecture to avoid aborting a batch job in case of a lock situation. + +*1. Normal processing in a batch window* + For simple batch processes running in a separate batch window, where the data being updated is not required by on-line users or other batch processes, concurrency is not an issue and a single commit can be done at the end of the batch run. + +In most cases a more robust approach is more appropriate. A thing to keep in mind is that batch systems have a tendency to grow as time goes by, both in terms of complexity and the data volumes they will handle. If no locking strategy is in place and the system still relies on a single commit point, modifying the batch programs can be painful. Therefore, even with the simplest batch systems, consider the need for commit logic for restart-recovery options as well as the information concerning the more complex cases below. + +*2. Concurrent batch / on-line processing* + Batch applications processing data that can simultaneously be updated by on-line users, should not lock any data (either in the database or in files) which could be required by on-line users for more than a few seconds. Also updates should be committed to the database at the end of every few transaction. This minimizes the portion of data that is unavailable to other processes and the elapsed time the data is unavailable. + +Another option to minimize physical locking is to have a logical row-level locking implemented using either an Optimistic Locking Pattern or a Pessimistic Locking Pattern. + + +* Optimistic locking assumes a low likelihood of record contention. It typically means inserting a timestamp column in each database table used concurrently by both batch and on-line processing. When an application fetches a row for processing, it also fetches the timestamp. As the application then tries to update the processed row, the update uses the original timestamp in the WHERE clause. If the timestamp matches, the data and the timestamp will be updated successfully. If the timestamp does not match, this indicates that another application has updated the same row between the fetch and the update attempt and therefore the update cannot be performed. + + +* Pessimistic locking is any locking strategy that assumes there is a high likelihood of record contention and therefore either a physical or logical lock needs to be obtained at retrieval time. One type of pessimistic logical locking uses a dedicated lock-column in the database table. When an application retrieves the row for update, it sets a flag in the lock column. With the flag in place, other applications attempting to retrieve the same row will logically fail. When the application that set the flag updates the row, it also clears the flag, enabling the row to be retrieved by other applications. Please note, that the integrity of data must be maintained also between the initial fetch and the setting of the flag, for example by using db locks (e.g., SELECT FOR UPDATE). Note also that this method suffers from the same downside as physical locking except that it is somewhat easier to manage building a time-out mechanism that will get the lock released if the user goes to lunch while the record is locked. + +These patterns are not necessarily suitable for batch processing, but they might be used for concurrent batch and on-line processing (e.g. in cases where the database doesn't support row-level locking). As a general rule, optimistic locking is more suitable for on-line applications, while pessimistic locking is more suitable for batch applications. Whenever logical locking is used, the same scheme must be used for all applications accessing data entities protected by logical locks. + +Note that both of these solutions only address locking a single record. Often we may need to lock a logically related group of records. With physical locks, you have to manage these very carefully in order to avoid potential deadlocks. With logical locks, it is usually best to build a logical lock manager that understands the logical record groups you want to protect and can ensure that locks are coherent and non-deadlocking. This logical lock manager usually uses its own tables for lock management, contention reporting, time-out mechanism, etc. + +*3. Parallel Processing* + Parallel processing allows multiple batch runs / jobs to run in parallel to minimize the total elapsed batch processing time. This is not a problem as long as the jobs are not sharing the same files, db-tables or index spaces. If they do, this service should be implemented using partitioned data. Another option is to build an architecture module for maintaining interdependencies using a control table. A control table should contain a row for each shared resource and whether it is in use by an application or not. The batch architecture or the application in a parallel job would then retrieve information from that table to determine if it can get access to the resource it needs or not. + +If the data access is not a problem, parallel processing can be implemented through the use of additional threads to process in parallel. In the mainframe environment, parallel job classes have traditionally been used, in order to ensure adequate CPU time for all the processes. Regardless, the solution has to be robust enough to ensure time slices for all the running processes. + +Other key issues in parallel processing include load balancing and the availability of general system resources such as files, database buffer pools etc. Also note that the control table itself can easily become a critical resource. + +*4. Partitioning* + Using partitioning allows multiple versions of large batch applications to run concurrently. The purpose of this is to reduce the elapsed time required to process long batch jobs. Processes which can be successfully partitioned are those where the input file can be split and/or the main database tables partitioned to allow the application to run against different sets of data. + +In addition, processes which are partitioned must be designed to only process their assigned data set. A partitioning architecture has to be closely tied to the database design and the database partitioning strategy. Please note, that the database partitioning doesn't necessarily mean physical partitioning of the database, although in most cases this is advisable. The following picture illustrates the partitioning approach: + +.Partitioned Process +image::{batch-asciidoc}images/partitioned.png[Figure 1.2: Partitioned Process, scaledwidth="60%"] + + +The architecture should be flexible enough to allow dynamic configuration of the number of partitions. Both automatic and user controlled configuration should be considered. Automatic configuration may be based on parameters such as the input file size and/or the number of input records. + +*4.1 Partitioning Approaches* + The following lists some of the possible partitioning approaches. Selecting a partitioning approach has to be done on a case-by-case basis. + +_1. Fixed and Even Break-Up of Record Set_ + +This involves breaking the input record set into an even number of portions (e.g. 10, where each portion will have exactly 1/10th of the entire record set). Each portion is then processed by one instance of the batch/extract application. + +In order to use this approach, preprocessing will be required to split the recordset up. The result of this split will be a lower and upper bound placement number which can be used as input to the batch/extract application in order to restrict its processing to its portion alone. + +Preprocessing could be a large overhead as it has to calculate and determine the bounds of each portion of the record set. + +_2. Breakup by a Key Column_ + +This involves breaking up the input record set by a key column such as a location code, and assigning data from each key to a batch instance. In order to achieve this, column values can either be + +_3. Assigned to a batch instance via a partitioning table (see below for details)._ + +_4. Assigned to a batch instance by a portion of the value (e.g. values 0000-0999, 1000 - 1999, etc.)_ + +Under option 1, addition of new values will mean a manual reconfiguration of the batch/extract to ensure that the new value is added to a particular instance. + +Under option 2, this will ensure that all values are covered via an instance of the batch job. However, the number of values processed by one instance is dependent on the distribution of column values (i.e. there may be a large number of locations in the 0000-0999 range, and few in the 1000-1999 range). Under this option, the data range should be designed with partitioning in mind. + +Under both options, the optimal even distribution of records to batch instances cannot be realized. There is no dynamic configuration of the number of batch instances used. + +_5. Breakup by Views_ + +This approach is basically breakup by a key column, but on the database level. It involves breaking up the recordset into views. These views will be used by each instance of the batch application during its processing. The breakup will be done by grouping the data. + +With this option, each instance of a batch application will have to be configured to hit a particular view (instead of the master table). Also, with the addition of new data values, this new group of data will have to be included into a view. There is no dynamic configuration capability, as a change in the number of instances will result in a change to the views. + +_6. Addition of a Processing Indicator_ + +This involves the addition of a new column to the input table, which acts as an indicator. As a preprocessing step, all indicators would be marked to non-processed. During the record fetch stage of the batch application, records are read on the condition that that record is marked non-processed, and once they are read (with lock), they are marked processing. When that record is completed, the indicator is updated to either complete or error. Many instances of a batch application can be started without a change, as the additional column ensures that a record is only processed once. + +With this option, I/O on the table increases dynamically. In the case of an updating batch application, this impact is reduced, as a write will have to occur anyway. + +_7. Extract Table to a Flat File_ + +This involves the extraction of the table into a file. This file can then be split into multiple segments and used as input to the batch instances. + +With this option, the additional overhead of extracting the table into a file, and splitting it, may cancel out the effect of multi-partitioning. Dynamic configuration can be achieved via changing the file splitting script. + +_8. Use of a Hashing Column_ + +This scheme involves the addition of a hash column (key/index) to the database tables used to retrieve the driver record. This hash column will have an indicator to determine which instance of the batch application will process this particular row. For example, if there are three batch instances to be started, then an indicator of 'A' will mark that row for processing by instance 1, an indicator of 'B' will mark that row for processing by instance 2, etc. + +The procedure used to retrieve the records would then have an additional WHERE clause to select all rows marked by a particular indicator. The inserts in this table would involve the addition of the marker field, which would be defaulted to one of the instances (e.g. 'A'). + +A simple batch application would be used to update the indicators such as to redistribute the load between the different instances. When a sufficiently large number of new rows have been added, this batch can be run (anytime, except in the batch window) to redistribute the new rows to other instances. + +Additional instances of the batch application only require the running of the batch application as above to redistribute the indicators to cater for a new number of instances. + +*4.2 Database and Application design Principles* + +An architecture that supports multi-partitioned applications which run against partitioned database tables using the key column approach, should include a central partition repository for storing partition parameters. This provides flexibility and ensures maintainability. The repository will generally consist of a single table known as the partition table. + +Information stored in the partition table will be static and in general should be maintained by the DBA. The table should consist of one row of information for each partition of a multi-partitioned application. The table should have columns for: Program ID Code, Partition Number (Logical ID of the partition), Low Value of the db key column for this partition, High Value of the db key column for this partition. + +On program start-up the program id and partition number should be passed to the application from the architecture (Control Processing Tasklet). These variables are used to read the partition table, to determine what range of data the application is to process (if a key column approach is used). In addition the partition number must be used throughout the processing to: + + +* Add to the output files/database updates in order for the merge process to work properly + + +* Report normal processing to the batch log and any errors that occur during execution to the architecture error handler + +*4.3 Minimizing Deadlocks* + +When applications run in parallel or partitioned, contention in database resources and deadlocks may occur. It is critical that the database design team eliminates potential contention situations as far as possible as part of the database design. + +Also ensure that the database index tables are designed with deadlock prevention and performance in mind. + +Deadlocks or hot spots often occur in administration or architecture tables such as log tables, control tables, and lock tables. The implications of these should be taken into account as well. A realistic stress test is crucial for identifying the possible bottlenecks in the architecture. + +To minimize the impact of conflicts on data, the architecture should provide services such as wait-and-retry intervals when attaching to a database or when encountering a deadlock. This means a built-in mechanism to react to certain database return codes and instead of issuing an immediate error handling, waiting a predetermined amount of time and retrying the database operation. + +*4.4 Parameter Passing and Validation* + +The partition architecture should be relatively transparent to application developers. The architecture should perform all tasks associated with running the application in a partitioned mode including: + + +* Retrieve partition parameters before application start-up + + +* Validate partition parameters before application start-up + + +* Pass parameters to application at start-up + +The validation should include checks to ensure that: + + +* the application has sufficient partitions to cover the whole data range + + +* there are no gaps between partitions + +If the database is partitioned, some additional validation may be necessary to ensure that a single partition does not span database partitions. + +Also the architecture should take into consideration the consolidation of partitions. Key questions include: + + +* Must all the partitions be finished before going into the next job step? + + +* What happens if one of the partitions aborts? + diff --git a/spring-batch-docs/asciidoc/step.adoc b/spring-batch-docs/asciidoc/step.adoc new file mode 100644 index 000000000..ad542cba4 --- /dev/null +++ b/spring-batch-docs/asciidoc/step.adoc @@ -0,0 +1,1903 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[configureStep]] +== Configuring a Step + +As discussed in <>, a + `Step` is a domain object that encapsulates an + independent, sequential phase of a batch job and contains all of the + information necessary to define and control the actual batch processing. + This is a necessarily vague description because the contents of any given + `Step` are at the discretion of the developer writing a + `Job`. A `Step` can be as simple or complex as the + developer desires. A simple `Step` might load data from + a file into the database, requiring little or no code. (depending upon the + implementations used) A more complex `Step` may have + complicated business rules that are applied as part of the + processing. + +.Step +image::{batch-asciidoc}images/step.png[Step, scaledwidth="60%"] + +[[chunkOrientedProcessing]] + +=== Chunk-Oriented Processing + +Spring Batch uses a 'Chunk Oriented' processing style within its + most common implementation. Chunk oriented processing refers to reading + the data one at a time, and creating 'chunks' that will be written out, + within a transaction boundary. One item is read in from an + `ItemReader`, handed to an + `ItemProcessor`, and aggregated. Once the number of + items read equals the commit interval, the entire chunk is written out via + the ItemWriter, and then the transaction is committed. + +.Chunk Oriented Processing +image::{batch-asciidoc}images/chunk-oriented-processing.png[Chunk Oriented Processing, scaledwidth="60%"] + +Below is a code representation of the same concepts shown + above: + + +[source, java] +---- +List items = new Arraylist(); +for(int i = 0; i < commitInterval; i++){ + Object item = itemReader.read() + Object processedItem = itemProcessor.process(item); + items.add(processedItem); +} +itemWriter.write(items); +---- + +[[configuringAStep]] + + +==== Configuring a Step + +Despite the relatively short list of required dependencies for a + `Step`, it is an extremely complex class that can + potentially contain many collaborators. In order to ease configuration, + the Spring Batch namespace can be used: + + +[source, xml] +---- + + + + + + + +---- + +The configuration above represents the only required dependencies + to create a item-oriented step: + +* reader - The `ItemReader` that provides + items for processing. + + +* writer - The ItemWriter that + processes the items provided by the + `ItemReader`. + + +* transaction-manager - Spring's + `PlatformTransactionManager` that will be + used to begin and commit transactions during processing. + + +* job-repository - The `JobRepository` + that will be used to periodically store the + `StepExecution` and + `ExecutionContext` during processing (just + before committing). For an in-line (one defined + within a ) it is an attribute on the + element; for a standalone step, it is defined as an attribute of + the . + + +* commit-interval - The number of items that will be processed + before the transaction is committed. + + + +It should be noted that, job-repository defaults to + "jobRepository" and transaction-manager defaults to "transactionManger". + Furthermore, the `ItemProcessor` is optional, not + required, since the item could be directly passed from the reader to the + writer. + +[[InheritingFromParentStep]] + + +==== Inheriting from a Parent Step + +If a group of `Steps` share similar + configurations, then it may be helpful to define a "parent" + `Step` from which the concrete + `Steps` may inherit properties. Similar to class + inheritance in Java, the "child" `Step` will + combine its elements and attributes with the parent's. The child will + also override any of the parent's `Steps`. + +In the following example, the `Step` + "concreteStep1" will inherit from "parentStep". It will be instantiated + with 'itemReader', 'itemProcessor', 'itemWriter', startLimit=5, and + allowStartIfComplete=true. Additionally, the commitInterval will be '5' + since it is overridden by the "concreteStep1": + + +[source, xml] +---- + + + + + + + + + + + +---- + +The id attribute is still required on the step within the job + element. This is for two reasons: +. The id will be used as the step name when persisting the + `StepExecution`. If the same standalone step is referenced in more + than one step in the job, an error will occur. + + +. When creating job flows, as described later in this chapter, + the next attribute should be referring to the step in the flow, + not the standalone step. + + + +[[abstractStep]] + + +===== Abstract Step + +Sometimes it may be necessary to define a parent + `Step` that is not a complete + `Step` configuration. If, for instance, the + reader, writer, and tasklet attributes are left off of a + `Step` configuration, then initialization will + fail. If a parent must be defined without these properties, then the + "abstract" attribute should be used. An "abstract" + `Step` will not be instantiated; it is used only + for extending. + +In the following example, the `Step` + "abstractParentStep" would not instantiate if it were not declared to + be abstract. The `Step` "concreteStep2" will have + 'itemReader', 'itemWriter', and commitInterval=10. + + +[source, xml] +---- + + + + + + + + + + + +---- + +[[mergingListsOnStep]] + + +===== Merging Lists + +Some of the configurable elements on + `Steps` are lists; the + element, for instance. If both the parent and child + `Steps` declare a element, + then the child's list will override the parent's. In order to allow a + child to add additional listeners to the list defined by the parent, + every list element has a "merge" attribute. If the element specifies + that merge="true", then the child's list will be combined with the + parent's instead of overriding it. + +In the following example, the `Step` + "concreteStep3" will be created will two listeners: + `listenerOne` and + `listenerTwo`: + + +[source, xml] +---- + + + + + + + + + + + + + + +---- + +[[commitInterval]] + + +==== The Commit Interval + +As mentioned above, a step reads in and writes out items, + periodically committing using the supplied + `PlatformTransactionManager`. With a + commit-interval of 1, it will commit after writing each individual item. + This is less than ideal in many situations, since beginning and + committing a transaction is expensive. Ideally, it is preferable to + process as many items as possible in each transaction, which is + completely dependent upon the type of data being processed and the + resources with which the step is interacting. For this reason, the + number of items that are processed within a commit can be + configured. + + +[source, xml] +---- + + + + + + + +---- + +In the example above, 10 items will be processed within each + transaction. At the beginning of processing a transaction is begun, and + each time read is called on the + `ItemReader`, a counter is incremented. When it + reaches 10, the list of aggregated items is passed to the + ItemWriter, and the transaction will be + committed. + +[[stepRestart]] + + +==== Configuring a Step for Restart + +In the <> section , restarting a + `Job` was discussed. Restart has numerous impacts + on steps, and as such may require some specific configuration. + +[[startLimit]] + + +===== Setting a StartLimit + +There are many scenarios where you may want to control the + number of times a `Step` may be started. For + example, a particular `Step` might need to be + configured so that it only runs once because it invalidates some + resource that must be fixed manually before it can be run again. This + is configurable on the step level, since different steps may have + different requirements. A `Step` that may only be + executed once can exist as part of the same `Job` + as a `Step` that can be run infinitely. Below is + an example start limit configuration: + + +[source, xml] +---- + + + + + +---- + +The simple step above can be run only once. Attempting to run it + again will cause an exception to be thrown. It should be noted that + the default value for the start-limit is + `Integer.MAX_VALUE`. + +[[allowStartIfComplete]] + + +===== Restarting a completed step + +In the case of a restartable job, there may be one or more steps + that should always be run, regardless of whether or not they were + successful the first time. An example might be a validation step, or a + `Step` that cleans up resources before + processing. During normal processing of a restarted job, any step with + a status of 'COMPLETED', meaning it has already been completed + successfully, will be skipped. Setting allow-start-if-complete to + "true" overrides this so that the step will always run: + + +[source, xml] +---- + + + + + +---- + +[[stepRestartExample]] + + +===== Step Restart Configuration Example + + +[source, xml] +---- + + + + + + + + + + + + + + + + + +---- + +The above example configuration is for a job that loads in + information about football games and summarizes them. It contains + three steps: playerLoad, gameLoad, and playerSummarization. The + playerLoad `Step` loads player information from a + flat file, while the gameLoad `Step` does the + same for games. The final `Step`, + playerSummarization, then summarizes the statistics for each player + based upon the provided games. It is assumed that the file loaded by + 'playerLoad' must be loaded only once, but that 'gameLoad' will load + any games found within a particular directory, deleting them after + they have been successfully loaded into the database. As a result, the + playerLoad `Step` contains no additional + configuration. It can be started almost limitlessly, and if complete + will be skipped. The 'gameLoad' `Step`, however, + needs to be run every time in case extra files have been dropped since + it last executed. It has 'allow-start-if-complete' set to 'true' in + order to always be started. (It is assumed that the database tables + games are loaded into has a process indicator on it, to ensure new + games can be properly found by the summarization step). The + summarization `Step`, which is the most important + in the `Job`, is configured to have a start limit + of 3. This is useful because if the step continually fails, a new exit + code will be returned to the operators that control job execution, and + it won't be allowed to start again until manual intervention has taken + place. + + +[NOTE] +==== +This job is purely for example purposes and is not the same as + the footballJob found in the samples project. +==== + + +Run 1: + + +. playerLoad is executed and completes successfully, adding + 400 players to the 'PLAYERS' table. + + +. gameLoad is executed and processes 11 files worth of game + data, loading their contents into the 'GAMES' table. + + +. playerSummarization begins processing and fails after 5 + minutes. + +Run 2: + + +. playerLoad is not run, since it has already completed + successfully, and allow-start-if-complete is 'false' (the + default). + + +. gameLoad is executed again and processes another 2 files, + loading their contents into the 'GAMES' table as well (with a + process indicator indicating they have yet to be processed) + + +. playerSummarization begins processing of all remaining game + data (filtering using the process indicator) and fails again after + 30 minutes. + +Run 3: + + +. playerLoad is not run, since it has already completed + successfully, and allow-start-if-complete is 'false' (the + default). + + +. gameLoad is executed again and processes another 2 files, + loading their contents into the 'GAMES' table as well (with a + process indicator indicating they have yet to be processed) + + +. playerSummarization is not start, and the job is immediately + killed, since this is the third execution of playerSummarization, + and its limit is only 2. The limit must either be raised, or the + `Job` must be executed as a new + `JobInstance`. + +[[configuringSkip]] + + +==== Configuring Skip Logic + +There are many scenarios where errors encountered while processing + should not result in `Step` failure, but should be + skipped instead. This is usually a decision that must be made by someone + who understands the data itself and what meaning it has. Financial data, + for example, may not be skippable because it results in money being + transferred, which needs to be completely accurate. Loading a list of + vendors, on the other hand, might allow for skips. If a vendor is not + loaded because it was formatted incorrectly or was missing necessary + information, then there probably won't be issues. Usually these bad + records are logged as well, which will be covered later when discussing + listeners. + + + +[source, xml] +---- + + + + + + + + + +---- + +In this example, a `FlatFileItemReader` is + used, and if at any point a + `FlatFileParseException` is thrown, it will be + skipped and counted against the total skip limit of 10. Separate counts + are made of skips on read, process and write inside the step execution, + and the limit applies across all. Once the skip limit is reached, the + next exception found will cause the step to fail. + +One problem with the example above is that any other exception + besides a `FlatFileParseException` will cause the + `Job` to fail. In certain scenarios this may be the + correct behavior. However, in other scenarios it may be easier to + identify which exceptions should cause failure and skip everything + else: + + + +[source, xml] +---- + + + + + + + + + + +---- + +By 'including' `java.lang.Exception` as a + skippable exception class, the configuration indicates that all + `Exceptions` are skippable. However, by 'excluding' + `java.io.FileNotFoundException`, the configuration + refines the list of skippable exception classes to be all + `Exceptions` __except__ + `FileNotFoundException`. Any excluded exception + classes will be fatal if encountered (i.e. not skipped). + +For any exception encountered, the skippability will be determined + by the nearest superclass in the class hierarchy. Any unclassifed + exception will be treated as 'fatal'. The order of the + `` and `` elements + does not matter. + +[[retryLogic]] + + +==== Configuring Retry Logic + +In most cases you want an exception to cause either a skip or + `Step` failure. However, not all exceptions are + deterministic. If a `FlatFileParseException` is + encountered while reading, it will always be thrown for that record; + resetting the `ItemReader` will not help. However, + for other exceptions, such as a + `DeadlockLoserDataAccessException`, which indicates + that the current process has attempted to update a record that another + process holds a lock on, waiting and trying again might result in + success. In this case, retry should be configured: + + +[source, xml] +---- + + + + + + + + + +---- +The `Step` allows a limit for the number of + times an individual item can be retried, and a list of exceptions that + are 'retryable'. More details on how retry works can be found in <>. + +[[controllingRollback]] + + +==== Controlling Rollback + +By default, regardless of retry or skip, any exceptions thrown + from the ItemWriter will cause the transaction + controlled by the `Step` to rollback. If skip is + configured as described above, exceptions thrown from the + `ItemReader` will not cause a rollback. However, + there are many scenarios in which exceptions thrown from the + ItemWriter should not cause a rollback because no + action has taken place to invalidate the transaction. For this reason, + the `Step` can be configured with a list of + exceptions that should not cause rollback. + + +[source, xml] +---- + + + + + + + + +---- + +[[transactionalReaders]] + + +===== Transactional Readers + +The basic contract of the `ItemReader` is + that it is forward only. The step buffers reader input, so that in the + case of a rollback the items don't need to be re-read from the reader. + However, there are certain scenarios in which the reader is built on + top of a transactional resource, such as a JMS queue. In this case, + since the queue is tied to the transaction that is rolled back, the + messages that have been pulled from the queue will be put back on. For + this reason, the step can be configured to not buffer the + items: + + +[source, xml] +---- + + + + + +---- + +[[transactionAttributes]] + +==== Transaction Attributes + +Transaction attributes can be used to control the isolation, + propagation, and timeout settings. More information on setting + transaction attributes can be found in the spring core + documentation. + + +[source, xml] +---- + + + + + + +---- + +[[registeringItemStreams]] + + +==== Registering ItemStreams with the Step + +The step has to take care of `ItemStream` + callbacks at the necessary points in its lifecycle. (for more + information on the `ItemStream` interface, please + refer to <>) This is vital if a step fails, + and might need to be restarted, because the + `ItemStream` interface is where the step gets the + information it needs about persistent state between executions. + +If the `ItemReader`, + `ItemProcessor`, or + ItemWriter itself implements the + `ItemStream` interface, then these will be + registered automatically. Any other streams need to be registered + separately. This is often the case where there are indirect dependencies + such as delegates being injected into the reader and writer. A stream + can be registered on the `Step` through the + 'streams' element, as illustrated below: + + +[source, xml] +---- + + + + + + + + + + + + + + + + + + + +---- + +In the example above, the + `CompositeItemWriter` is not an + `ItemStream`, but both of its delegates are. + Therefore, both delegate writers must be explicitly registered as + streams in order for the framework to handle them correctly. The + `ItemReader` does not need to be explicitly + registered as a stream because it is a direct property of the + `Step`. The step will now be restartable and the + state of the reader and writer will be correctly persisted in the event + of a failure. + +[[interceptingStepExecution]] + + +==== Intercepting Step Execution + +Just as with the `Job`, there are many events + during the execution of a `Step` where a user may + need to perform some functionality. For example, in order to write out + to a flat file that requires a footer, the + ItemWriter needs to be notified when the + `Step` has been completed, so that the footer can + written. This can be accomplished with one of many + `Step` scoped listeners. + +Any class that implements one of the extensions + of `StepListener` (but not that interface + itself since it is empty) can be applied to a step via the + listeners element. The listeners element is valid inside a + step, tasklet or chunk declaration. It is recommended that you + declare the listeners at the level which its function applies, + or if it is multi-featured + (e.g. `StepExecutionListener` + and `ItemReadListener`) then declare it at + the most granular level that it applies (chunk in the example + given). + + +[source, xml] +---- + + + + + + + + +---- + +An `ItemReader`, + ItemWriter or + `ItemProcessor` that itself implements one of the + `StepListener` interfaces will be registered + automatically with the `Step` if using the + namespace `` element, or one of the the + `*StepFactoryBean` factories. This only applies to + components directly injected into the `Step`: if + the listener is nested inside another component, it needs to be + explicitly registered (as described above). + +In addition to the `StepListener` interfaces, + annotations are provided to address the same concerns. Plain old Java + objects can have methods with these annotations that are then converted + into the corresponding `StepListener` type. It is + also common to annotate custom implementations of chunk components like + `ItemReader` or ItemWriter + or `Tasklet`. The annotations are analysed by the + XML parser for the `` elements, so all you + need to do is use the XML namespace to register the listeners with a + step. + +[[stepExecutionListener]] + + +===== StepExecutionListener + +`StepExecutionListener` represents the most + generic listener for `Step` execution. It allows + for notification before a `Step` is started and + after it has ends, whether it ended normally or failed: + + +[source, java] +---- +public interface StepExecutionListener extends StepListener { + + void beforeStep(StepExecution stepExecution); + + ExitStatus afterStep(StepExecution stepExecution); + +} +---- + +ExitStatus is the return type of + `afterStep` in order to allow listeners the + chance to modify the exit code that is returned upon completion of a + `Step`. + +The annotations corresponding to this interface are: + + +* `@BeforeStep` + + +* `@AfterStep` + +[[chunkListener]] + + +===== ChunkListener + +A chunk is defined as the items processed within the scope of a + transaction. Committing a transaction, at each commit interval, + commits a 'chunk'. A `ChunkListener` can be + useful to perform logic before a chunk begins processing or after a + chunk has completed successfully: + + +[source, java] +---- +public interface ChunkListener extends StepListener { + + void beforeChunk(); + void afterChunk(); + +} +---- + +The beforeChunk method is called after + the transaction is started, but before read + is called on the `ItemReader`. Conversely, + `afterChunk` is called after the chunk has been + committed (and not at all if there is a rollback). + +The annotations corresponding to this interface are: + + +* `@BeforeChunk` + + +* `@AfterChunk` + +A `ChunkListener` can be applied + when there is no chunk declaration: it is + the `TaskletStep` that is responsible for + calling the `ChunkListener` so it applies + to a non-item-oriented tasklet as well (called before and + after the tasklet). + +[[itemReadListener]] + + +===== ItemReadListener + +When discussing skip logic above, it was mentioned that it may + be beneficial to log the skipped records, so that they can be deal + with later. In the case of read errors, this can be done with an + `ItemReaderListener`: + + + +[source, java] +---- +public interface ItemReadListener extends StepListener { + + void beforeRead(); + void afterRead(T item); + void onReadError(Exception ex); + +} +---- + +The `beforeRead` method will be called + before each call to read on the + `ItemReader`. The + afterRead method will be called after each + successful call to read, and will be passed + the item that was read. If there was an error while reading, the + `onReadError` method will be called. The + exception encountered will be provided so that it can be + logged. + +The annotations corresponding to this interface are: + + +* `@BeforeRead` + + +* `@AfterRead` + + +* `@OnReadError` + +[[itemProcessListener]] + + +===== ItemProcessListener + +Just as with the `ItemReadListener`, the + processing of an item can be 'listened' to: + + +[source, java] +---- +public interface ItemProcessListener extends StepListener { + + void beforeProcess(T item); + void afterProcess(T item, S result); + void onProcessError(T item, Exception e); + +} +---- + +The `beforeProcess` method will be called + before `process` on the + `ItemProcessor`, and is handed the item that will + be processed. The `afterProcess` method will be + called after the item has been successfully processed. If there was an + error while processing, the `onProcessError` + method will be called. The exception encountered and the item that was + attempted to be processed will be provided, so that they can be + logged. + +The annotations corresponding to this interface are: + + +* `@BeforeProcess` + + +* `@AfterProcess` + + +* `@OnProcessError` + +[[itemWriteListener]] + + +===== ItemWriteListener + +The writing of an item can be 'listened' to with the + `ItemWriteListener`: + + +[source, java] +---- +public interface ItemWriteListener extends StepListener { + + void beforeWrite(List items); + void afterWrite(List items); + void onWriteError(Exception exception, List items); + +} +---- + +The `beforeWrite` method will be called + before `write` on the + `ItemWriter`, and is handed the item that will be + written. The `afterWrite` method will be called + after the item has been successfully written. If there was an error + while writing, the `onWriteError` method will + be called. The exception encountered and the item that was attempted + to be written will be provided, so that they can be logged. + +The annotations corresponding to this interface are: + + +* `@BeforeWrite` + + +* `@AfterWrite` + + +* `@OnWriteError` + +[[skipListener]] + + +===== SkipListener + +`ItemReadListener`, + `ItemProcessListener`, and + `ItemWriteListener` all provide mechanisms for + being notified of errors, but none will inform you that a record has + actually been skipped. `onWriteError`, for + example, will be called even if an item is retried and successful. For + this reason, there is a separate interface for tracking skipped + items: + + +[source, java] +---- +public interface SkipListener extends StepListener { + + void onSkipInRead(Throwable t); + void onSkipInProcess(T item, Throwable t); + void onSkipInWrite(S item, Throwable t); + +} +---- + +`onSkipInRead` will be called whenever an + item is skipped while reading. It should be noted that rollbacks may + cause the same item to be registered as skipped more than once. + `onSkipInWrite` will be called when an item is + skipped while writing. Because the item has been read successfully + (and not skipped), it is also provided the item itself as an + argument. + +The annotations corresponding to this interface are: + + +* `@OnSkipInRead` + + +* `@OnSkipInWrite` + + +* `@OnSkipInProcess` + +[[skipListenersAndTransactions]] + + +====== SkipListeners and Transactions + +One of the most common use cases for a + `SkipListener` is to log out a skipped item, so + that another batch process or even human process can be used to + evaluate and fix the issue leading to the skip. Because there are + many cases in which the original transaction may be rolled back, + Spring Batch makes two guarantees: + + +. The appropriate skip method (depending on when the error + happened) will only be called once per item. + + +. The `SkipListener` will always be + called just before the transaction is committed. This is to + ensure that any transactional resources call by the listener are + not rolled back by a failure within the + `ItemWriter`. + +[[taskletStep]] + + +=== TaskletStep + +Chunk-oriented processing is not the only way to process in a + `Step`. What if a `Step` must + consist as a simple stored procedure call? You could implement the call as + an `ItemReader` and return null after the procedure + finishes, but it is a bit unnatural since there would need to be a no-op + `ItemWriter`. Spring Batch provides the + `TaskletStep` for this scenario. + +The `Tasklet` is a simple interface that has + one method, `execute`, which will be a called + repeatedly by the `TaskletStep` until it either + returns `RepeatStatus.FINISHED` or throws an exception to + signal a failure. Each call to the `Tasklet` is + wrapped in a transaction. `Tasklet` implementors + might call a stored procedure, a script, or a simple SQL update statement. + To create a `TaskletStep`, the 'ref' attribute of the + element should reference a bean defining a + `Tasklet` object; no element should be + used within the : + + +[source, xml] +---- + + + +---- + + +[NOTE] +==== +`TaskletStep` will automatically register the + tasklet as `StepListener` if it implements this + interface + +==== + + +[[taskletAdapter]] + + +==== TaskletAdapter + +As with other adapters for the `ItemReader` + and `ItemWriter` interfaces, the + `Tasklet` interface contains an implementation that + allows for adapting itself to any pre-existing class: + `TaskletAdapter`. An example where this may be + useful is an existing DAO that is used to update a flag on a set of + records. The `TaskletAdapter` can be used to call + this class without having to write an adapter for the + `Tasklet` interface: + + +[source, xml] +---- + + + + + + +---- + +[[exampleTaskletImplementation]] + + +==== Example Tasklet Implementation + +Many batch jobs contain steps that must be done before the main + processing begins in order to set up various resources or after + processing has completed to cleanup those resources. In the case of a + job that works heavily with files, it is often necessary to delete + certain files locally after they have been uploaded successfully to + another location. The example below taken from the Spring Batch samples + project, is a `Tasklet` implementation with just + such a responsibility: + + +[source, java] +---- +public class FileDeletingTasklet implements Tasklet, InitializingBean { + + private Resource directory; + + public RepeatStatus execute(StepContribution contribution, + ChunkContext chunkContext) throws Exception { + File dir = directory.getFile(); + Assert.state(dir.isDirectory()); + + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + boolean deleted = files[i].delete(); + if (!deleted) { + throw new UnexpectedJobExecutionException("Could not delete file " + + files[i].getPath()); + } + } + return RepeatStatus.FINISHED; + } + + public void setDirectoryResource(Resource directory) { + this.directory = directory; + } + + public void afterPropertiesSet() throws Exception { + Assert.notNull(directory, "directory must be set"); + } +} +---- + +The above `Tasklet` implementation will + delete all files within a given directory. It should be noted that the + `execute` method will only be called once. All + that is left is to reference the `Tasklet` from the + `Step`: + + +[source, xml] +---- + + + + + + + + + + + + + +---- + +[[controllingStepFlow]] + + +=== Controlling Step Flow + +With the ability to group steps together within an owning job comes + the need to be able to control how the job 'flows' from one step to + another. The failure of a `Step` doesn't necessarily + mean that the `Job` should fail. Furthermore, there + may be more than one type of 'success' which determines which + `Step` should be executed next. Depending upon how a + group of `Steps` is configured, certain steps may not even be processed at + all. + +[[SequentialFlow]] + + +==== Sequential Flow + +The simplest flow scenario is a job where all of the steps execute + sequentially: + +.Sequential Flow +image::{batch-asciidoc}images/sequential-flow.png[Sequential Flow, scaledwidth="60%"] + +This can be achieved using the 'next' attribute of the step + element: + + +[source, xml] +---- + + + + + +---- + +In the scenario above, 'step A' will execute + first because it is the first `Step` listed. If + 'step A' completes normally, then 'step B' will execute, and so on. + However, if 'step A' fails, then the entire `Job` + will fail and 'step B' will not execute. + + +[NOTE] +==== +With the Spring Batch namespace, the first step listed in the + configuration will __always__ be the first step + executed by the `Job`. The order of the other + step elements does not matter, but the first step must always appear + first in the xml. +==== + + +[[conditionalFlow]] + + +==== Conditional Flow + +In the example above, there are only two possibilities: + + +. The `Step` is successful and the next + `Step` should be executed. + + +. The `Step` failed and thus the + `Job` should fail. + +In many cases, this may be sufficient. However, what about a + scenario in which the failure of a `Step` should + trigger a different `Step`, rather than causing + failure? + +.Conditional Flow +image::{batch-asciidoc}images/conditional-flow.png[Conditional Flow, scaledwidth="60%"] + +[[nextElement]] +In order to handle more complex scenarios, the + Spring Batch namespace allows transition elements to be defined within + the step element. One such transition is the "next" element. Like the + "next" attribute, the "next" element will tell the + `Job` which `Step` to execute + next. However, unlike the attribute, any number of "next" elements are + allowed on a given `Step`, and there is no default + behavior the case of failure. This means that if transition elements are + used, then all of the behavior for the `Step`'s + transitions must be defined explicitly. Note also that a single step + cannot have both a "next" attribute and a transition element. + +The next element specifies a pattern to match and the step to + execute next: + + +[source, xml] +---- + + + + + + + + +---- + +The "on" attribute of a transition element uses a simple + pattern-matching scheme to match the `ExitStatus` + that results from the execution of the `Step`. Only + two special characters are allowed in the pattern: + + +* "*" will zero or more characters + + +* "?" will match exactly one character + +For example, "c*t" will match "cat" and "count", while "c?t" will + match "cat" but not "count". + +While there is no limit to the number of transition elements on a + `Step`, if the `Step`'s + execution results in an `ExitStatus` that is not + covered by an element, then the framework will throw an exception and + the `Job` will fail. The framework will + automatically order transitions from most specific to + least specific. This means that even if the elements were swapped for + "stepA" in the example above, an `ExitStatus` of + "FAILED" would still go to "stepC". + +[[batchStatusVsExitStatus]] + + +===== Batch Status vs. Exit Status + +When configuring a `Job` for conditional + flow, it is important to understand the difference between + BatchStatus and + `ExitStatus`. BatchStatus + is an enumeration that is a property of both + JobExecution and + `StepExecution` and is used by the framework to + record the status of a `Job` or + `Step`. It can be one of the following values: + COMPLETED, STARTING, STARTED, STOPPING, STOPPED, FAILED, ABANDONED or + UNKNOWN. Most of them are self explanatory: COMPLETED is the status + set when a step or job has completed successfully, FAILED is set when + it fails, and so on. The example above contains the following 'next' + element: + + +[source, xml] +---- + +---- + +At first glance, it would appear that the 'on' attribute + references the BatchStatus of the + `Step` to which it belongs. However, it actually + references the `ExitStatus` of the + `Step`. As the name implies, + `ExitStatus` represents the status of a + `Step` after it finishes execution. More + specifically, the 'next' element above references the exit code of the + `ExitStatus`. To write it in English, it says: + "go to stepB if the exit code is FAILED". By default, the exit code is + always the same as the BatchStatus for the + `Step`, which is why the entry above works. However, what if the exit + code needs to be different? A good example comes from the skip sample + job within the samples project: + + +[source, xml] +---- + + + + + +---- + +The above step has three possibilities: + + +. The `Step` failed, in which case the + job should fail. + + +. The `Step` completed + successfully. + + +. The `Step` completed successfully, but + with an exit code of 'COMPLETED WITH SKIPS'. In this case, a + different step should be run to handle the errors. + +The above configuration will work. However, something needs to + change the exit code based on the condition of the execution having + skipped records: + + +[source, java] +---- +public class SkipCheckingListener extends StepExecutionListenerSupport { + public ExitStatus afterStep(StepExecution stepExecution) { + String exitCode = stepExecution.getExitStatus().getExitCode(); + if (!exitCode.equals(ExitStatus.FAILED.getExitCode()) && + stepExecution.getSkipCount() > 0) { + return new ExitStatus("COMPLETED WITH SKIPS"); + } + else { + return null; + } + } +} +---- + +The above code is a `StepExecutionListener` + that first checks to make sure the `Step` was + successful, and next if the skip count on the + `StepExecution` is higher than 0. If both + conditions are met, a new `ExitStatus` with an + exit code of "COMPLETED WITH SKIPS" is returned. + +[[configuringForStop]] + + +==== Configuring for Stop + +After the discussion of <>, one might wonder how the + `BatchStatus` and `ExitStatus` + are determined for the `Job`. While these statuses + are determined for the `Step` by the code that is + executed, the statuses for the `Job` will be + determined based on the configuration. + +So far, all of the job configurations discussed have had at least + one final `Step` with no transitions. For example, + after the following step executes, the `Job` will + end: + + +[source, xml] +---- + +---- + +If no transitions are defined for a `Step`, + then the `Job`'s statuses will be defined as + follows: + + +* If the `Step` ends with + `ExitStatus` FAILED, then the + `Job`'s `BatchStatus` and + `ExitStatus` will both be FAILED. + + +* Otherwise, the `Job`'s + `BatchStatus` and + `ExitStatus` will both be COMPLETED. + +While this method of terminating a batch job is sufficient for + some batch jobs, such as a simple sequential step job, custom defined + job-stopping scenarios may be required. For this purpose, Spring Batch + provides three transition elements to stop a `Job` + (in addition to the <> + that we discussed previously). Each of these stopping elements will stop + a `Job` with a particular + `BatchStatus`. It is important to note that the + stop transition elements will have no effect on either the + `BatchStatus` or `ExitStatus` + of any `Steps` in the `Job`: + these elements will only affect the final statuses of the + `Job`. For example, it is possible for every step + in a job to have a status of FAILED but the job to have a status of + COMPLETED, or vise versa. + +[[endElement]] + + +===== The 'End' Element + +The 'end' element instructs a `Job` to stop + with a `BatchStatus` of COMPLETED. A + `Job` that has finished with status COMPLETED + cannot be restarted (the framework will throw a + `JobInstanceAlreadyCompleteException`). The 'end' + element also allows for an optional 'exit-code' attribute that can be + used to customize the `ExitStatus` of the + `Job`. If no 'exit-code' attribute is given, then + the `ExitStatus` will be "COMPLETED" by default, + to match the `BatchStatus`. + +In the following scenario, if step2 fails, then the + `Job` will stop with a + `BatchStatus` of COMPLETED and an + `ExitStatus` of "COMPLETED" and step3 will not + execute; otherwise, execution will move to step3. Note that if step2 + fails, the `Job` will not be restartable (because + the status is COMPLETED). + + +[source, xml] +---- + + + + + + + + +---- + +[[failElement]] + + +===== The 'Fail' Element + +The 'fail' element instructs a `Job` to + stop with a `BatchStatus` of FAILED. Unlike the + 'end' element, the 'fail' element will not prevent the + `Job` from being restarted. The 'fail' element + also allows for an optional 'exit-code' attribute that can be used to + customize the `ExitStatus` of the + `Job`. If no 'exit-code' attribute is given, then + the `ExitStatus` will be "FAILED" by default, to + match the `BatchStatus`. + +In the following scenario, if step2 fails, then the + `Job` will stop with a + `BatchStatus` of FAILED and an + `ExitStatus` of "EARLY TERMINATION" and step3 + will not execute; otherwise, execution will move to step3. + Additionally, if step2 fails, and the `Job` is + restarted, then execution will begin again on step2. + + +[source, xml] +---- + + + + + + + + +---- + +[[stopElement]] + + +===== The 'Stop' Element + +The 'stop' element instructs a `Job` to + stop with a `BatchStatus` of STOPPED. Stopping a + `Job` can provide a temporary break in processing + so that the operator can take some action before restarting the + `Job`. The 'stop' element requires a 'restart' + attribute that specifies the step where execution should pick up when + the `Job is restarted`. + +In the following scenario, if step1 finishes with COMPLETE, then + the job will then stop. Once it is restarted, execution will begin on + step2. + + +[source, xml] +---- + + + + + +---- + +[[programmaticFlowDecisions]] + + +==== Programmatic Flow Decisions + +In some situations, more information than the + `ExitStatus` may be required to decide which step + to execute next. In this case, a + `JobExecutionDecider` can be used to assist in the + decision. + + +[source, java] +---- +public class MyDecider implements JobExecutionDecider { + public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { + if (someCondition) { + return "FAILED"; + } + else { + return "COMPLETED"; + } + } +} +---- + +In the job configuration, a "decision" tag will specify the + decider to use as well as all of the transitions. + + +[source, xml] +---- + + + + + + + + + + + + + +---- + +[[split-flows]] + + +==== Split Flows + +Every scenario described so far has involved a + `Job` that executes its + `Steps` one at a time in a linear fashion. In + addition to this typical style, the Spring Batch namespace also allows + for a job to be configured with parallel flows using the 'split' + element. As is seen below, the 'split' element contains one or more + 'flow' elements, where entire separate flows can be defined. A 'split' + element may also contain any of the previously discussed transition + elements such as the 'next' attribute or the 'next', 'end', 'fail', or + 'pause' elements. + + +[source, xml] +---- + + + + + + + + + + +---- + +[[external-flows]] + + +==== Externalizing Flow Definitions and Dependencies Between Jobs + +Part of the flow in a job can be externalized as a separate bean + definition, and then re-used. There are two ways to do this, and the + first is to simply declare the flow as a reference to one defined + elsewhere: + + +[source, xml] +---- + + + + + + + + + +---- + +The effect of defining an external flow like this is simply to + insert the steps from the external flow into the job as if they had been + declared inline. In this way many jobs can refer to the same template + flow and compose such templates into different logical flows. This is + also a good way to separate the integration testing of the individual + flows. + +The other form of an externalized flow is to use a + `JobStep`. A `JobStep` is + similar to a `FlowStep`, but actually creates and + launches a separate job execution for the steps in the flow specified. + Here is an example: + + +[source, xml] +---- + + + + + + +... + + + + +---- + +The job parameters extractor is a strategy that determines how a + the `ExecutionContext` for the + `Step` is converted into + JobParameters for the `Job` that is executed. The + `JobStep` is useful when you want to have some more + granular options for monitoring and reporting on jobs and steps. Using + `JobStep` is also often a good answer to the + question: "How do I create dependencies between jobs?". It is a good way + to break up a large system into smaller modules and control the flow of + jobs. + +[[late-binding]] + + +=== Late Binding of Job and Step Attributes + +Both the XML and Flat File examples above use the Spring + `Resource` abstraction to obtain a file. This works + because `Resource` has a getFile + method, which returns a java.io.File. Both XML and + Flat File resources can be configured using standard Spring + constructs: + + +[source, xml] +---- + + + +---- + +The above `Resource` will load the file from + the file system location specified. Note that absolute locations have to + start with a double slash ("//"). In most spring applications, this + solution is good enough because the names of these are known at compile + time. However, in batch scenarios, the file name may need to be determined + at runtime as a parameter to the job. This could be solved using '-D' + parameters, i.e. a system property: + + +[source, xml] +---- + + + +---- + +All that would be required for this solution to work would be a + system argument (-Dinput.file.name="file://file.txt"). (Note that although + a `PropertyPlaceholderConfigurer` can be used here, + it is not necessary if the system property is always set because the + `ResourceEditor` in Spring already filters and does + placeholder replacement on system properties.) + +Often in a batch setting it is preferable to parameterize the file + name in the `JobParameters` of the + job, instead of through system properties, and access them that way. To + accomplish this, Spring Batch allows for the late binding of various `Job` + and `Step` attributes: + + +[source, xml] +---- + + + +---- + +Both the JobExecution and + `StepExecution` level + `ExecutionContext` can be accessed in the same + way: + + +[source, xml] +---- + + + +---- + + +[source, xml] +---- + + + +---- + + +[NOTE] +==== +Any bean that uses late-binding must be declared with + scope="step". See for <> more + information. +==== + + + +[NOTE] +==== +If you are using Spring 3.0 (or above) the expressions in + step-scoped beans are in the Spring Expression Language, a powerful + general purpose language with many interesting features. To provide + backward compatibility, if Spring Batch detects the presence of older + versions of Spring it uses a native expression language that is less + powerful, and has slightly different parsing rules. The main difference + is that the map keys in the example above do not need to be quoted with + Spring 2.5, but the quotes are mandatory in Spring 3.0. +==== + + +[[step-scope]] + + +==== Step Scope + +All of the late binding examples from above have a scope of "step" + declared on the bean definition: + + +[source, xml] +---- + + + +---- + +Using a scope of `Step` is required in order + to use late binding since the bean cannot actually be instantiated until + the `Step` starts, which allows the attributes to + be found. Because it is not part of the Spring container by default, the + scope must be added explicitly, either by using the + `batch` namespace: + + +[source, xml] +---- + + +... + +---- + +or by including a bean definition explicitly for the + StepScope (but not both): + + +[source, xml] +---- + +---- + +[[job-scope]] + + +==== Job Scope + +`Job` scope, introduced in Spring Batch 3.0 is similar to `Step` scope + in configuration but is a Scope for the `Job` context so there is only one + instance of such a bean per executing job. Additionally, support is provided + for late binding of references accessible from the JobContext using + #{..} placeholders. Using this feature, bean properties can be pulled from + the job or job execution context and the job parameters. E.g. + + + +[source, xml] +---- + + + +---- + + +[source, xml] +---- + + + +---- + +Because it is not part of the Spring container by default, the scope + must be added explicitly, either by using the `batch` namespace: + + +[source, xml] +---- + + + + ... + +---- + +Or by including a bean definition explicitly for the JobScope (but not both): + +[source, xml] +---- + +---- + diff --git a/spring-batch-docs/asciidoc/stylesheets/spring.css b/spring-batch-docs/asciidoc/stylesheets/spring.css new file mode 100644 index 000000000..faa7c4732 --- /dev/null +++ b/spring-batch-docs/asciidoc/stylesheets/spring.css @@ -0,0 +1,691 @@ +@import url(https://fonts.googleapis.com/css?family=Varela+Round|Montserrat:400,700); +/*! normalize.css v2.1.2 | MIT License | git.io/normalize */ +/* ========================================================================== HTML5 display definitions ========================================================================== */ +/** Correct `block` display not defined in IE 8/9. */ +article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary { display: block; } + +/** Correct `inline-block` display not defined in IE 8/9. */ +audio, canvas, video { display: inline-block; } + +/** Prevent modern browsers from displaying `audio` without controls. Remove excess height in iOS 5 devices. */ +audio:not([controls]) { display: none; height: 0; } + +/** Address `[hidden]` styling not present in IE 8/9. Hide the `template` element in IE, Safari, and Firefox < 22. */ +[hidden], template { display: none; } + +script { display: none !important; } + +/* ========================================================================== Base ========================================================================== */ +/** 1. Set default font family to sans-serif. 2. Prevent iOS text size adjust after orientation change, without disabling user zoom. */ +html { font-family: sans-serif; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ } + +/** Remove default margin. */ +body { margin: 0; } + +/* ========================================================================== Links ========================================================================== */ +/** Remove the gray background color from active links in IE 10. */ +a { background: transparent; } + +/** Address `outline` inconsistency between Chrome and other browsers. */ +a:focus { outline: thin dotted; } + +/** Improve readability when focused and also mouse hovered in all browsers. */ +a:active, a:hover { outline: 0; } + +/* ========================================================================== Typography ========================================================================== */ +/** Address variable `h1` font-size and margin within `section` and `article` contexts in Firefox 4+, Safari 5, and Chrome. */ +h1 { font-size: 2em; margin: 0.67em 0; } + +/** Address styling not present in IE 8/9, Safari 5, and Chrome. */ +abbr[title] { border-bottom: 1px dotted; } + +/** Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome. */ +b, strong { font-weight: bold; } + +/** Address styling not present in Safari 5 and Chrome. */ +dfn { font-style: italic; } + +/** Address differences between Firefox and other browsers. */ +hr { -moz-box-sizing: content-box; box-sizing: content-box; height: 0; } + +/** Address styling not present in IE 8/9. */ +mark { background: #ff0; color: #000; } + +/** Correct font family set oddly in Safari 5 and Chrome. */ +code, kbd, pre, samp { font-family: monospace, serif; font-size: 1em; } + +/** Improve readability of pre-formatted text in all browsers. */ +pre { white-space: pre-wrap; } + +/** Set consistent quote types. */ +q { quotes: "\201C" "\201D" "\2018" "\2019"; } + +/** Address inconsistent and variable font size in all browsers. */ +small { font-size: 80%; } + +/** Prevent `sub` and `sup` affecting `line-height` in all browsers. */ +sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } + +sup { top: -0.5em; } + +sub { bottom: -0.25em; } + +/* ========================================================================== Embedded content ========================================================================== */ +/** Remove border when inside `a` element in IE 8/9. */ +img { border: 0; } + +/** Correct overflow displayed oddly in IE 9. */ +svg:not(:root) { overflow: hidden; } + +/* ========================================================================== Figures ========================================================================== */ +/** Address margin not present in IE 8/9 and Safari 5. */ +figure { margin: 0; } + +/* ========================================================================== Forms ========================================================================== */ +/** Define consistent border, margin, and padding. */ +fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } + +/** 1. Correct `color` not being inherited in IE 8/9. 2. Remove padding so people aren't caught out if they zero out fieldsets. */ +legend { border: 0; /* 1 */ padding: 0; /* 2 */ } + +/** 1. Correct font family not being inherited in all browsers. 2. Correct font size not being inherited in all browsers. 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome. */ +button, input, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 2 */ margin: 0; /* 3 */ } + +/** Address Firefox 4+ setting `line-height` on `input` using `!important` in the UA stylesheet. */ +button, input { line-height: normal; } + +/** Address inconsistent `text-transform` inheritance for `button` and `select`. All other form control elements do not inherit `text-transform` values. Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+. Correct `select` style inheritance in Firefox 4+ and Opera. */ +button, select { text-transform: none; } + +/** 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` and `video` controls. 2. Correct inability to style clickable `input` types in iOS. 3. Improve usability and consistency of cursor style between image-type `input` and others. */ +button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; /* 2 */ cursor: pointer; /* 3 */ } + +/** Re-set default cursor for disabled elements. */ +button[disabled], html input[disabled] { cursor: default; } + +/** 1. Address box sizing set to `content-box` in IE 8/9. 2. Remove excess padding in IE 8/9. */ +input[type="checkbox"], input[type="radio"] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } + +/** 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome. 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome (include `-moz` to future-proof). */ +input[type="search"] { -webkit-appearance: textfield; /* 1 */ -moz-box-sizing: content-box; -webkit-box-sizing: content-box; /* 2 */ box-sizing: content-box; } + +/** Remove inner padding and search cancel button in Safari 5 and Chrome on OS X. */ +input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } + +/** Remove inner padding and border in Firefox 4+. */ +button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } + +/** 1. Remove default vertical scrollbar in IE 8/9. 2. Improve readability and alignment in all browsers. */ +textarea { overflow: auto; /* 1 */ vertical-align: top; /* 2 */ } + +/* ========================================================================== Tables ========================================================================== */ +/** Remove most spacing between table cells. */ +table { border-collapse: collapse; border-spacing: 0; } + +meta.foundation-mq-small { font-family: "only screen and (min-width: 768px)"; width: 768px; } + +meta.foundation-mq-medium { font-family: "only screen and (min-width:1280px)"; width: 1280px; } + +meta.foundation-mq-large { font-family: "only screen and (min-width:1440px)"; width: 1440px; } + +*, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } + +html, body { font-size: 100%; } + +body { background: white; color: #34302d; padding: 0; margin: 0; font-family: "Varela Round", sans-serif; font-weight: normal; font-style: normal; line-height: 1; position: relative; cursor: auto; } + +a:hover { cursor: pointer; } + +img, object, embed { max-width: 100%; height: auto; } + +object, embed { height: 100%; } + +img { -ms-interpolation-mode: bicubic; } + +#map_canvas img, #map_canvas embed, #map_canvas object, .map_canvas img, .map_canvas embed, .map_canvas object { max-width: none !important; } + +.left { float: left !important; } + +.right { float: right !important; } + +.text-left { text-align: left !important; } + +.text-right { text-align: right !important; } + +.text-center { text-align: center !important; } + +.text-justify { text-align: justify !important; } + +.hide { display: none; } + +.antialiased { -webkit-font-smoothing: antialiased; } + +img { display: inline-block; vertical-align: middle; } + +textarea { height: auto; min-height: 50px; } + +select { width: 100%; } + +object, svg { display: inline-block; vertical-align: middle; } + +.center { margin-left: auto; margin-right: auto; } + +.spread { width: 100%; } + +p.lead, .paragraph.lead > p, #preamble > .sectionbody > .paragraph:first-of-type p { font-size: 1.21875em; line-height: 1.6; } + +.subheader, .admonitionblock td.content > .title, .audioblock > .title, .exampleblock > .title, .imageblock > .title, .listingblock > .title, .literalblock > .title, .stemblock > .title, .openblock > .title, .paragraph > .title, .quoteblock > .title, table.tableblock > .title, .verseblock > .title, .videoblock > .title, .dlist > .title, .olist > .title, .ulist > .title, .qlist > .title, .hdlist > .title { line-height: 1.45; color: #0b0a0a; font-weight: normal; margin-top: 0; margin-bottom: 0.25em; } + +/* Typography resets */ +div, dl, dt, dd, ul, ol, li, h1, h2, h3, #toctitle, .sidebarblock > .content > .title, h4, h5, h6, pre, form, p, blockquote, th, td { margin: 0; padding: 0; direction: ltr; } + +/* Default Link Styles */ +a { color: #548e2e; text-decoration: underline; line-height: inherit; } +a:hover, a:focus { color: #487a28; } +a img { border: none; } + +/* Default paragraph styles */ +p { font-family: inherit; font-weight: normal; font-size: 1em; line-height: 1.6; margin-bottom: 1.25em; text-rendering: optimizeLegibility; } +p aside { font-size: 0.875em; line-height: 1.35; font-style: italic; } + +/* Default header styles */ +h1, h2, h3, #toctitle, .sidebarblock > .content > .title, h4, h5, h6 { font-family: Montserrat, sans-serif; font-weight: 400; font-style: normal; color: #34302d; text-rendering: optimizeLegibility; margin-top: 1em; margin-bottom: 0.5em; line-height: 1.0125em; } +h1 small, h2 small, h3 small, #toctitle small, .sidebarblock > .content > .title small, h4 small, h5 small, h6 small { font-size: 60%; color: #867c74; line-height: 0; } + +h1 { font-size: 2.125em; } + +h2 { font-size: 1.6875em; } + +h3, #toctitle, .sidebarblock > .content > .title { font-size: 1.375em; } + +h4 { font-size: 1.125em; } + +h5 { font-size: 1.125em; } + +h6 { font-size: 1em; } + +hr { border: solid #ddddd8; border-width: 1px 0 0; clear: both; margin: 1.25em 0 1.1875em; height: 0; } + +/* Helpful Typography Defaults */ +em, i { font-style: italic; line-height: inherit; } + +strong, b { font-weight: bold; line-height: inherit; } + +small { font-size: 60%; line-height: inherit; } + +code { font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-weight: normal; color: rgba(0, 0, 0, 0.9); } + +/* Lists */ +ul, ol, dl { font-size: 1em; line-height: 1.6; margin-bottom: 1.25em; list-style-position: outside; font-family: inherit; } + +ul, ol { margin-left: 1.5em; } +ul.no-bullet, ol.no-bullet { margin-left: 1.5em; } + +/* Unordered Lists */ +ul li ul, ul li ol { margin-left: 1.25em; margin-bottom: 0; font-size: 1em; /* Override nested font-size change */ } +ul.square li ul, ul.circle li ul, ul.disc li ul { list-style: inherit; } +ul.square { list-style-type: square; } +ul.circle { list-style-type: circle; } +ul.disc { list-style-type: disc; } +ul.no-bullet { list-style: none; } + +/* Ordered Lists */ +ol li ul, ol li ol { margin-left: 1.25em; margin-bottom: 0; } + +/* Definition Lists */ +dl dt { margin-bottom: 0.3125em; font-weight: bold; } +dl dd { margin-bottom: 1.25em; } + +/* Abbreviations */ +abbr, acronym { text-transform: uppercase; font-size: 90%; color: #34302d; border-bottom: 1px dotted #dddddd; cursor: help; } + +abbr { text-transform: none; } + +/* Blockquotes */ +blockquote { margin: 0 0 1.25em; padding: 0.5625em 1.25em 0 1.1875em; border-left: 1px solid #dddddd; } +blockquote cite { display: block; font-size: 0.9375em; color: rgba(0, 0, 0, 0.6); } +blockquote cite:before { content: "\2014 \0020"; } +blockquote cite a, blockquote cite a:visited { color: rgba(0, 0, 0, 0.6); } + +blockquote, blockquote p { line-height: 1.6; color: rgba(0, 0, 0, 0.85); } + +/* Microformats */ +.vcard { display: inline-block; margin: 0 0 1.25em 0; border: 1px solid #dddddd; padding: 0.625em 0.75em; } +.vcard li { margin: 0; display: block; } +.vcard .fn { font-weight: bold; font-size: 0.9375em; } + +.vevent .summary { font-weight: bold; } +.vevent abbr { cursor: auto; text-decoration: none; font-weight: bold; border: none; padding: 0 0.0625em; } + +@media only screen and (min-width: 768px) { h1, h2, h3, #toctitle, .sidebarblock > .content > .title, h4, h5, h6 { line-height: 1.2; } + h1 { font-size: 2.75em; } + h2 { font-size: 2.3125em; } + h3, #toctitle, .sidebarblock > .content > .title { font-size: 1.6875em; } + h4 { font-size: 1.4375em; } } +/* Tables */ +table { background: white; margin-bottom: 1.25em; border: solid 1px #dedede; } +table thead, table tfoot { background: #f7f8f7; font-weight: bold; } +table thead tr th, table thead tr td, table tfoot tr th, table tfoot tr td { padding: 0.5em 0.625em 0.625em; font-size: inherit; color: #34302d; text-align: left; } +table tr th, table tr td { padding: 0.5625em 0.625em; font-size: inherit; color: #34302d; } +table tr.even, table tr.alt, table tr:nth-of-type(even) { background: #f8f8f7; } +table thead tr th, table tfoot tr th, table tbody tr td, table tr td, table tfoot tr td { display: table-cell; line-height: 1.6; } + +body { -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; tab-size: 4; } + +h1, h2, h3, #toctitle, .sidebarblock > .content > .title, h4, h5, h6 { line-height: 1.2; word-spacing: -0.05em; } + +.clearfix:before, .clearfix:after, .float-group:before, .float-group:after { content: " "; display: table; } +.clearfix:after, .float-group:after { clear: both; } + +*:not(pre) > code { font-size: 0.9375em; font-style: normal !important; letter-spacing: 0; padding: 0.1em 0.5ex; word-spacing: -0.15em; background-color: #f7f7f8; -webkit-border-radius: 4px; border-radius: 4px; line-height: 1.45; text-rendering: optimizeSpeed; word-wrap: break-word; } +*:not(pre) > code.nobreak { word-wrap: normal; } +*:not(pre) > code.nowrap { white-space: nowrap; } + +pre, pre > code { line-height: 1.45; color: rgba(0, 0, 0, 0.9); font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-weight: normal; text-rendering: optimizeSpeed; } + +em em { font-style: normal; } + +strong strong { font-weight: normal; } + +.keyseq { color: #6b625c; } + +kbd { font-family: Monaco, Menlo, Consolas, "Courier New", monospace; display: inline-block; color: #34302d; font-size: 0.65em; line-height: 1.45; background-color: #f7f7f7; border: 1px solid #ccc; -webkit-border-radius: 3px; border-radius: 3px; -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 0 0.1em white inset; box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 0 0.1em white inset; margin: 0 0.15em; padding: 0.2em 0.5em; vertical-align: middle; position: relative; top: -0.1em; white-space: nowrap; } + +.keyseq kbd:first-child { margin-left: 0; } + +.keyseq kbd:last-child { margin-right: 0; } + +.menuseq, .menu { color: #191715; } + +b.button:before, b.button:after { position: relative; top: -1px; font-weight: normal; } + +b.button:before { content: "["; padding: 0 3px 0 2px; } + +b.button:after { content: "]"; padding: 0 2px 0 3px; } + +p a > code:hover { color: rgba(0, 0, 0, 0.9); } + +#header, #content, #footnotes, #footer { width: 100%; margin-left: auto; margin-right: auto; margin-top: 0; margin-bottom: 0; max-width: 62.5em; *zoom: 1; position: relative; padding-left: 0.9375em; padding-right: 0.9375em; } +#header:before, #header:after, #content:before, #content:after, #footnotes:before, #footnotes:after, #footer:before, #footer:after { content: " "; display: table; } +#header:after, #content:after, #footnotes:after, #footer:after { clear: both; } + +#content { margin-top: 1.25em; } + +#content:before { content: none; } + +#header > h1:first-child { color: rgba(0, 0, 0, 0.85); margin-top: 2.25rem; margin-bottom: 0; } +#header > h1:first-child + #toc { margin-top: 8px; border-top: 1px solid #ddddd8; } +#header > h1:only-child, body.toc2 #header > h1:nth-last-child(2) { border-bottom: 1px solid #ddddd8; padding-bottom: 8px; } +#header .details { border-bottom: 1px solid #ddddd8; line-height: 1.45; padding-top: 0.25em; padding-bottom: 0.25em; padding-left: 0.25em; color: rgba(0, 0, 0, 0.6); display: -ms-flexbox; display: -webkit-flex; display: flex; -ms-flex-flow: row wrap; -webkit-flex-flow: row wrap; flex-flow: row wrap; } +#header .details span:first-child { margin-left: -0.125em; } +#header .details span.email a { color: rgba(0, 0, 0, 0.85); } +#header .details br { display: none; } +#header .details br + span:before { content: "\00a0\2013\00a0"; } +#header .details br + span.author:before { content: "\00a0\22c5\00a0"; color: rgba(0, 0, 0, 0.85); } +#header .details br + span#revremark:before { content: "\00a0|\00a0"; } +#header #revnumber { text-transform: capitalize; } +#header #revnumber:after { content: "\00a0"; } + +#content > h1:first-child:not([class]) { color: rgba(0, 0, 0, 0.85); border-bottom: 1px solid #ddddd8; padding-bottom: 8px; margin-top: 0; padding-top: 1rem; margin-bottom: 1.25rem; } + +#toc { border-bottom: 1px solid #efefed; padding-bottom: 0.5em; } +#toc > ul { margin-left: 0.125em; } +#toc ul.sectlevel0 > li > a { font-style: italic; } +#toc ul.sectlevel0 ul.sectlevel1 { margin: 0.5em 0; } +#toc ul { font-family: Montserrat, sans-serif; list-style-type: none; } +#toc li { line-height: 1.3334; margin-top: 0.3334em; } +#toc a { text-decoration: none; } +#toc a:active { text-decoration: underline; } + +#toctitle { color: #0b0a0a; font-size: 1.2em; } + +@media only screen and (min-width: 768px) { #toctitle { font-size: 1.375em; } + body.toc2 { padding-left: 15em; padding-right: 0; } + #toc.toc2 { margin-top: 0 !important; background-color: #f1f1f1; position: fixed; width: 15em; left: 0; top: 0; border-right: 1px solid #efefed; border-top-width: 0 !important; border-bottom-width: 0 !important; z-index: 1000; padding: 1.25em 1em; height: 100%; overflow: auto; } + #toc.toc2 #toctitle { margin-top: 0; margin-bottom: 0.8rem; font-size: 1.2em; } + #toc.toc2 > ul { font-size: 0.9em; margin-bottom: 0; } + #toc.toc2 ul ul { margin-left: 0; padding-left: 1em; } + #toc.toc2 ul.sectlevel0 ul.sectlevel1 { padding-left: 0; margin-top: 0.5em; margin-bottom: 0.5em; } + body.toc2.toc-right { padding-left: 0; padding-right: 15em; } + body.toc2.toc-right #toc.toc2 { border-right-width: 0; border-left: 1px solid #efefed; left: auto; right: 0; } } +@media only screen and (min-width: 1280px) { body.toc2 { padding-left: 20em; padding-right: 0; } + #toc.toc2 { width: 20em; } + #toc.toc2 #toctitle { font-size: 1.375em; } + #toc.toc2 > ul { font-size: 0.95em; } + #toc.toc2 ul ul { padding-left: 1.25em; } + body.toc2.toc-right { padding-left: 0; padding-right: 20em; } } +#content #toc { border-style: solid; border-width: 1px; border-color: #d7d7d7; margin-bottom: 1.25em; padding: 1.25em; background: #f1f1f1; -webkit-border-radius: 4px; border-radius: 4px; } +#content #toc > :first-child { margin-top: 0; } +#content #toc > :last-child { margin-bottom: 0; } + +#footer { max-width: 100%; background-color: #34302d; padding: 1.25em; } + +#footer-text { color: #cbcfd2; line-height: 1.44; } + +.sect1 { padding-bottom: 0.625em; } + +@media only screen and (min-width: 768px) { .sect1 { padding-bottom: 1.25em; } } +.sect1 + .sect1 { border-top: 1px solid #efefed; } + +#content h1 > a.anchor, h2 > a.anchor, h3 > a.anchor, #toctitle > a.anchor, .sidebarblock > .content > .title > a.anchor, h4 > a.anchor, h5 > a.anchor, h6 > a.anchor { position: absolute; z-index: 1001; width: 1.5ex; margin-left: -1.5ex; display: block; text-decoration: none !important; visibility: hidden; text-align: center; font-weight: normal; } +#content h1 > a.anchor:before, h2 > a.anchor:before, h3 > a.anchor:before, #toctitle > a.anchor:before, .sidebarblock > .content > .title > a.anchor:before, h4 > a.anchor:before, h5 > a.anchor:before, h6 > a.anchor:before { content: "\00A7"; font-size: 0.85em; display: block; padding-top: 0.1em; } +#content h1:hover > a.anchor, #content h1 > a.anchor:hover, h2:hover > a.anchor, h2 > a.anchor:hover, h3:hover > a.anchor, #toctitle:hover > a.anchor, .sidebarblock > .content > .title:hover > a.anchor, h3 > a.anchor:hover, #toctitle > a.anchor:hover, .sidebarblock > .content > .title > a.anchor:hover, h4:hover > a.anchor, h4 > a.anchor:hover, h5:hover > a.anchor, h5 > a.anchor:hover, h6:hover > a.anchor, h6 > a.anchor:hover { visibility: visible; } +#content h1 > a.link, h2 > a.link, h3 > a.link, #toctitle > a.link, .sidebarblock > .content > .title > a.link, h4 > a.link, h5 > a.link, h6 > a.link { color: #34302d; text-decoration: none; } +#content h1 > a.link:hover, h2 > a.link:hover, h3 > a.link:hover, #toctitle > a.link:hover, .sidebarblock > .content > .title > a.link:hover, h4 > a.link:hover, h5 > a.link:hover, h6 > a.link:hover { color: #262321; } + +.audioblock, .imageblock, .literalblock, .listingblock, .stemblock, .videoblock { margin-bottom: 1.25em; } + +.admonitionblock td.content > .title, .audioblock > .title, .exampleblock > .title, .imageblock > .title, .listingblock > .title, .literalblock > .title, .stemblock > .title, .openblock > .title, .paragraph > .title, .quoteblock > .title, table.tableblock > .title, .verseblock > .title, .videoblock > .title, .dlist > .title, .olist > .title, .ulist > .title, .qlist > .title, .hdlist > .title { text-rendering: optimizeLegibility; text-align: left; font-family: "Varela Round", sans-serif; font-size: 1rem; font-style: italic; } + +table.tableblock > caption.title { white-space: nowrap; overflow: visible; max-width: 0; } + +.paragraph.lead > p, #preamble > .sectionbody > .paragraph:first-of-type p { color: rgba(0, 0, 0, 0.85); } + +table.tableblock #preamble > .sectionbody > .paragraph:first-of-type p { font-size: inherit; } + +.admonitionblock > table { border-collapse: separate; border: 0; background: none; width: 100%; } +.admonitionblock > table td.icon { text-align: center; width: 80px; } +.admonitionblock > table td.icon img { max-width: initial; } +.admonitionblock > table td.icon .title { font-weight: bold; font-family: Montserrat, sans-serif; text-transform: uppercase; } +.admonitionblock > table td.content { padding-left: 1.125em; padding-right: 1.25em; border-left: 1px solid #ddddd8; color: rgba(0, 0, 0, 0.6); } +.admonitionblock > table td.content > :last-child > :last-child { margin-bottom: 0; } + +.exampleblock > .content { border-style: solid; border-width: 1px; border-color: #e6e6e6; margin-bottom: 1.25em; padding: 1.25em; background: white; -webkit-border-radius: 4px; border-radius: 4px; } +.exampleblock > .content > :first-child { margin-top: 0; } +.exampleblock > .content > :last-child { margin-bottom: 0; } + +.sidebarblock { border-style: solid; border-width: 1px; border-color: #d7d7d7; margin-bottom: 1.25em; padding: 1.25em; background: #f1f1f1; -webkit-border-radius: 4px; border-radius: 4px; } +.sidebarblock > :first-child { margin-top: 0; } +.sidebarblock > :last-child { margin-bottom: 0; } +.sidebarblock > .content > .title { color: #0b0a0a; margin-top: 0; text-align: center; } + +.exampleblock > .content > :last-child > :last-child, .exampleblock > .content .olist > ol > li:last-child > :last-child, .exampleblock > .content .ulist > ul > li:last-child > :last-child, .exampleblock > .content .qlist > ol > li:last-child > :last-child, .sidebarblock > .content > :last-child > :last-child, .sidebarblock > .content .olist > ol > li:last-child > :last-child, .sidebarblock > .content .ulist > ul > li:last-child > :last-child, .sidebarblock > .content .qlist > ol > li:last-child > :last-child { margin-bottom: 0; } + +.literalblock pre, .listingblock pre:not(.highlight), .listingblock pre[class="highlight"], .listingblock pre[class^="highlight "], .listingblock pre.CodeRay, .listingblock pre.prettyprint { background: whitesmoke; } +.sidebarblock .literalblock pre, .sidebarblock .listingblock pre:not(.highlight), .sidebarblock .listingblock pre[class="highlight"], .sidebarblock .listingblock pre[class^="highlight "], .sidebarblock .listingblock pre.CodeRay, .sidebarblock .listingblock pre.prettyprint { background: #f2f1f1; } + +.literalblock pre, .literalblock pre[class], .listingblock pre, .listingblock pre[class] { border: 1px solid #dddddd; -webkit-border-radius: 4px; border-radius: 4px; word-wrap: break-word; padding: 1em; font-size: 0.8125em; } +.literalblock pre.nowrap, .literalblock pre[class].nowrap, .listingblock pre.nowrap, .listingblock pre[class].nowrap { overflow-x: auto; white-space: pre; word-wrap: normal; } +@media only screen and (min-width: 768px) { .literalblock pre, .literalblock pre[class], .listingblock pre, .listingblock pre[class] { font-size: 0.90625em; } } +@media only screen and (min-width: 1280px) { .literalblock pre, .literalblock pre[class], .listingblock pre, .listingblock pre[class] { font-size: 1em; } } + +.literalblock.output pre { color: whitesmoke; background-color: rgba(0, 0, 0, 0.9); } + +.listingblock pre.highlightjs { padding: 0; } +.listingblock pre.highlightjs > code { padding: 1em; -webkit-border-radius: 4px; border-radius: 4px; } + +.listingblock > .content { position: relative; } + +.listingblock code[data-lang]:before { display: none; content: attr(data-lang); position: absolute; font-size: 0.75em; top: 0.425rem; right: 0.5rem; line-height: 1; text-transform: uppercase; color: #999; } + +.listingblock:hover code[data-lang]:before { display: block; } + +.listingblock.terminal pre .command:before { content: attr(data-prompt); padding-right: 0.5em; color: #999; } + +.listingblock.terminal pre .command:not([data-prompt]):before { content: "$"; } + +table.pyhltable { border-collapse: separate; border: 0; margin-bottom: 0; background: none; } + +table.pyhltable td { vertical-align: top; padding-top: 0; padding-bottom: 0; line-height: 1.45; } + +table.pyhltable td.code { padding-left: .75em; padding-right: 0; } + +pre.pygments .lineno, table.pyhltable td:not(.code) { color: #999; padding-left: 0; padding-right: .5em; border-right: 1px solid #ddddd8; } + +pre.pygments .lineno { display: inline-block; margin-right: .25em; } + +table.pyhltable .linenodiv { background: none !important; padding-right: 0 !important; } + +.quoteblock { margin: 0 1em 1.25em 1.5em; display: table; } +.quoteblock > .title { margin-left: -1.5em; margin-bottom: 0.75em; } +.quoteblock blockquote, .quoteblock blockquote p { color: rgba(0, 0, 0, 0.85); font-size: 1.15rem; line-height: 1.75; word-spacing: 0.1em; letter-spacing: 0; font-style: italic; text-align: justify; } +.quoteblock blockquote { margin: 0; padding: 0; border: 0; } +.quoteblock blockquote:before { content: "\201c"; float: left; font-size: 2.75em; font-weight: bold; line-height: 0.6em; margin-left: -0.6em; color: #0b0a0a; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); } +.quoteblock blockquote > .paragraph:last-child p { margin-bottom: 0; } +.quoteblock .attribution { margin-top: 0.5em; margin-right: 0.5ex; text-align: right; } +.quoteblock .quoteblock { margin-left: 0; margin-right: 0; padding: 0.5em 0; border-left: 3px solid rgba(0, 0, 0, 0.6); } +.quoteblock .quoteblock blockquote { padding: 0 0 0 0.75em; } +.quoteblock .quoteblock blockquote:before { display: none; } + +.verseblock { margin: 0 1em 1.25em 1em; } +.verseblock pre { font-family: "Open Sans", "DejaVu Sans", sans; font-size: 1.15rem; color: rgba(0, 0, 0, 0.85); font-weight: 300; text-rendering: optimizeLegibility; } +.verseblock pre strong { font-weight: 400; } +.verseblock .attribution { margin-top: 1.25rem; margin-left: 0.5ex; } + +.quoteblock .attribution, .verseblock .attribution { font-size: 0.9375em; line-height: 1.45; font-style: italic; } +.quoteblock .attribution br, .verseblock .attribution br { display: none; } +.quoteblock .attribution cite, .verseblock .attribution cite { display: block; letter-spacing: -0.025em; color: rgba(0, 0, 0, 0.6); } + +.quoteblock.abstract { margin: 0 0 1.25em 0; display: block; } +.quoteblock.abstract blockquote, .quoteblock.abstract blockquote p { text-align: left; word-spacing: 0; } +.quoteblock.abstract blockquote:before, .quoteblock.abstract blockquote p:first-of-type:before { display: none; } + +table.tableblock { max-width: 100%; border-collapse: separate; } +table.tableblock td > .paragraph:last-child p > p:last-child, table.tableblock th > p:last-child, table.tableblock td > p:last-child { margin-bottom: 0; } + +table.tableblock, th.tableblock, td.tableblock { border: 0 solid #dedede; } + +table.grid-all th.tableblock, table.grid-all td.tableblock { border-width: 0 1px 1px 0; } + +table.grid-all tfoot > tr > th.tableblock, table.grid-all tfoot > tr > td.tableblock { border-width: 1px 1px 0 0; } + +table.grid-cols th.tableblock, table.grid-cols td.tableblock { border-width: 0 1px 0 0; } + +table.grid-all * > tr > .tableblock:last-child, table.grid-cols * > tr > .tableblock:last-child { border-right-width: 0; } + +table.grid-rows th.tableblock, table.grid-rows td.tableblock { border-width: 0 0 1px 0; } + +table.grid-all tbody > tr:last-child > th.tableblock, table.grid-all tbody > tr:last-child > td.tableblock, table.grid-all thead:last-child > tr > th.tableblock, table.grid-rows tbody > tr:last-child > th.tableblock, table.grid-rows tbody > tr:last-child > td.tableblock, table.grid-rows thead:last-child > tr > th.tableblock { border-bottom-width: 0; } + +table.grid-rows tfoot > tr > th.tableblock, table.grid-rows tfoot > tr > td.tableblock { border-width: 1px 0 0 0; } + +table.frame-all { border-width: 1px; } + +table.frame-sides { border-width: 0 1px; } + +table.frame-topbot { border-width: 1px 0; } + +th.halign-left, td.halign-left { text-align: left; } + +th.halign-right, td.halign-right { text-align: right; } + +th.halign-center, td.halign-center { text-align: center; } + +th.valign-top, td.valign-top { vertical-align: top; } + +th.valign-bottom, td.valign-bottom { vertical-align: bottom; } + +th.valign-middle, td.valign-middle { vertical-align: middle; } + +table thead th, table tfoot th { font-weight: bold; } + +tbody tr th { display: table-cell; line-height: 1.6; background: #f7f8f7; } + +tbody tr th, tbody tr th p, tfoot tr th, tfoot tr th p { color: #34302d; font-weight: bold; } + +p.tableblock > code:only-child { background: none; padding: 0; } + +p.tableblock { font-size: 1em; } + +td > div.verse { white-space: pre; } + +ol { margin-left: 1.75em; } + +ul li ol { margin-left: 1.5em; } + +dl dd { margin-left: 1.125em; } + +dl dd:last-child, dl dd:last-child > :last-child { margin-bottom: 0; } + +ol > li p, ul > li p, ul dd, ol dd, .olist .olist, .ulist .ulist, .ulist .olist, .olist .ulist { margin-bottom: 0.625em; } + +ul.unstyled, ol.unnumbered, ul.checklist, ul.none { list-style-type: none; } + +ul.unstyled, ol.unnumbered, ul.checklist { margin-left: 0.625em; } + +ul.checklist li > p:first-child > .fa-square-o:first-child, ul.checklist li > p:first-child > .fa-check-square-o:first-child { width: 1em; font-size: 0.85em; } + +ul.checklist li > p:first-child > input[type="checkbox"]:first-child { width: 1em; position: relative; top: 1px; } + +ul.inline { margin: 0 auto 0.625em auto; margin-left: -1.375em; margin-right: 0; padding: 0; list-style: none; overflow: hidden; } +ul.inline > li { list-style: none; float: left; margin-left: 1.375em; display: block; } +ul.inline > li > * { display: block; } + +.unstyled dl dt { font-weight: normal; font-style: normal; } + +ol.arabic { list-style-type: decimal; } + +ol.decimal { list-style-type: decimal-leading-zero; } + +ol.loweralpha { list-style-type: lower-alpha; } + +ol.upperalpha { list-style-type: upper-alpha; } + +ol.lowerroman { list-style-type: lower-roman; } + +ol.upperroman { list-style-type: upper-roman; } + +ol.lowergreek { list-style-type: lower-greek; } + +.hdlist > table, .colist > table { border: 0; background: none; } +.hdlist > table > tbody > tr, .colist > table > tbody > tr { background: none; } + +td.hdlist1, td.hdlist2 { vertical-align: top; padding: 0 0.625em; } + +td.hdlist1 { font-weight: bold; padding-bottom: 1.25em; } + +.literalblock + .colist, .listingblock + .colist { margin-top: -0.5em; } + +.colist > table tr > td:first-of-type { padding: 0 0.75em; line-height: 1; } +.colist > table tr > td:first-of-type img { max-width: initial; } +.colist > table tr > td:last-of-type { padding: 0.25em 0; } + +.thumb, .th { line-height: 0; display: inline-block; border: solid 4px white; -webkit-box-shadow: 0 0 0 1px #dddddd; box-shadow: 0 0 0 1px #dddddd; } + +.imageblock.left, .imageblock[style*="float: left"] { margin: 0.25em 0.625em 1.25em 0; } +.imageblock.right, .imageblock[style*="float: right"] { margin: 0.25em 0 1.25em 0.625em; } +.imageblock > .title { margin-bottom: 0; } +.imageblock.thumb, .imageblock.th { border-width: 6px; } +.imageblock.thumb > .title, .imageblock.th > .title { padding: 0 0.125em; } + +.image.left, .image.right { margin-top: 0.25em; margin-bottom: 0.25em; display: inline-block; line-height: 0; } +.image.left { margin-right: 0.625em; } +.image.right { margin-left: 0.625em; } + +a.image { text-decoration: none; display: inline-block; } +a.image object { pointer-events: none; } + +sup.footnote, sup.footnoteref { font-size: 0.875em; position: static; vertical-align: super; } +sup.footnote a, sup.footnoteref a { text-decoration: none; } +sup.footnote a:active, sup.footnoteref a:active { text-decoration: underline; } + +#footnotes { padding-top: 0.75em; padding-bottom: 0.75em; margin-bottom: 0.625em; } +#footnotes hr { width: 20%; min-width: 6.25em; margin: -0.25em 0 0.75em 0; border-width: 1px 0 0 0; } +#footnotes .footnote { padding: 0 0.375em 0 0.225em; line-height: 1.3334; font-size: 0.875em; margin-left: 1.2em; text-indent: -1.05em; margin-bottom: 0.2em; } +#footnotes .footnote a:first-of-type { font-weight: bold; text-decoration: none; } +#footnotes .footnote:last-of-type { margin-bottom: 0; } +#content #footnotes { margin-top: -0.625em; margin-bottom: 0; padding: 0.75em 0; } + +.gist .file-data > table { border: 0; background: #fff; width: 100%; margin-bottom: 0; } +.gist .file-data > table td.line-data { width: 99%; } + +div.unbreakable { page-break-inside: avoid; } + +.big { font-size: larger; } + +.small { font-size: smaller; } + +.underline { text-decoration: underline; } + +.overline { text-decoration: overline; } + +.line-through { text-decoration: line-through; } + +.aqua { color: #00bfbf; } + +.aqua-background { background-color: #00fafa; } + +.black { color: black; } + +.black-background { background-color: black; } + +.blue { color: #0000bf; } + +.blue-background { background-color: #0000fa; } + +.fuchsia { color: #bf00bf; } + +.fuchsia-background { background-color: #fa00fa; } + +.gray { color: #606060; } + +.gray-background { background-color: #7d7d7d; } + +.green { color: #006000; } + +.green-background { background-color: #007d00; } + +.lime { color: #00bf00; } + +.lime-background { background-color: #00fa00; } + +.maroon { color: #600000; } + +.maroon-background { background-color: #7d0000; } + +.navy { color: #000060; } + +.navy-background { background-color: #00007d; } + +.olive { color: #606000; } + +.olive-background { background-color: #7d7d00; } + +.purple { color: #600060; } + +.purple-background { background-color: #7d007d; } + +.red { color: #bf0000; } + +.red-background { background-color: #fa0000; } + +.silver { color: #909090; } + +.silver-background { background-color: #bcbcbc; } + +.teal { color: #006060; } + +.teal-background { background-color: #007d7d; } + +.white { color: #bfbfbf; } + +.white-background { background-color: #fafafa; } + +.yellow { color: #bfbf00; } + +.yellow-background { background-color: #fafa00; } + +span.icon > .fa { cursor: default; } + +.admonitionblock td.icon [class^="fa icon-"] { font-size: 2.5em; text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); cursor: default; } +.admonitionblock td.icon .icon-note:before { content: "\f05a"; color: #3f6a22; } +.admonitionblock td.icon .icon-tip:before { content: "\f0eb"; text-shadow: 1px 1px 2px rgba(155, 155, 0, 0.8); color: #111; } +.admonitionblock td.icon .icon-warning:before { content: "\f071"; color: #bf6900; } +.admonitionblock td.icon .icon-caution:before { content: "\f06d"; color: #bf3400; } +.admonitionblock td.icon .icon-important:before { content: "\f06a"; color: #bf0000; } + +.conum[data-value] { display: inline-block; color: #fff !important; background-color: #34302d; -webkit-border-radius: 100px; border-radius: 100px; text-align: center; font-size: 0.75em; width: 1.67em; height: 1.67em; line-height: 1.67em; font-family: "Open Sans", "DejaVu Sans", sans-serif; font-style: normal; font-weight: bold; } +.conum[data-value] * { color: #fff !important; } +.conum[data-value] + b { display: none; } +.conum[data-value]:after { content: attr(data-value); } +pre .conum[data-value] { position: relative; top: -0.125em; } + +b.conum * { color: inherit !important; } + +.conum:not([data-value]):empty { display: none; } + +.admonitionblock { border-left: 4px solid #6db33f; background-color: #ebf1e7; padding: 1.2em 0; margin: 30px 0; width: auto; } + +#toc a:hover { text-decoration: underline; } + +.admonitionblock > table td.content { border-left: none; } diff --git a/spring-batch-docs/asciidoc/testing.adoc b/spring-batch-docs/asciidoc/testing.adoc new file mode 100644 index 000000000..8b726a207 --- /dev/null +++ b/spring-batch-docs/asciidoc/testing.adoc @@ -0,0 +1,316 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[testing]] + +== Unit Testing + +Just as with other application styles, it is extremely important to + unit test any code written as part of a batch job as well. The Spring core + documentation covers how to unit and integration test with Spring in great + detail, so it won't be repeated here. It is important, however, to think + about how to 'end to end' test a batch job, which is what this chapter will + focus on. The spring-batch-test project includes classes that will help + facilitate this end-to-end test approach. + +[[creatingUnitTestClass]] + + +=== Creating a Unit Test Class + +In order for the unit test to run a batch job, the framework must + load the job's ApplicationContext. Two annotations are used to trigger + this: + + +* `@RunWith(SpringJUnit4ClassRunner.class)`: + Indicates that the class should use Spring's JUnit facilities + + +* `@ContextConfiguration(locations = {...})`: + Indicates which XML files contain the ApplicationContext. + + +[source, java] +---- +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", + "/jobs/skipSampleJob.xml" }) +public class SkipSampleFunctionalTests { ... } +---- + +[[endToEndTesting]] + + +=== End-To-End Testing of Batch Jobs + +'End To End' testing can be defined as testing the complete run of a + batch job from beginning to end. This allows for a test that sets up a + test condition, executes the job, and verifies the end result. + +In the example below, the batch job reads from the database and + writes to a flat file. The test method begins by setting up the database + with test data. It clears the CUSTOMER table and then inserts 10 new + records. The test then launches the `Job` using the + `launchJob()` method. The + `launchJob()` method is provided by the + `JobLauncherTestUtils` class. Also provided by the + utils class is `launchJob(JobParameters)`, which + allows the test to give particular parameters. The + `launchJob()` method returns the + `JobExecution` object which is useful for asserting + particular information about the `Job` run. In the + case below, the test verifies that the `Job` ended + with status "COMPLETED". + + +[source, java] +---- +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", + "/jobs/skipSampleJob.xml" }) +public class SkipSampleFunctionalTests { + + @Autowired + private JobLauncherTestUtils jobLauncherTestUtils; + + private SimpleJdbcTemplate simpleJdbcTemplate; + + @Autowired + public void setDataSource(DataSource dataSource) { + this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + } + + @Test + public void testJob() throws Exception { + simpleJdbcTemplate.update("delete from CUSTOMER"); + for (int i = 1; i <= 10; i++) { + simpleJdbcTemplate.update("insert into CUSTOMER values (?, 0, ?, 100000)", + i, "customer" + i); + } + + JobExecution jobExecution = jobLauncherTestUtils.launchJob().getStatus(); + + + Assert.assertEquals("COMPLETED", jobExecution.getExitStatus()); + } +} +---- + +[[testingIndividualSteps]] + + +=== Testing Individual Steps + +For complex batch jobs, test cases in the end-to-end testing + approach may become unmanageable. It these cases, it may be more useful to + have test cases to test individual steps on their own. The + `AbstractJobTests` class contains a method + `launchStep` that takes a step name and runs just + that particular `Step`. This approach allows for more + targeted tests by allowing the test to set up data for just that step and + to validate its results directly. + + +[source, java] +---- +JobExecution jobExecution = jobLauncherTestUtils.launchStep("loadFileStep"); +---- + + + +=== Testing Step-Scoped Components + +Often the components that are configured for your steps at runtime + use step scope and late binding to inject context from the step or job + execution. These are tricky to test as standalone components unless you + have a way to set the context as if they were in a step execution. That is + the goal of two components in Spring Batch: the + `StepScopeTestExecutionListener` and the + `StepScopeTestUtils`. + +The listener is declared at the class level, and its job is to + create a step execution context for each test method. For example: + + +[source, java] +---- +@ContextConfiguration +@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, + StepScopeTestExecutionListener.class }) +@RunWith(SpringJUnit4ClassRunner.class) +public class StepScopeTestExecutionListenerIntegrationTests { + + // This component is defined step-scoped, so it cannot be injected unless + // a step is active... + @Autowired + private ItemReader reader; + + public StepExecution getStepExection() { + StepExecution execution = MetaDataInstanceFactory.createStepExecution(); + execution.getExecutionContext().putString("input.data", "foo,bar,spam"); + return execution; + } + + @Test + public void testReader() { + // The reader is initialized and bound to the input data + assertNotNull(reader.read()); + } + +} +---- + +There are two `TestExecutionListeners`, one + from the regular Spring Test framework and handles dependency injection + from the configured application context, injecting the reader, and the + other is the Spring Batch + `StepScopeTestExecutionListener`. It works by looking + for a factory method in the test case for a + `StepExecution`, and using that as the context for + the test method, as if that execution was active in a `Step` at runtime. The + factory method is detected by its signature (it just has to return a + `StepExecution`). If a factory method is not provided + then a default `StepExecution` is created. + +The listener approach is convenient if you want the duration of the + step scope to be the execution of the test method. For a more flexible, + but more invasive approach you can use the + `StepScopeTestUtils`. For example, to count the + number of items available in the reader above: + + +[source, java] +---- +int count = StepScopeTestUtils.doInStepScope(stepExecution, + new Callable() { + public Integer call() throws Exception { + + int count = 0; + + while (reader.read() != null) { + count++; + } + return count; + } +}); +---- + +[[validatingOutputFiles]] + + +=== Validating Output Files + +When a batch job writes to the database, it is easy to query the + database to verify that the output is as expected. However, if the batch + job writes to a file, it is equally important that the output be verified. + Spring Batch provides a class `AssertFile` to + facilitate the verification of output files. The method + `assertFileEquals` takes two + `File` objects (or two + `Resource` objects) and asserts, line by line, that + the two files have the same content. Therefore, it is possible to create a + file with the expected output and to compare it to the actual + result: + + +[source, java] +---- +private static final String EXPECTED_FILE = "src/main/resources/data/input.txt"; +private static final String OUTPUT_FILE = "target/test-outputs/output.txt"; + +AssertFile.assertFileEquals(new FileSystemResource(EXPECTED_FILE), + new FileSystemResource(OUTPUT_FILE)); +---- + +[[mockingDomainObjects]] + + +=== Mocking Domain Objects + +Another common issue encountered while writing unit and integration + tests for Spring Batch components is how to mock domain objects. A good + example is a `StepExecutionListener`, as illustrated + below: + + +[source, java] +---- +public class NoWorkFoundStepExecutionListener extends StepExecutionListenerSupport { + + public ExitStatus afterStep(StepExecution stepExecution) { + if (stepExecution.getReadCount() == 0) { + throw new NoWorkFoundException("Step has not processed any items"); + } + return stepExecution.getExitStatus(); + } +} +---- + +The above listener is provided by the framework and checks a + `StepExecution` for an empty read count, thus + signifying that no work was done. While this example is fairly simple, it + serves to illustrate the types of problems that may be encountered when + attempting to unit test classes that implement interfaces requiring Spring + Batch domain objects. Consider the above listener's unit test: + + +[source, java] +---- +private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener(); + +@Test +public void testAfterStep() { + StepExecution stepExecution = new StepExecution("NoProcessingStep", + new JobExecution(new JobInstance(1L, new JobParameters(), + "NoProcessingJob"))); + + stepExecution.setReadCount(0); + + try { + tested.afterStep(stepExecution); + fail(); + } catch (NoWorkFoundException e) { + assertEquals("Step has not processed any items", e.getMessage()); + } +} +---- + +Because the Spring Batch domain model follows good object orientated + principles, the `StepExecution` requires a + `JobExecution`, which requires a + `JobInstance` and + `JobParameters` in order to create a valid + `StepExecution`. While this is good in a solid domain + model, it does make creating stub objects for unit testing verbose. To + address this issue, the Spring Batch test module includes a factory for + creating domain objects: `MetaDataInstanceFactory`. + Given this factory, the unit test can be updated to be more + concise: + + +[source, java] +---- +private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener(); + +@Test +public void testAfterStep() { + StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(); + + stepExecution.setReadCount(0); + + try { + tested.afterStep(stepExecution); + fail(); + } catch (NoWorkFoundException e) { + assertEquals("Step has not processed any items", e.getMessage()); + } +} +---- + +The above method for creating a simple + `StepExecution` is just one convenience method + available within the factory. A full method listing can be found in its + link:$$http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/test/MetaDataInstanceFactory.html$$[Javadoc]. + diff --git a/src/site/docbook/reference/transaction-appendix.xml b/spring-batch-docs/asciidoc/transaction-appendix.adoc similarity index 59% rename from src/site/docbook/reference/transaction-appendix.xml rename to spring-batch-docs/asciidoc/transaction-appendix.adoc index b00c1bb79..0dd3b5ee4 100644 --- a/src/site/docbook/reference/transaction-appendix.xml +++ b/spring-batch-docs/asciidoc/transaction-appendix.adoc @@ -1,18 +1,25 @@ - - - - Batch Processing and Transactions +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 -
- Simple Batching with No Retry +[[transactions]] - Consider the following simple example of a nested batch with no +[appendix] +== Batch Processing and Transactions + +[[transactionsNoRetry]] + + +=== Simple Batching with No Retry + +Consider the following simple example of a nested batch with no retries. This is a very common scenario for batch processing, where an input source is processed until exhausted, but we commit - periodically at the end of a "chunk" of processing. + periodically at the end of a "chunk" of processing. + + +---- - 1 | REPEAT(until=exhausted) { | 2 | TX { @@ -23,26 +30,30 @@ | } | | } - + +---- - The input operation (3.1) could be a message-based receive +The input operation (3.1) could be a message-based receive (e.g. JMS), or a file-based read, but to recover and continue processing with a chance of completing the whole job, it must be transactional. The same applies to the operation at (3.2) - it must - be either transactional or idempotent. + be either transactional or idempotent. - If the chunk at REPEAT(3) fails because of a database exception at - (3.2), then TX(2) will roll back the whole chunk. -
+If the chunk at REPEAT(3) fails because of a database exception at + (3.2), then TX(2) will roll back the whole chunk. -
- Simple Stateless Retry +[[transactionStatelessRetry]] - It is also useful to use a retry for an operation which is not + +=== Simple Stateless Retry + +It is also useful to use a retry for an operation which is not transactional, like a call to a web-service or other remote - resource. For example: + resource. For example: + + +---- - 0 | TX { 1 | input; 1.1 | output; @@ -50,24 +61,28 @@ 2.1 | remote access; | } | } - + +---- - This is actually one of the most useful applications of a retry, +This is actually one of the most useful applications of a retry, since a remote call is much more likely to fail and be retryable than a database update. As long as the remote access (2.1) eventually succeeds, the transaction TX(0) will commit. If the remote access (2.1) eventually fails, then the transaction TX(0) is - guaranteed to roll back. -
+ guaranteed to roll back. -
- Typical Repeat-Retry Pattern +[[repeatRetry]] - The most typical batch processing pattern is to add a retry to the + +=== Typical Repeat-Retry Pattern + +The most typical batch processing pattern is to add a retry to the inner block of the chunk in the Simple Batching example. - Consider this: + Consider this: + + +---- - 1 | REPEAT(until=exhausted, exception=not critical) { | 2 | TX { @@ -85,41 +100,39 @@ | } | | } - + +---- - The inner RETRY(4) block is marked as "stateful" - see the +The inner RETRY(4) block is marked as "stateful" - see the typical use case for a description of a stateful retry. This means that if the the retry PROCESS(5) block fails, the - behaviour of the RETRY(4) is as follows. - - - - Throw an exception, rolling back the transaction TX(2) at the + behaviour of the RETRY(4) is as follows. + + +* Throw an exception, rolling back the transaction TX(2) at the chunk level, and allowing the item to be re-presented to the input - queue. - - - When the item re-appears, it might be retried depending on the + queue. + + +* When the item re-appears, it might be retried depending on the retry policy in place, executing PROCESS(5) again. The second and - subsequent attempts might fail again and rethrow the exception. - - - Eventually the item re-appears for the final time: the retry + subsequent attempts might fail again and rethrow the exception. + + +* Eventually the item re-appears for the final time: the retry policy disallows another attempt, so PROCESS(5) is never executed. In this case we follow a RECOVER(6) path, effectively - "skipping" the item that was received and is being processed. - - + "skipping" the item that was received and is being processed. - Notice that the notation used for the RETRY(4) in the plan above +Notice that the notation used for the RETRY(4) in the plan above shows explictly that the the input step (4.1) is part of the retry. It also makes clear that there are two alternate paths for processing: the normal case is denoted by PROCESS(5), and the recovery path is a separate block, RECOVER(6). The two alternate paths are completely distinct: only one is ever taken in normal - circumstances. + circumstances. - In special cases (e.g. a special TranscationValidException +In special cases (e.g. a special TranscationValidException type), the retry policy might be able to determine that the RECOVER(6) path can be taken on the last attempt after PROCESS(5) has just failed, instead of waiting for the item to be re-presented. @@ -127,17 +140,17 @@ knowledge of what has happened inside the PROCESS(5) block, which is not usually available - e.g. if the output included write access before the failure, then the exception should be rethrown to - ensure transactional integrity. + ensure transactional integrity. - The completion policy in the outer, REPEAT(1) is crucial to the +The completion policy in the outer, REPEAT(1) is crucial to the success of the above plan. If the output(5.1) fails it may throw an exception (it usually does, as described), in which case the transaction TX(2) fails and the exception could propagate up through the outer batch REPEAT(1). We do not want the whole batch to stop because the RETRY(4) might still be successful if we try again, so - we add the exception=not critical to the outer REPEAT(1). + we add the exception=not critical to the outer REPEAT(1). - Note, however, that if the TX(2) fails and we do try again, by +Note, however, that if the TX(2) fails and we __do__ try again, by virtue of the outer completion policy, the item that is next processed in the inner REPEAT(3) is not guaranteed to be the one that just failed. It might well be, but it depends on the @@ -149,18 +162,21 @@ after 10 consecutive attempts, but not necessarily at the same item. This is consistent with the overall retry strategy: it is the inner RETRY(4) that is aware of the history of each item, and can decide - whether or not to have another attempt at it. -
+ whether or not to have another attempt at it. -
- Asynchronous Chunk Processing +[[asyncChunkProcessing]] - The inner batches or chunks in the typical example + +=== Asynchronous Chunk Processing + +The inner batches or chunks in the typical example above can be executed concurrently by configuring the outer batch to - use an AsyncTaskExecutor. The outer batch waits for all the - chunks to complete before completing. + use an AsyncTaskExecutor. The outer batch waits for all the + chunks to complete before completing. + + +---- - 1 | REPEAT(until=exhausted, concurrent, exception=not critical) { | 2 | TX { @@ -178,19 +194,23 @@ | } | | } - -
+ +---- -
- Asynchronous Item Processing +[[asyncItemProcessing]] - The individual items in chunks in the typical + +=== Asynchronous Item Processing + +The individual items in chunks in the typical can also in principle be processed concurrently. In this case the transaction boundary has to move to the level of the individual item, so that each transaction is on a single thread: - + + + +---- - 1 | REPEAT(until=exhausted, exception=not critical) { | 2 | REPEAT(size=5, concurrent) { @@ -208,26 +228,30 @@ | } | | } - + +---- - This plan sacrifices the optimisation benefit, that the simple plan +This plan sacrifices the optimisation benefit, that the simple plan had, of having all the transactional resources chunked together. It is only useful if the cost of the processing (5) is much higher than - the cost of transaction management (3). -
+ the cost of transaction management (3). -
- Interactions Between Batching and Transaction Propagation +[[transactionPropagation]] - There is a tighter coupling between batch-retry and TX management + +=== Interactions Between Batching and Transaction Propagation + +There is a tighter coupling between batch-retry and TX management than we would ideally like. In particular a stateless retry cannot be used to retry database operations with a transaction manager that doesn't support NESTED propagation. - + - For a simple example using retry without repeat, consider this: +For a simple example using retry without repeat, consider this: + + +---- - 1 | TX { | 1.1 | input; @@ -239,16 +263,19 @@ | } | | } - + +---- - Again, and for the same reason, the inner transaction TX(3) can +Again, and for the same reason, the inner transaction TX(3) can cause the outer transaction TX(1) to fail, even if the RETRY(2) is - eventually successful. + eventually successful. - Unfortunately the same effect percolates from the retry block up to - the surrounding repeat batch if there is one: +Unfortunately the same effect percolates from the retry block up to + the surrounding repeat batch if there is one: + + +---- - 1 | TX { | 2 | REPEAT(size=5) { @@ -262,45 +289,46 @@ | } | | } - - - Now if TX(3) rolls back it can pollute the whole batch at TX(1) and - force it to roll back at the end. - - What about non-default propagation? - - - In the last example PROPAGATION_REQUIRES_NEW at TX(3) will +---- + +Now if TX(3) rolls back it can pollute the whole batch at TX(1) and + force it to roll back at the end. + +What about non-default propagation? + + +* In the last example PROPAGATION_REQUIRES_NEW at TX(3) will prevent the outer TX(1) from being polluted if both transactions are eventually successful. But if TX(3) commits and TX(1) rolls back, then TX(3) stays committed, so we violate the transaction contract for TX(1). If TX(3) rolls back, TX(1) does not necessarily (but it probably will in practice because the retry will throw a roll back - exception). - - - PROPAGATION_NESTED at TX(3) works as we require in the retry + exception). + + +* PROPAGATION_NESTED at TX(3) works as we require in the retry case (and for a batch with skips): TX(3) can commit, but subsequently be rolled back by the outer transaction TX(1). If TX(3) rolls back, again TX(1) will roll back in practice. This option is only available on some platforms, e.g. not Hibernate or - JTA, but it is the only one that works consistently. - - + JTA, but it is the only one that works consistently. - So NESTED is best if the retry block contains any database access. -
+So NESTED is best if the retry block contains any database access. -
- Special Case: Transactions with Orthogonal Resources +[[specialTransactionOrthonogonal]] - Default propagation is always OK for simple cases where there are no + +=== Special Case: Transactions with Orthogonal Resources + +Default propagation is always OK for simple cases where there are no nested database transactions. Consider this (where the SESSION and TX are not global XA resources, so their resources are orthogonal): - + + + +---- - 0 | SESSION { 1 | input; 2 | RETRY { @@ -309,36 +337,40 @@ | } | } | } - + +---- - Here there is a transactional message SESSION(0), but it doesn't +Here there is a transactional message SESSION(0), but it doesn't participate in other transactions with - PlatformTransactionManager, so doesn't propagate when TX(3) + PlatformTransactionManager, so doesn't propagate when TX(3) starts. There is no database access outside the RETRY(2) block. If TX(3) fails and then eventually succeeds on a retry, SESSION(0) can commit (it can do this independent of a TX block). This is similar to the vanilla "best-efforts-one-phase-commit" scenario - the worst that can happen is a duplicate message when the RETRY(2) succeeds and the SESSION(0) cannot commit, e.g. because the message system is - unavailable. -
+ unavailable. -
- Stateless Retry Cannot Recover +[[statelessRetryCannotRecover]] - The distinction between a stateless and a stateful retry in the + +=== Stateless Retry Cannot Recover + +The distinction between a stateless and a stateful retry in the typical example above is important. It is actually ultimately a transactional constraint that forces the distinction, and this constraint also makes it obvious why the distinction exists. - + - We start with the observation that there is no way to skip an item +We start with the observation that there is no way to skip an item that failed and successfully commit the rest of the chunk unless we wrap the item processing in a transaction. So we simplify the - typical batch execution plan to look like this: + typical batch execution plan to look like this: + + +---- - 0 | REPEAT(until=exhausted) { | 1 | TX { @@ -357,23 +389,23 @@ | } | | } - + +---- - Here we have a stateless RETRY(3) with a RECOVER(5) path that kicks +Here we have a stateless RETRY(3) with a RECOVER(5) path that kicks in after the final attempt fails. The "stateless" label just means that the block will be repeated without rethrowing any exception up to some limit. This will only work if the transaction TX(4) has - propagation NESTED. + propagation NESTED. - If the TX(3) has default propagation properties and it rolls back, +If the TX(3) has default propagation properties and it rolls back, it will pollute the outer TX(1). The inner transaction is assumed by the transaction manager to have corrupted the transactional - resource, and so it cannot be used again. + resource, and so it cannot be used again. - Support for NESTED propagation is sufficiently rare that we choose +Support for NESTED propagation is sufficiently rare that we choose not to support recovery with stateless retries in current versions of Spring Batch. The same effect can always be achieved (at the expense of repeating more processing) using the - typical pattern above. -
-
\ No newline at end of file + typical pattern above. + diff --git a/spring-batch-docs/asciidoc/whatsnew.adoc b/spring-batch-docs/asciidoc/whatsnew.adoc new file mode 100644 index 000000000..324f79a73 --- /dev/null +++ b/spring-batch-docs/asciidoc/whatsnew.adoc @@ -0,0 +1,51 @@ +:batch-asciidoc: http://docs.spring.io/spring-batch/reference/html/ +:toc: left +:toclevels: 4 + +[[whatsNew]] + +== What's New in Spring Batch 4.0 + +The Spring Batch 4.0 release has three major themes: + + +* Java 8 Requirement + + +* Dependencies re-baseline + + +* Builders for ItemReaders and ItemWriters + +[[whatsNewJava]] + + +=== Java 8 Requirement + +Spring Batch has historically followed Spring Framework's baselines for both + java version as well as third party dependencies. With Spring Batch 4, the Spring + Framework version is being upgraded to Spring Framework 5. As such, the java + version requirement for Spring Batch is also increasing to Java 8. + + +[[whatsNewDependencies]] + + +=== Dependencies re-baseline + +In order to continue to integrate with supported versions of the third party + libraries Spring Batch utilizes, Spring Batch 4 is updating the dependencies across + the board. The new dependency versions are in alignment with Spring Framework 5. + + +[[whatsNewBuilders]] + + +=== Provide builders for the ItemReaders and ItemWriters + +Spring Batch 4 is providing a collection of builders for all of the ItemReaders + and ItemWriters that come with the framework. As of this release, builders for the + `FlatFileItemReader`, `FlatFileItemWriter`, `JdbcCursorItemReader`, and + `JdbcBatchItemWriter` are available. More information can be found in the javadoc + for Spring Batch. + diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ldif/MappingLdifReader.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ldif/MappingLdifReader.java index cde3301cb..e9213274b 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ldif/MappingLdifReader.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ldif/MappingLdifReader.java @@ -36,11 +36,6 @@ import org.springframework.util.ClassUtils; * object which can be consumed and manipulated as necessary by {@link org.springframework.batch.item.ItemProcessor ItemProcessor} or any * output service. *

- * {@link LdifReader LdifReader} usage is mimics that of the FlatFileItemReader for all intensive purposes. Adjustments have been made to - * process records instead of lines, however. As such, the {@link #recordsToSkip recordsToSkip} attribute indicates the number of records - * from the top of the file that should not be processed. Implementations of the {@link RecordCallbackHandler RecordCallbackHandler} - * interface can be used to execute operations on those skipped records. - *

* As with the {@link org.springframework.batch.item.file.FlatFileItemReader FlatFileItemReader}, the {@link #strict strict} option * differentiates between whether or not to require the resource to exist before processing. In the case of a value set to false, a warning * is logged instead of an exception being thrown. diff --git a/src/site/apt/articles.apt b/src/site/apt/articles.apt deleted file mode 100644 index aaf2584b5..000000000 --- a/src/site/apt/articles.apt +++ /dev/null @@ -1,22 +0,0 @@ - ------ - Spring Batch in the Media - ------ - Dave Syer - ------ - November 2007 - -Spring Batch In the Media - - * http://www.theserverside.com/tt/articles/article.tss?l=SpringBatchOverview - - * http://www.theserverside.com/news/thread.tss?thread_id=47506#242493 - - * http://blog.decaresystems.ie/index.php/2007/04/12/spring-batch/ - - * http://www.itweek.co.uk/itweek/news/2189502/accenture-launches-batch - - * http://www.theserverside.com/tt/articles/article.tss?l=SpringBatchOverview - - * http://www.infoq.com/interviews/johnson-spring-portfolio - - * http://www.infoq.com/news/2008/06/spring-batch diff --git a/src/site/apt/building.apt b/src/site/apt/building.apt deleted file mode 100644 index 8d14e5cc9..000000000 --- a/src/site/apt/building.apt +++ /dev/null @@ -1,377 +0,0 @@ - ------ - Building Spring Batch - ------ - Dave Syer - ------ - April 2007 - -Building Spring Batch - - Spring Batch is organised as a reactor build in Maven (m2). To - build from the command line use - -+--- -$ mvn install -+--- - - or the goal of your choice (compile, test, etc.). This builds the - artifact (e.g. jar file) from the project in the current directory, - and deploys it to you local m2 repo at - <<<${user.home}/.m2/repository>>>. If there are any dependency resolution - problems try - -+--- -$ mvn install -P bootstrap -+--- - - which enables some additional, non-standard repositories (which - should not be present in ther deployed artifacts). You should only - need to do this once, because then all the dependencies will be - installed in your local repository. To get the source code (where - available) for all dependencies, you can use - -+--- -$ mvn dependency:sources -P bootstrap -+--- - - See below for instructions on how - to build the documentation and web site. - - By default the whole project (including subprojects) will be built - using Maven's "reactor" plugin. This can be expensive. To build - only one module, cd to that directory first. Or at the top level - use -N (for non-recursive) to exclude subprojects. - -+--- -$ mvn -N install -+--- - -* Skipping Tests - - The profile <> skips all the tests, so - -+--- -mvn -o install -P fast -+--- - - is the quickest way to update your local repo (assuming the tests - are OK). It is equivalent of setting <<<-Dmaven.test.skip=true>>>. - -* Running Individual Tests - - The standard way to do this with Maven is -Dtest= with the class name (not fully qualified), e.g. - -+--- -$ mvn test -Dtest=FootballJobFunctionalTests -+--- - - In the samples you can also add additional system properties, which will be used to override bean properties. This can be done with an argLine property, e.g. - -+--- -$ mvn test -Dtest=FootballJobFunctionalTests -DargLine='-Dplayer.file.name=player.csv -Dgames.file.name=games.csv' -+--- - - or by specifying forkMode=never (in which case the test is run in the same process as Maven): - -+--- -$ mvn test -DforkMode=never -Dtest=FootballJobFunctionalTests -Dplayer.file.name=player.csv -Dgames.file.name=games.csv -Djob.commit.interval=50 -+--- - -* Eclipse IDE - - Our policy is to commit Eclipse (and only Eclipse) meta data to - source control. This will work out of the box for you if you use - the (excellent) Q4E Eclipse-plugin - (http://q4e.googlecode.com/svn/trunk/updatesite). With this plugin, - each of the reactor modules at the top level builds independently - and feeds changes into other projects in your workspace. It is not - recommended to use the Maven Eclipse plugin (<<>>) because it cannot track dependencies across the - Eclipse workspace. It will also create Eclipse meta-data every time - you run it, conflicting with the version under source control. - -* Dependencies - - If you get multiple versions of the same jar across projects, or a - jar is appearing in the classpath that you don't think is necessary, - look into the dependency structure and try and exclude it from - wherever it is being transitively included. To see the dependencies - for a project look in the site for the dependency report. - Alternatively (very useful for quickly locating a rogue jar) use - -+--- -$ mvn -P snapshots dependency:tree -+--- - - We use the "snapshots" profile here so that we get a snapshot of the - dependency plugin (older versions did not have the tree goal, but - newer versions are not stable enough to use in production). - -* Subversion and Line Endings - - Please use - -+--- -*.xml = svn:eol-style=LF -*.sql = svn:eol-style=LF -*.txt = svn:eol-style=LF -*.java = svn:eol-style=LF -*.apt = svn:eol-style=LF -*.properties = svn:eol-style=LF -+--- - - in your <<<~/.subversion>>> (or <<\Application Data\Subversion/config>>>). If anyone forgets to do that then the property can be recursively set using Tortoise (type in the property key and value and use the recursive checkbox). - -* Documentation - - With the exception of reference docs, please put content in the - project that it is most closely associated with. Here is a - {{{./sitemap.html}site map}} to help you decide. - -** Quotidian Web Content - - Maven allows you to choose from a range of source format for - building web content. For Spring Batch we prefer the "almost plain - text" version. See files under <<>> in all the projects - for examples, and also refer to the - {{{http://maven.apache.org/guides/mini/guide-apt-format.html}Apt - Format Guide}} on the Maven website. - - N.B. you put .apt source files in a subdirectory called <<>>, - but they are moved to the top level when the site is built. Thus - <<>> becomes <<>>. - -*** Using emacs to edit .apt files - - Because the .apt format relies on indentation in plain text files, - the emacs auto-fill feature in text mode makes editing very - convenient. Put this in your .emacs - -+--- -(setq auto-mode-alist (cons '("\\.apt\\'" . text-mode) auto-mode-alist)) -+--- - - Then use <<>> to auto-fill the current paragraph. Emacs - adjusts the indentation of all the lines to match the first one (or - the first two if the second is different. - - If anyone knows how to do this with Eclipse or other editors, let us - know and we'll put a note here. - -** Reference Guide - - The <<>> project is reserved for reference guides in the - normal Spring docbook format. Each chapter of the reference guide - is in a separate xml file under <<>>. - The easiest way to work with the reference guide is to cd to the - <<>> module, and run Maven from there. - - Use the DTD with a validating XML editor (e.g. Eclipse) to explore - the docbook format. Also look at existing examples in Spring Batch - and in the Core Spring Framework source code. - - [Section numbers] There is no need to explicitly create section numbers in the - XML - this is done for you by the build when everything is stitched - together into a book. - - [Source location] You put docbook .xml source files in a - subdirectory called <<>>, but they are moved to the top - level when the site is built. Thus - <<>> becomes - <<>>. - - [XMLMind] If you use {{{http://www.xmlmind.com}XMLMind}} to edit the - reference guide add the following line to - <<</addon/config/docbook/common.incl>>>: - -+--- - -+--- - -** Adding a new chapter to the Reference Guide - - Here is a skeleton chapter including the DTD to get you started on a - new chapter. - -+--- - - - - Chapter Title -

- Introduction - -
- -+--- - - Create a file with the template above, and put it in - <<>>. Use lower case, dash separated file names - (XML style), e.g. <<>>. - - Add the chapter to the master book in <<>> using - -+--- - -+--- - -* Adding graphics - - Put (e.g.) PNG image content in <<>>, and - then refer to the file using the <<>> directory prefix. - -** In .apt - - With no whitespace add the image name in square brackets (\[\]): - -+--- -[images/MyFigure.png] Caption content here is not rendered by default -in a browser (it's the ALT content)... -+--- - -** In docbook - - Use the \ element: - -+--- - - - - - - - - - - Figure 1: the figure caption... - - - -+--- - -* Program Listings in Docbook (Including XML) - - Use CDATA to save you from having to use the HTML escapes for all - the special characters. E.g. - -+--- - -]]> - -+--- - -* Dynamic Editing - - To see your changes to web site content as soon as you have typed - it, use - -+--- -mvn site:run -+--- - - and go to http://localhost:8080. - - In a project with unit tests, you can skip the tests and go straight - to the documentation using - -+--- -mvn -o site:run -P fast -+--- - - If you are offline, or want to speed things up a bit, the "-o" stops - Maven from trying to resolve dependencies on the internet. - - Use -N to build only the current project, not subprojects, So this - is pretty useful at the top level: - -+--- -mvn -N -o site:run -P fast -+--- - - In the <<>> project the docbook reference guide shows up at - http://localhost:8080/reference/*.html, where * is the name of an - xml file with a chapter in it. There is no link to these pages on - the site because the real docbook generated output is much nicer, - but this is still pretty useful for debugging and dynamic - editing. - - Note that the formatting is a bit limited compared to the whole - docbook stylesheet - Maven uses Doxia to squish all of docbook into - some simple wiki-like formatting rules. In particular it can't - generate the index page in the format we need it, so you may see - errors from <<>> if you visit that page. One of the - features is that the <<<\>>> syntax we use to build the - index and table of contents in the docbook-generated pages does not - work. Images are another problem. Use the generated content from - <<>> to view these artifacts. - -* Building and deploying the web site - - There is a bug in the m2 reactor (MNG-740) which means that we have - to install the parent pom to the local repo first. - - So do it this way: - -+--- -$ mvn install -P fast -$ mvn -P staging clean site site:deploy -+--- - - Remove "-P staging" to deploy to the real website (requires ssh - access to static.springframework.org). - - The "-P staging" is to deploy to <<>>, so we - don't get accidental updates to the site. To test the site contents - navigate with your browser to that directory. The site:stage goal - deos not work properly for this build: all the subprojects are not - integrated into the staging site, so use site:deploy instead. - - The static website content is not deleted during the deployment - process - merely replaced. If you need to clean everything up from - scratch you need to delete the contents on the server as well - (using ssh). - -Problems? - - Make sure your source code is up to date. Delete everything from - your local Spring Batch repo - <<<${user.home}/.m2/repository/org/springframework/batch>>>. If - necessary, delete a project or directory and update from SVN again. - - Try - -+--- -$ mvn install -+--- - - or - -+--- -$ mvn clean install -+--- - - or - -+--- -$ mvn clean install -P fast -+--- - - from the top level, and - -+--- -$ mvn -U ... -+--- - - from wherever you are (top level or sub-project). The latter will - update any older plugins you have in your local Maven repository. - Some people have had trouble building the web site without this. - - If you get <<>> e.g. building the site, use - MAVEN_OPTS to boost the heap size (on the command line if you have a - sensible shell): - -+--- -$ MAVEN_OPTS=-Xmx256m mvn site -+--- diff --git a/src/site/apt/cases/async.apt b/src/site/apt/cases/async.apt deleted file mode 100644 index 2255d5ba3..000000000 --- a/src/site/apt/cases/async.apt +++ /dev/null @@ -1,159 +0,0 @@ - ------ - Asynchronous Chunk Processing Use Case - ------ - Dave Syer - ------ - January 2007 - -Use Case: Asynchronous Chunk Processing - -* Goal - - Increased the efficiency of chunk processing by having it execute - asynchronously: in multiple threads. Maintain transactional - intergrity of the chunk. - -* Scope - - * All chunks might conceivably benefit from parallel processing, so - we don't want any unnecessary restrictions on the batch operation, - or its implementation. A should be possible for Client to write a - batch operation without reference to the fact that it might run in - an asynchronous chunk. - -* Preconditions - - * Input data exists with non-trivial size: chunks contain more than - one record. - - * Batch processing of a record is slow, or can be delayed, so that - the asynchronous processing can take longer than launching the - threads. - - * A chunk can be made to fail after at least one record is - processed. - -* Success - - * A chunk is processed and the results inspected to verify that all - records were processed. - - * Transactional behaviour is verified by rolling back a chunk and - verifying that no records were processed. - -* Description - - The vanilla case proceeds as for normal {{{./chunks.html}chunk - processing}}, but: - - [[1]] Within a chunk, Container processes records in parallel. - - [[1]] At the end of a chunk, Container waits for the last record - to be processed (with a timeout if the wait is long). - -* Variations - -** Rollback on Failure - - If there is an exception in one of the record processing threads, - the whole chunk should roll back: - - [[1]] Client throws exception in record processing. - - [[1]] Container catahes exception and attempts to abort other - running processes. - - [[1]] Container waits for running processes to abort (or finish - normally, but preferably to abort). - - [[1]] Container propagates the exception and signals transaction to - rollback. - -** Timeout - - If there is a timeout during a chunk, it might happen before the - chunk has finished, or while waiting for the processes to complete - before exiting. - - [[1]] At end of chunk, Container is waiting for all processes to - finish. It times out, according to a parameter set by the - Operator. - - [[1]] Container does not start any new processes, and attempts to - abort running processes. - - [[1]] Container waits for running processes to abort (or finish - normally, but preferably to abort). - - [[1]] Container throws a time out exception and signals chunk - transaction to rollback. - -* Implementation - - * The implementation of this use case could be tricky in the general - case. In particular, the transactional nature is going to be hard - or impossible to maintain across multiple threads without the - individual processes being aware of the transaction, and (perhaps) - without global (XA) transaction support. - - A "normal" local transaction is thread bound - i.e. it only executes - in one thread. If the code inside the transaction creates new - threads, then they might not finish processing before the parent - exits and the transaction wants to finish. The transaction needs to - wait for the sub-processes before committing, or (more difficult) - rolling back. The rollback case basically forces us to a model of - one transaction per thread, and therefore to one transaction per - data item in a concurrent environment. - - Otherwise some transactional semantics might be respected in a - parallel process, but others certainly will not be because - synchronizations and resources are managed at the level of the - thread where the transaction started. If the transaction manager is - a local one (not XA) there is little hope even that the datasource - resource would be the same for all the parallel threads and the - parent method. - - If we use a global transaction manager to make the parallel - processes transactional, how will they know which transaction to - participate in? There could be many active chunks, and each would - have its own threads - how would each one be able to guide its child - processes to participate in the same transaction? - - * Beware a framework that extracts data from an <<>> - before executing the business logic (e.g. in a - <<>>). It is not enough to allow concurrent - processing but simply insist that the individual records are - processed transactionally because the <<>> will then - not be able to participate in the transaction - its next record has - already been passed to the consumer when the transaction starts, so - if there is a rollback then the record is lost. - - This is the origin of the signature: - -+--- -public interface ItemReader { - Object next(); -} -+--- - - There is no peeking and no iterator-style <<>>. If there - is a processing problem, transactional clients of the - <<>> throw an exception the provider's - <<>> has been called, but in the same thread (so that - transactional semantics are preserved and the data provider reverts - to its previous state). - - This means that in the callback interface also picks up an - <<>> return type - -+--- -public interface RepeatCallback { - Object doInIteration(BatchContext context); -} -+--- - - so we can return an object, which is null when the processing has - finished. - - In the end we decided against the <<>> return type and went - with an exit status to signal for no more processing. diff --git a/src/site/apt/cases/chunks.apt b/src/site/apt/cases/chunks.apt deleted file mode 100644 index 0f3e129d7..000000000 --- a/src/site/apt/cases/chunks.apt +++ /dev/null @@ -1,208 +0,0 @@ - ------ - Commit Periodically Use Case - ------ - Dave Syer - ------ - January 2007 - -Use Case: Commit Batch Process Periodically - -* Goal - - Read a file line-by-line and process into database inserts, for - example using the Jdbc API. Commit periodically, and if there is a - fault where the database transaction rolls back, then the file - reader is reset to the place it was after the last successful - commit. - - To develop a batch process to achieve the goal above should be as - simple a process as possible. The more that can be done with simple - POJOs and Spring configuration the better. - -* Scope - - To keep things simple for now, assume that: - - * All lines in the input file are in the same format and each line - generates a single database insert (or a fixed number). - - * The file is read synchronously by a single consumer. - -* Preconditions - - * A file exists in the right format, with a sufficiently large - number of lines to be realistic. - - * A mechanism exists to force a rollback at a non-trivial position - (not during the first commit), but produce a successful operation - on the second try. - - * A framework for retry exists, so that the case above can be - tested. - -* Success - - Integration test confirms that - - * All data are processed and records inserted successfully. - - * When a rollback occurs and the retry is successful, the complete - dataset is processed (same result as successful run). - - * Batch operations can be implemented without framework code (or - with minimal dependencies, e.g. through interfaces). Launching - the batch might require access to framework code. - -* Description - - The vanilla successful batch use case proceeds as follows: - - [[1]] Container starts a transaction. - - [[1]] Container makes resources available, e.g. opens file and - creates <<>> for it. - - [[1]] Client reads a line from the file, and converts it to a - database statement, then runs it. - - [[1]] Container increments counter. - - [[1]] Repeat previous two steps until a counter is equal to chunk - size. - - [[1]] Container commits database transaction. - - [[1]] Repeat chunk processing until input source is exhausted. - -* Variations - -** Non-fatal Chunk Failure - - If there is an unrecoverable database exception during execution of - client code: - - [[1]] Container rolls back current transaction. - - [[1]] Container resets input source to the point it was at before - failure. - - [[1]] Container retries chunk. - -** Fatal Chunk Failure - - If there is an error in the input data in the middle of a chunk - (could be manifested as database exception, e.g. uniqueness - exception, or nullable exception): - - [[1]] Container rolls back current transaction. - - [[1]] Container terminates batch and notifies client of precise - details, including the line number of error, and the last line - that was committed (last of the previous chunk). - - There is no need to reset the input source because the error is - fatal. - - To restart: - - [[1]] Operator truncates the input file so the completed chunks - are not repeated. - - [[1]] Operator fixes bad line (if there was one), and starts the - batch process wit hthe same parameters. - - Variations on this theme are also necessary, e.g. a tolerance for a - small number of bad records in the input data. - -* Implementation - - * The concept of a batch iterator seems relevant here (see also the - {{{./simple.html}simple}} use case). The iterator could be more than - just a loop that might terminate early: here it could also manage - the file cursor on the input source. In this design there is a - <<>> interface that can take care of termination and - iteration (e.g. iterator-like method signatures). - - * Another design idea (more encapsulated and more in keeping with - existing Spring practice) is to make the data source transaction - aware, and for the client use it like a database resource, through a - template. In this case there is a <<>>. The - <<>> needs to be aware of the data source template, so - that it can terminate when the data is exhausted. - - In this version of events there are two kinds of resource in play. - The transaction itself, and the data sources that are aware of the - transaction. The comparison with <<>> - and <<>> is obvious. The client is often completely - unaware of the transaction manager, which is applied through an - interceptor, whereas the data source is used explicitly with its own - API through a template. The Client can concentrate on his domain, - and not be concerned with infrastructure or resource handling. - - * The analogy with <<>> is even stronger. If the input - data came from JMS instead of a file, we would hardly have to do - anything to implement very robust chunking. JMS is the obvious best - practice and already provides all the transactional semantics we - need for chunking - simply roll back a transaction and the records - processed return to the message system for delivery to the next - consumer. Bad records can be sent to a bad message queue for - independent processing. JMS might ssem like overkill for a lot of - batch processes, but it is tempting to say that if the robustness is - needed then the we should take that as a sign that installing and - configuring JMS is worth the extra effort. - - * Naturally we do not want to insist that the client code is aware - of the transaction that is surrounding it - this would be the normal - practice familiar from the Spring programming model. Should a - client need access to transaction-scoped resources, the usual way to - do that is to wrap the transactional resource (data source etc.) in - a proxy that uses a synchronization, or a more generic thread-bound - resource (using <<>>). The aim - is to retain this separation in a batch operation. The batch - framework itself might provide some of these synchronizations. - - * The {{{./simple.html}Simple Batch Repeat}} is actually a pretty good - model for the chunk processing in this use case. This observation - leads to another: that a batch of chunks is a nested (or composed) - batch - the outer termination policy is dependent only on the data - source having further records to process, the inner one is a simple - iterator (with a check for empty data). A simplified programming - model for this is - -+--- -RepeatCallback chunkCallback = new RepeatCallback() { - - public boolean doInIteration(RepeatContext context) { - - int count = 0; - - do { - - Object result = callback.doWithRepeat(context); - - } while (result!=null && count++>>). The termination policy depends - only on a data source eventually returning null. - - * N.B. the chunkSize can be dynamic. E.g., if the chunk is long - during a nightime batch window, and short when the window is over, - in case the batch has to be terminated. - - * Chunking can also be implemented simply in an - <<>>. The handler just buffers records up to a - chunk size, and then executes them all in one step (which might be - transactional). This is easier to implement, and easier to - configure for the clients, but cannot easily be made both concurrent - and transactional. diff --git a/src/site/apt/cases/file-to-file.apt b/src/site/apt/cases/file-to-file.apt deleted file mode 100644 index 53a6bc45d..000000000 --- a/src/site/apt/cases/file-to-file.apt +++ /dev/null @@ -1,89 +0,0 @@ - ------ - Copy File to File - ------ - Dave Syer - ------ - January 2007 - -Use Case: Copy File to File - -* Goal - - Read a file line-by-line and process into a file in a different - format (possibly different number of lines). Commit periodically - and in the event of an error both data sources (input and output) - rollback to the last known good point. - -* Scope - - To keep things simple for now, assume that: - - * All lines in the file are in the same format and the final - output is an aggregate. - - * The files are read and written synchronously by a single - consumer. - - * This use case requires two kinds of transactional file source. - One is read-only and the other is write-only. Only one consumer - can use the write-only source at a time. - -* Preconditions - - * An input file exists in the right format, with a sufficiently - large number of lines to be realistic. - -* Success - - Integration test confirms that - - * All data are processed and output produced successfully. - -* Description - - Very similar to the use case {{{./chunks.html}Copy File to - Database}}, but involving transactional access to an output source - which is a file. Also we are introducing the idea of an aggregate - function for the output. - - The vanilla successful case proceeds as in the file to database - version, except that: - - [[1]] A successful chunk results in a line in an intermediate file - output source. - - [[1]] After all chunks are successfully processed the intermediate - file is itself processed in a single transaction to complete the - aggregate. The output is itself sent to an output channel - (e.g. database or file). - -* Variations - - * Chunk failure variations proceed as in the use case - {{{./chunks.html}Copy File to Database}}. In the case of a - restart after fatal failure, the intermediate output file need does - not need to be reset or re-created. - -* Implementation - - * The write-only file source is new in this use case. It has a - similar flavour to the read-only version, but also has more serious - implications for implementation and usage. Since a file system is - not inherently transactional, when we create the write-only data - source we are assuming that consumers will play by the rules, - principally that there is only one consumer at a time. - - * With some external limitations the write-only file source can be - implemented so that within a single JVM it will behave like a - transactional database datasource. We can provide a - <<>> that hides the resource acquisition and - release, and interacts with an existing transaction to provide the - transactional behaviour that is required. - - * File-based transactional resources are a lot like messaging - clients. We can send a message (write a line) through a sender - client, and receive a message (read a line) through a consumer - client. In the case of a transaction rollback, all sent messages - are guaranteed not to reach consumers, and all received messages are - returned to the queue. Maybe ActiveMQ has a file transport already? - Mule definitely does, but it isn't transactional. diff --git a/src/site/apt/cases/index.apt b/src/site/apt/cases/index.apt deleted file mode 100644 index c544aa4cb..000000000 --- a/src/site/apt/cases/index.apt +++ /dev/null @@ -1,113 +0,0 @@ - ------ - Use Cases - ------ - Dave Syer - ------ - January 2007 - -Use Cases for Spring Batch - - These are more like scenarios or flows than real use cases in formal - UML terms, but they serve a useful purpose as both. We don't want - to be over formal, and probably code is being written and tested at - the same time as these use cases. But there are many stakeholders - in this project, and use cases are a useful resource to make sure - they are all agreed on scope and certain implementation details. - - * {{{./simple.html}Simple Batch Repeat}} - - * {{{./retry.html}Automatic Retry After Failure}} - - * {{{./chunks.html}Commit Batch Process Periodically}}: chunk - processing. - - * {{{./async.html}Asynchronous Chunk Processing}}: parallel - processing within a chunk. - - * {{{./file-to-file.html}Copy File to File in a Batch}} - - * {{{./parallel.html}Massively Parallel Batch Processing}}. Spring - Batch 1.0 does not contain any implementations of this use case, - but it is quite feasible to implement them using the framework as - a starting point. 1.1 has some prototype code under the Integration - module. - - * {{{./restart.html}Manual Restart After Failure}} - - * {{{./steps.html}Sequential Processing of Dependent Steps}} - - * {{{./partial.html}Partial Processing}}: skip records (e.g. on rollback). - - * Whole-Batch Transaction - transactional support for the whole - batch, not just chunks. Quite a common requirement, but not - always practical using normal transaction support. May require a - staging area, and a decision after it is full about whether to - copy it in one big batch (e.g. using native database tools) or - chunk it (e.g. if it is now in a form for which chunk failure is - easier to deal with). - - * {{{./scheduled.html}Scheduled Processing}}: Batch Jobs controlled - by scheduler (e.g. start, stop, suspend, kill). Spring Batch does - not intend to implement the scheduler concerns, but needs - to provide enough information that a scheduler can act - appropriately. - - * Non-Sequential Processing of Steps (Conditional Branching) - - * {{{./pause.html}Pause and Resume Job Execution}} - - -* Actors - - The following actors are involved in the use cases (Container and - Client being the most common / important). - -** Client or Business Domain - - Code written by the batch developer. - - One aim us that the client is a POJO - the batch behaviour, boundary - conditions, transactions etc. can be dealt with by the Container in - such as way that the client does not need to know about them. The - client may have access to framework abstractions, like templated - data sources (<<>> etc.), but these should work the - same whether they are in a batch or not. - -** Container - - An application that converts user requests for batch jobs into - running processes. Container concerns are robustness, traceability, - manageability. - -** Framework - - The Framework is the infrastructure code that the Container depends - on, and possibly spi implementations where knowledge of the - non-business logic resides. - - The Framework provides two kinds of infrastruture (as per usual - Spring cornerstones and ): - - * For cross-cutting concerns there are interceptors that can be - wrapped around client code without it needing any knowledge of the - Framework at all. An existing parallel is with transaction - support - the client code can use <<>> - directly, but does not always need to. - - * Concrete abstractions that allow access to resources in a - uniform way without needing to know the details of how they are - provided (e.g. partitioned). Client code can use these - abstractions like it would a use a <<>>. - -** Operator - - The batch operator is not a developer. Tools are provided for the - Operator to be able to stop and start a batch, and to monitor the - progress and status of on ongoing or finished batch. - -** Business User - - The Operator has technical skills, e.g. a member of an application - support team, but may need help with business-related decisions. - For instance if input data are bad, he would not expect to be able - to fix them alone because they might be bad for a business reason. diff --git a/src/site/apt/cases/parallel.apt b/src/site/apt/cases/parallel.apt deleted file mode 100644 index c61cacf2a..000000000 --- a/src/site/apt/cases/parallel.apt +++ /dev/null @@ -1,278 +0,0 @@ - ------ - Parallel Processing Use Case - ------ - Dave Syer - ------ - January 2007 - -Use Case: Massively Parallel Batch Processing - -* Goal - - Support efficient processing of really large batch jobs (100K - - 1000K records) through parallel processing, across multiple - processes or physical or virtual machines. The goals of other use - cases should not be compromised, e.g. we need to be able to start - and stop a batch job easily (for non developer), and trace the - progress and failure points of a batch. The client code should not - be aware of whether the processing is parallel or serial. - -* Scope - - * Any batch operation that reads data item-by-item from an input - source is capable of being scaled up by parallelizing. - - * The initial implementation might concentrate on multiple threads - in a single process. Ultimately we need to be able to support - multiple processes each one running in an application server - (e.g. so that jobs that require EJBs can be used). - -* Preconditions - - * A data source with multiple chunks (commitable units) - more chunks - than parallel processes. - - * A way for the framework to launch parallel processes. - -* Success - - * A batch completes successfully, and the results are verified. - - * A batch fails in one of the nodes, and when restarted processes - the remaining records. - -* Description - - [[1]] Framework splits input data into partitions. - - [[1]] Framework sends input data (or references to them) to - processing nodes. - - [[1]] Processing nodes act independently, converting the input data - and sending it transactionally to output source (as per normal - single process batch). - - [[1]] Framework collects status data from individual nodes for - reporting and auditing. - - [[1]] When all nodes are complete Framework decides that batch is - complete finishes processing. - -* Variations - - Two failure cases can be distinguished, bad input data on a node and - an internal node failure have different implications for how to - proceed. In both cases, however - - [[1]] Framework catches exception and classifies it. Rolls back - current transaction to preserve state of data (input and output). - - [[1]] Framework saves state for restart from last known good - point, including a pointer to the next input record. - - Then if a processing node detects bad data in the input source, it - cannot be restarted or re-distributed because the data need to be - modified for a successful outcome. - - [[1]] Framework alerts Operator of the location and nature of the - failure. - - [[1]] Operator waits for batch to finish - the overall status will - be a failure, but most of the data might be consumed. - - [[1]] Operator fixes problem and restarts batch. - - [[1]] Framework does not re-process data that has already been - processed successfully. The parallel processing nodes are used as - before. - - [[1]] Batch completes normally. - - If a processing node fails unrecoverably (e.g. after retry timeout), - but with no indication that the input data were bad, then the data - can be re-used: Framework returns unprocessed input data, and - redistributes it to other nodes. - -* Implementation - - * There are actually two approaches to this problem, which are - largely complementary. - - [[1]] The model dynamically assigned chunks of items to - be processed and sends them to durable middleware. Worker - processes pick them up and process them, sending back a message - about the status. This approach works best if the dispatching is - efficient compared to the processing. - - [[1]] The approach is more like running multiple - jobs in parallel, with input data partitioned into larger pieces, - and not split any further by the dispatcher. The item reading - happens in the worker processes. This approach is necessary if - the dispatcher in the model becomes a bottle neck. - - Generally, chunking is easier to implement than partitioning, but - there are tools available for implementing both patterns - efficiently. - -** Chunking - - The messages from a dispatcher to worker processes consist of a - chunk of items - a set of items to be processed together in a single - transaction (or as the worker sees fit). The dispatcher is usually - single threaded, but this is only a restriction based on the input - data type (if it is a file it is difficult to read in parallel and - maintain restartability). Using a process indicator the dispatcher - could be reading from a database table in a multi-threaded model. - - The main restriction is that for restartability the messages between - the dispatcher and workers has to be durable (i.e. JMS or - equivalent). If there is a durable middleware there are no in - principle difficulties with this approach. - - The practicalities deserve some discussion. In particular the - dispatcher has to co-ordinate asynchronous replies from its workers, - and also has to avoid overwhelming the workers (so there should be - some throttling). As long as the middleware is durable the - dispatcher can simply wait for replies whenever it thinks there are - workers working. It needs to record this expectation in a durable - form as well, as part of an <<>> for the step. - -** Partitioning - - The hard thing about this use case is the partitioning of input (and - output) sources. Ideally, this has to be done in such a way that - the individual operations are unaware that they are participating in - a batch farm. Partitioning has to be at least partially - deterministic because restarts have to be able to ignore data that - have already been processed successfully. - - Consider two examples: a file input source and a JDBC (SQL query) - based input source. Each provides its own challenges. - -*** File Data Source - - * If each node reads the whole file there could be a performance - issue. They would all need to have instructions about which lines - to process. - - * If each record of input data is a line, this isn't so bad. Each - node can have a range of line numbers to process. The only problem - is knowing how many lines there are, and how many nodes, so that the - job can be partitionaed efficiently. - - * But if each input record can span a variable number of lines (not - that unlikely in practice), then we can't use line numbers - - * Maybe the best solution is to use middleware anyway. A single - process parses the file and sends it to a message queue, item by - item (or chunk by chunk). The integration pattern could then be a - simple Eager Consumer, assuming that all records are processed - independently. The messaging semantics would simply have to ensure - that a consumer can roll back and return the input records to a - queue for another consumer to retry. - - * For large batches a real messaging infrastructure (JMS etc.) with - guaranteed delivery would be a benefit, but might be seen as - overkill for a system that didn't otherwise require it. In this - case we could imagine the partitioning process being one of simply - dividing the input file up into smaller files, which are then - processed by individual nodes independently. The integration - pattern is then different - more like a Router. - - * What would parallel processing look like to the client? We can - make it completely transparent if we assume that the client only - ever implements <<>> and <<>>. The - client code is unaware of the partitioning of its data source. - - * Parallelisation could also take place at the level of the - <<>> - we could proxy the data provider and wrap it in - a partitioning proxy: - -+--- - - - - - ... - - - - - - - - ... - - -+--- - -*** SQL Data Source Partitioning - - * If each node is allowed to do its own query or queries to - determine the input data: - - * Each node has to be given a way to narrow the query so that they - don't all use the same data. There is no easy universal way to - achieve this, and in the general case we have to know in advance - when we are going to execute in a parallel or as a single process. - Maybe a range of primary keys would work as a special case that we - could support as a strategy. - - * Maybe we could assume that all nodes execute precisely the same - query, and then provide a way to add a cursor to the result set, - so it can be treated a bit more like a file. - - * We might be forced to use a distributed transaction to ensure - that all the nodes see the same data. This would be unfortunate, - but possibly necessary. It would be up to the client to configure - distributed transactions if that was required, otherwise the - result might be unpredictable if data can be added to an input - source while it is being read. - - * If only one query is done by the Framework and the results shared - out amongst the nodes we face the issue of how to send the data - between nodes. Performance problems might ensue. Plus (more - seriously) the individual nodes would now need a different - implementation if they were acting in a parallel cluster to the - vanilla serial processing case - a single node would do the query - and work directly with the results, whereas in a parallel - environment it would be one step removed from the actual query. - This breaks our encapsulation design goal. - - * When considering the approach to partitioning the data source - we should follow closely the discussion above on partitioning a file - input source. If the client is to remain unaware of the batch - parameters, then an interceptor looks like the best approach. - - If each node prefers to do its own query then an interceptor would - have to catch the call to a JDBC template and modify the query - dynamically. This is quite a scary thing to be doing - it might end - up with us needing to parse the SQL and add where clauses. Maybe a - client should be forced to specify (in the case of a parallel batch) - how his query should be partitioned. For example: - -+--- - - - - SELECT * from T_INPUT - - - - SELECT * from T_INPUT where ID>=? and ID - - - -+--- - - It would be an error to run a batch in parallel if the partition - query had not been provided. - - * What happens if the data source changes between failed execution - and restart? We can't legislate for that because it is outside the - realm of what can be controlled through a transaction. A restart - might produce different results than the original failed batch would - have done were it successful. diff --git a/src/site/apt/cases/partial.apt b/src/site/apt/cases/partial.apt deleted file mode 100644 index 015ff5a19..000000000 --- a/src/site/apt/cases/partial.apt +++ /dev/null @@ -1,154 +0,0 @@ - ------ - Partial Processing Use Case - ------ - Dave Syer - ------ - January 2007 - -Partial Processing - -* Goal - - Support partial processing of a batch, without having to interrupt - or manually restart, but enabling corrective action to be taken - after the process has finished to complete the processing of failed - records. A batch that is going to fail completely can be be - identified as soon as possible, but one which is substantially - alright can run as far as possible to prevent costly duplication. - Records that are skipped are reported in such a way that they can be - easily identified by the Operator and / or Business User and a new - batch created to finish the original goal. By the same token, in - the case of an aborted batch where a minority of records are - processed successfully first time, it should be possible to identify - the successful records and exclude them from data presented on - restart. - -* Scope - - Any batch should be configurable to support partial processing. - -* Preconditions - - * A data source with a small number of bad records exists. - -* Success - - * A test data set with a small number of bad records is run through - the batch processer and completes normally. Operator confirms - that the good recirds are all processed and then fixes and - resubmits the bad records, and confirms that they are also - correctly processed with no duplicates. - -* Description - - The vanilla flow proceeds as follows: - - [[1]] Batch processing begins as per normal (see for example - {{{./chunks.apt}chunk processing use case}}). - - [[1]] A record is processed. This step repeats until... - - [[1]] Container detects a bad record, e.g. by catching a - classified execption. - - [[1]] Container logs the exception in a way that identifies the - bad record easily and immediately to the Operator. - - [[1]] Container stores an identifier for the bad record (or the - whole record) in a location designated to the Operator for that - purpose. - - [[1]] Container determines that the batch can still succeed - despite the cumulative number or nature of bad records - the bad - record is skipped. Container goes back to normal processing, and - eventually completes the whole batch. - -* Variations - -** Abort Batch Early - - The batch cannot skip all records. After each failure the decision - about whether to coninue has to be made: - - [[1]] When a record is processed successfully, Container logs the - event in a form that can be used later to identify successful - records in case the batch is aborted. - - [[1]] Container determines that a sufficiently large fraction of - the records processed so far have failed. The faction relevant is - to be specified through configuration meta data (not specified by - business logic). - - [[1]] Container aborts the batch with a clear signal to the - Operator that it has aborted owing to an unacceptable number of - errors. - -* Implementation - - * When the decision to abort is taken, Container may have - successfully processed a small number of records and the - corresponding transactions might have committed. Those records that - were successfully processed on the first attempt are easy to - exclude from the restart, if transactional semantics are respected - by the item processing. - - * The decision to abort is based on exception classification. Each - time an item is processed, the framework needs to catch exceptions - and classify them as - - * fatal: signals an abort - rethrow. - - * transient: nominally fatal, but the operation is retryable. - - * non-fatal: signals a skip. - - The transient failure is really just a sub-type of fatal case. It - is treated differently by the {{{./retry.html}retry framework}} but - not necessarily by the vanilla batch. - - * Actually we can't decide what action to take simply on the - evidence of the current exception. What we need to do is decide, - potentially based on the whole history of exceptions in a given - batch, whether the latest one should trigger an abort. E.g. a - simple and sensible policy would be to abort if the total number of - exceptions reaches a threshold, either absolute or relative to the - number of items processed. - - * So how does it look? In the template... - -+--- -public void iterate(RepeatCallback callback) { - - ... - - try { - result = callback.doInIteration(context); - } catch (Exception e) { - handleException(e); // Maybe re-throw, maybe not... - } - - ... - -} -+--- - - If the callback was transactional it has already rolled back. If - the whole <<>> was transactional we need to rethrow - - * If the processing is asynchronous, the template has to execute in - a separate thread (see {{{./async.html}asynchronous example}}). In - this case the whole thread (i.e. the <<>>) has to be - transactional. Whoever is counting failed items needs to be - poooling information from multiple threads. - - * It may also be the role of the framework to translate exceptions - into a batch-specific hierarchy. This is not the same concern as - exception classification (as done for instance by the Spring Jdbc - and Jms templates). Exception classification might also be of - value, but the argument is not as clear cut as the existing core - templates, where there is an underlying Jave EE API checked - exception to convert. In the absence of a batch-specific exception - hierarchy definition, we could choose to leave exception translation - out of the batch framework. - - diff --git a/src/site/apt/cases/pause.apt b/src/site/apt/cases/pause.apt deleted file mode 100644 index 15b568a3b..000000000 --- a/src/site/apt/cases/pause.apt +++ /dev/null @@ -1,121 +0,0 @@ - ------ - Pause Resume Use Case - ------ - Dave Syer - ------ - October 2008 - -Use Case: Pause and Resume Job Execution - -* Goal - - Allow a job to pause itself and await further instructions. A - paused status indicates to a user that the job is waiting, either - for a manual signal to proceed, or for a remote worker to finish - doing something asynchronously. For instance, a job may require - manual verification of business condition before continuing - a - sanity check on critical data. Assume that a job execution could - receive hundreds of resume signals, and this is a "normal" - situation, so it does not create a horrible mess in the history of - the execution - e.g. looking like hundreds of restarts. - -* Scope - - * The instruction to pause comes from processing logic, not from an - external signal (like an interrupt). A variation where the signal - comes from outside might be a useful extension, but isn't explicitly - included here. - -* Preconditions - - * A job is configured and one of its components can send the signal to pause - - * The launching interface has the ability to resume a paused job - - * The execution meta data can be inspected to verify that a pause has occurred - -* Success - - * User launches job and verifies that it has paused at a certain point - - * User resumes job and verifies that it completes successfully. - - * The end state is indistinguishable from a successful completion of - the job in one attempt - -* Description - - The vanilla successful case proceeds as follows: - - [[1]] User launches a new job execution. - - [[1]] Framework begins processing, and successfully executes one - or more steps. - - [[1]] At the end of a step Framework encounters condition that - signals it should pause (e.g. a status flag). - - [[1]] Framework gracefully exits the job execution, marking it as - paused so that it can be identifed as such when asked to resume. - Often the framework will also be configured to notify a user that - the pause has occurred, so that some business condition can be - verified manually. - - [[1]] User requests the job execution be resumed. - - [[1]] Framework picks up where it left off, ignoring steps that - have already successfully executed and starting with the one after - the pause. - - [[1]] Job finishes processing and Framework marks it as - sucessfully completed, just as if it hadn't paused in the first - place. - -* Variations - - * The agent that causes the job to resume is not a User but a remote - worker process. - - * Two agents request a resume at the same time. One of them has to - lose (an exception is acceptable). - - * A step pauses in the middle of execution. The job picks it - up and start where it left off, just like in a restart. - - * More than one step was executing when the pause signal was - detected. Framework allows steps that are executing in process to - complete (or pause) before exiting the job execution. - - * More than one step is in a paused state when the job resumes. - Requires no special treatment from Framework: if those steps were - active when the pause reached the job level on the last run, then - they will be processed in the same way on a resume (presumably in - multiple threads). - -* Implementation - - * A new <<>>. - - * The <<>> interface may not need any more than it already has: - -+--- -public interface JobLauncher { - - public JobExecution run(Job job, JobParameters jobParameters) throws ....; - -} -+--- - - In the case that the last execution failed, we already pick up from - where we left off with a new <<>>. The only - difference now is that we don't need a new <<>>, so we - have to be careful about concurrency - what happens if two agents - try to resume the job at once. To be safe we can treat this the - same way as a restart - lock the <<>> table in the - database by setting a TX isolation attribute on the - <<>>. - - * When we resume we need to wind forward through the job execution - and look at all step executions to see if they are active. Once the - <<>> has been identified the process should be no - different to a restart. diff --git a/src/site/apt/cases/restart.apt b/src/site/apt/cases/restart.apt deleted file mode 100644 index 8f703d5ef..000000000 --- a/src/site/apt/cases/restart.apt +++ /dev/null @@ -1,86 +0,0 @@ - ------ - Restart Use Case - ------ - Dave Syer - ------ - January 2007 - -Use Case: Manual Restart After Failure - -* Goal - - Restart a failed or interrupted batch and have it pick up where it - left off (within limits of transaction boundaries) to save time and - resources. A key goal is that the management of the batch process - (locating a job and its input and results, starting, scheduling, - restarting) should be as easy as possible for a non-developer, like - an application support team with some business back up. - -* Scope - - Any batch should be able to restart gracefully, even if (depending - on chosen execution or client implementation) it might have to go - right back to the beginning. - -* Preconditions - - * It is possible to identify exception conditions under which a - restart will be able to carry on processing a batch from where it - left off. - - * There exists a persistent storage mechanism for the initial - conditions. - -* Success - - * Force a batch to fail, and then fix the problem and restart. See - successful completion with no duplicate results. - -* Description - - [[1]] A batch operation encounters an exception which forces the - process to stop processing. - - [[1]] Framework catches exception and classifies it. - - [[1]] Framework logs event with enough information to identify the - location of the job and the nature of the problem. - - [[1]] Framework saves initial condition from last commit point, to - enable restart to start from the last known good operation. - - [[1]] Operator fixes problem (e.g. makes missing resource available, - edits input file). - - [[1]] Operator restarts batch. - - [[1]] Framework loads initial conditions and continues processing. - -* Variations - - * Some restarts might lend themsleves to being handled automatically - - see the use case {{{./retry.html}Automatic Retry}}. - -* Implementation - - * The saving of initial conditions needs to be strategised. In some - cases saving a native serialization to a file will suffice. In - others a database might be used, or some custom serialization - (persist / rehydrate). - - * The initial condition is naturally under control of the - <<>>. The client need not know about the persistence - and rehydration. In fact explicit persistence and rehydration might - be overkill - just relying on the transaction semantics might be - adequate in a lot of cases. The <<>> would have to be - aware of the transactions, which we assume are normally demarcated - in the <<>>. Since the point at which persistence - is needed is tied to transaction commits, there may have to be some - transaction synchronization. - - * The persistence of initial conditions is a cross cutting concern. - It may lend itself (along with the application of an execution - handler generally) to being implemented as an aspect. Compare the - <<>>, where the most common usage is via an - interceptor, but occasionally the template is used directly by - client code. diff --git a/src/site/apt/cases/retry.apt b/src/site/apt/cases/retry.apt deleted file mode 100644 index 5ea21cac7..000000000 --- a/src/site/apt/cases/retry.apt +++ /dev/null @@ -1,279 +0,0 @@ - ------ - Automatic Retry Use Case - ------ - Dave Syer - ------ - January 2007 - -Use Case: Automatic Retry - -* Goal - - Support automatic retry of an operation if it fails in certain - pre-determined ways. Client code is not aware of the details of - when and how many times to retry the operation, and various - strategies for those details are available. The decision about - whether to retry or abandon lies with the Framework, but is - parameterisable through some retry meta data. - - Retryable operations are usually transactional, but this can be - provided by a normal transaction template or interceptor - (transaction meta data are independent of the retry meta data). - -* Scope - - Any operation can be retried, but there are restrictions on nesting - transactions (normally an inner transaction needs to be - propagation=NESTED). - -* Preconditions - - An operation exists that can be forced to fail and is able to - succeed on a retry. - -* Success - - * Verify that an operation fails and then succeeds on a retry. - - * Verify that back off policy (time between retries) can be - strategised without changing client code. - - * Verify that the retry policy can be strategised, and can be used - to change the number of retry attempts depending on the type of - exception thrown in the retry block. - -* Description - - Successful retry proceeds as follows: - - [[1]] Framework executes an operation provided by Client. - - [[1]] The operation fails and Framework catches an exception, - classified as retryable. - - [[1]] Framework waits for a pre-defined back off period. The - period is not be fixed, but is strategised so that different - policies can be applied. The most common and useful policy is an - exponentially increasing back off delay, with a ceiling. - - [[1]] Framework repeats the operation. - - [[1]] Processing is successful. - - [[1]] Framework stores and / or logs statistics about the retry - for management purposes. Details? - -* Variations - - The following variations are supported. - -** Retry Failure - - A retry can fail for a number of reasons. E.g. if the number of - retries is too high, or there is a timeout, or an exception of - another sort that cannot be classified as retryable. - - [[1]] Last retry attempt fails and Framework determines that - another retry is not permitted by the current policy. - - [[1]] Framework records status for management purposes. - - [[1]] Framework throws a recognisable exception? - - [[1]] Control may return to client (if the exception was caught), - or the processing may end. - -** Transient and Non-transient Failures - - We may wish to classify exceptions into (at least) three types, and - vary the retry policy based on the classification: - - * Transient failures come from resources that are external and may - have independent lifecycles to the client process. Examples are - database deadlock, network connectivity. It is always worth - retrying on a transient failure, and normally we can keep retrying - (if not forever then for a very long time), in the belief that - eventually the resource will become available again. - - * Non-transient failures can be retried a few times. This is the - default. - - * Non-retryable failures like a configuration or input data error - should not be retried (they will always fail the same way). - -** Early Termination - - Normally client code is unaware of the Framework, but occasionally - emergency measures might be taken inside client code where all - further retry attempts are vetoed for the current block. - -** Stateful Retry - - A stateful (or external) retry is used to force a roll back of an - external message (or other data) resource, so that the message will - be re-delivered. The implementation has to be stateful so it can - remember the context for the failed message next time it is - delivered. The additional features of a stateful retry, as opposed - to a normal rollback, are that: - - * A message can be retried indefinitely or up to a set number of - times, after which an error processing route is taken. - - * A back-off delay is used at the of the retry - before any other transactional resources are enlisted. - -* {Implementation} - - * The vanilla case and most of the variations can be achieved with a - simple template approach: - -+--- -RetryTemplate retryTemplate = new RetryTemplate(); -retryTemplate.setRetryPolicy(new SimpleRetryPolicy(5)); -Object result = retryTemplate.execute(new RetryCallback() { - public Object doWithRetry(RetryContext context) throws Throwable { - // do some processing - return result; - } -}); -+--- - - * Schematically we can represent the implementation of the [retry} - template as follows: - -+--- -1 | TRY { -1.1 | do something; -2 | } FAIL { -2.1 | if (retry limit reached) { -2.2 | rethrow exception; - | } else { -2.3 | TRY(1) again; - | } - | } -+--- - - * The template has policies for back off and retry (whether or not - to retry the last exception). The example above shows the retry - policy being set to simply retry all exceptions up to a limit of 5 - times. - - * The <<>> has an API that allows clients to override - the retry policy. The context can also be accessed as a thread - local from a static convenience class, in the case that the callback - is implemented as a wrapper around a POJO. - - * External retry is the most difficult variation to implement, and - doesn't fit naturally into the template model above. Two things - depend on the retry count - back-off delay and the decision to - follow the recovery path - so it needs to be available at the - beginning of every processing block. - - We will discuss the implementation from a JMS-flavoured viewpoint, - where the current item being processed is a message. This can be - generalised to more generic data types, as long as the item can be - rejected transactionally to signal that we require it to be - re-delivered to this or another consumer. - - Consider this pattern, which is very typical: - -+--- -1 | SESSION { -2 | receive; -3 | RETRY { - | remote access; - | } - | } -+--- - - A <<>> is responsible for the RETRY(3) block. But - we can't put the same wrapper around the whole process: - -+--- -0 | RETRY { // Do not do this! -1 | SESSION { -2 | receive; -3 | RETRY { - | remote access; - | } - | } - | } -+--- - - because the receive(2) might not get the same message back on the - second and subsequent attempts (another consumer might get it, or it - might come out of order). So external retry has a different flow - - it might be a different implementation of the same interface, or a - different parameterisation of the normal retry template. - - We can break down the implementation of an external retry into steps - as follows: - -+--- -1 | SESSION { -2 | receive; -3 | TRY { -3.1 | if (already processed) { -3.2 | backoff; - | } -4 | RETRY { - | remote access; - | } -5 | } FAIL { -5.1 | if (retry limit reached) { -5.2 | recover; - | } else { -5.3 | rethrow exception; - | } - | } - | } -+--- - - Decisions (3.1) and (5.1) require knowledge of the history of - processing the current message. Note that the action on failure is - the opposite to the vanilla case {{{Implementation}above}} - if the retry - limit is not reached then we rethrow the exception. - - If the retry limit is not reached then the rethrow(5.3) causes the - SESSION(1) to roll back, and the message will be re-delivered. - RETRY(4) is a normal retry with a template. - - The retry logic is easy to implement - the hard bit is that the - policies depend on the history of the message. This requires some - special retry and back off policies that are aware of the history: - - * When a message arrives, at the beginning of the TRY(3) above, we - need to update our knowledge of its history. - - * The backoff policy can decide whether to back off immediately - when it is initialized at step (3.1). - - * The retry decision at (5.1) has to be aware of the history as - well as some simple exception classification rules. - - * If the retry cannot proceed the retry policy can take steps to - recover (5.2), e.g. send the current message to an error queue. - The exception should not propagate in this case. - - * If we fail and rethrow (5.3), then we need to store the - knowledge of the message history somewhere where another consumer - can access it. - - There is a small conundrum about what value to return from the - TRY(3) block if it ultimately fails (5.2) - a normal retry never - completes unless it is successful, but an external retry can - complete if it is unsuccessful. The obvious choice is to return - null. It probably won't matter in a messaging application anyway - because the client of the retry block probably isn't expecting - anything. It may matter if the TRY(3) block is part of a batch - because the batch template uses null as a signal that the current - batch is complete. But on the other hand it might be a good - strategy to close the batch if processing a message fails. - - With JMS there is no indication in the <<>> how many times - it has been rejected - only a flag <<>> to show - that it has failed at least once. To count the number of retries, - we have to store a global map of messages (ids) to retry counts - (within a single VM - for more than one OS process each one has to - be independent). - diff --git a/src/site/apt/cases/scheduled.apt b/src/site/apt/cases/scheduled.apt deleted file mode 100644 index 7b65ce82d..000000000 --- a/src/site/apt/cases/scheduled.apt +++ /dev/null @@ -1,42 +0,0 @@ - ------ - Scheduler Managed Use Case - ------ - Wayne Lund, Dave Syer - ------ - May 2007 - -Use Case: Scheduler Managed Processing - -* Goal - - Ensure that an Enterprise Scheduler can interact with the Batch Launcher to start, stop, - suspend and/or kill a batch job. - -* Scope - - * Batch jobs tends to run within carefully planned job stream - schedules. At a minimum this requires an integration between the - Batch Launcher (in the abstract) and the scheduler's control - mechanism to start and stop batch jobs and then to understand the - results of the batch job execution (e.g. COMPLETED, ABENDED, etc.) - so that subsequent actions may be taken. - - * Spring Batch does not aim to implement the scheduling concerns as - such (other tools are available for that). The framework, does need - to provide the information that such tools need to decide when to - act and what to do (e.g. exit code mapping). - -* Preconditions - - * A mechanism has been established for the scheduler to launch a batch job. This is often times - a simple unix or dos shell script. - - * A mapping of exit codes to the error code numbers that the scheduler is expecting on the exiting - of a batch job. - -* Success - - * Batch Jobs are launched and managed by scheduler - -* Description - diff --git a/src/site/apt/cases/simple.apt b/src/site/apt/cases/simple.apt deleted file mode 100644 index b24c77233..000000000 --- a/src/site/apt/cases/simple.apt +++ /dev/null @@ -1,290 +0,0 @@ - ------ - Simple Batch Repeat Use Case - ------ - Dave Syer - ------ - January 2007 - -Use Case: Simple Batch Repeat - -* Goal - - Repeat a simple operation such as processing a data item, or a - message, up to a fixed number of times, normally with a transaction - scoped to the whole batch. Transaction resources are shared between - the operations in the batch, leading to performance benefits. - -* Scope - - The operation to be repeated: - - * Can expect to use and manage its own I/O or datastore resources, - but not necessarily transactions; - - * May need to introspect the batch status (as a variation); - - * Executes synchronously or asynchronously (as a variation). - - * Is stateless - this is not a framework restriction in principle, - but simplifies the implementation for now. See in the - {{{store}Implementation}} section below for some notes on - stateful synchronisation; - - * Should be implementable as a POJO if desired. - -* Preconditions - - Client code can locate and acquire all the resources it needs for - the batched operation, and can force transactions to rollback for - testing purposes. - -* Success - - * Verify that a successful batch executed a fixed number of times. - - * Verify that a batch completes early but successfully if an - underlying transaction times out. - - * Terminate a batch by failing one of the operations, and verify - that the preceding operations rolled back (subject to batch meta - data). - - * Execute a batch asynchronously and verify that the correct number - of operations is performed. - -* Description - - We are often interested in a specific scenario of this use case - where the batched operation is: - - * Read a message or data item from an endpoint like a JMS - Destination. - - * Do some business processing involving database reads and writes. - - The vanilla successful batch use case proceeds as follows: - - [[1]] Framework starts a batch, acquiring resources as needed and - creating a context for the execution. - - [[1]] Client provides a batch operation in the form of a source of - data items and a processor acting on the data item. - - [[1]] Framework executes batch operation. - - [[1]] Repeat the last step until the batch size is reached. - - [[1]] Framework commits the batch. All database changes are - committed and received messages removed from the endpoints. - -* Variations - -** Rollback - - If one of the operations rolls back it will throw an exception. - Normal transaction semantics determine what happens next. Usually - (in the scenario described above) there is an outer transaction for - the whole batch, which rolls back as well: all the messages remain - unsent, and all the data remain uncommitted. A retry will receive - exactly the same initial conditions. - -** Timeout - - The batch size is not fixed. The use case proceeds as above, but in - the middle of a batch operation execution: - - - [[1]] Framework determines that the batch has timed out operation - (e.g. while it was waiting for an incoming message). - - [[1]] Framework commits the batch with all operations so far - complete - possibly a smaller than normal size. - -** Asynchronous Processing - - Instead of the Framework waiting for each operation to complete it - could spin them off independently into separate threads or a work - queue. The batch still has to have a definite endpoint, so the - Framework waits for all the operations to finish or fail - before cmpleting the batch. - -** Introspection of Batch Context - - Client may wish to inspect the state of the ongoing batch operation, - and potentially force an early completion. - -* {Implementation} - - * The completion of the batch loop is handled by a policy delegate - that we can use to strategise the concept of a loop that might - complete early. This can cover both the timeout variation and the - vanilla use case flow. - - * What form should the batch template (<<>>) - interface take? We might start with something like this: - -+--- -batchTemplate.iterate(new RepeatCallback() { - - public boolean doInIteration() { - // do stuff - } - -}); -+--- - - * A nice tool for a batch operation in a callback is an iterator - through a data set or message endpoint (<<>>), coupled - with a handler for processing the item. This adds a potential - implementation of <<>> that knows about the - <<>> and adds a processor object. E.g. as an - anonymous inner class: - -+--- -final ItemProvider provider = new JmsItemProvider(); -final ItemProcessor processor = new ItemProcessor() { - public void process(Object data) { - // do something with the data (a record) - } -}; - -batchTemplate.execute(new RepeatCallback() { - - public boolean doInIteration() { - Object data = provider.next(); - if (data!=null) { - processor.process(data); - } - return data!=null; - } - -}); -+--- - - * Is a batch template with callback the best implementation? Could - we perhaps use or re-use <<>> somehow? Which is - better for the client: - -+--- -batchTemplate.iterate(new RepeatCallback() { - - public boolean doInIteration() { - // do stuff - } - -}); -+--- - - where the batch template might itself use a <<>> - internally, or - -+--- -batchTemplate.iterate(new Runnable() { - - public void run() { - // do stuff with data - }; - -}); -+--- - - where the batch template is a <<>>. Probably the - former because it is more encapsulated: it gives the framework more - freedom to implement the template in any way it needs to, e.g. to - accommodate more complicated use cases. - - * To {store} up SQL operations until the end of a batch, and take - advantage of JDBC driver efficiencies, the client needs to store - some state during the batch, and also register a transaction - synchronisation. For this kind of scenario we introduce an - interceptor framework in the template execution. The template calls - back to interceptors, which themselves can strategise clean up and - close-type behaviour: - -+--- -public class RepeatTemplate implements RepeatOperations { - - public void iterate(RepeatCallback callback) { - - // set up the batch - interceptors.open(); - - while (running) { - - // allow interceptor to pre-process and veto continuation - interceptor.before(); - - // continue only if batch is ongoing - if (running = callback.doInIteration()!=null) { - interceptor.after(); - } - - } - - // clean up or commit the whole batch - interceptor.close(); - - } -} -+--- - - The <<>> can be stateful, and can store up inserts - until the end of the batch. If the <<>> is - transactional then they will only happen if the transaction is - successful. - - This way the client can even decide to use a batch interceptor - that runs in its own transaction at the end of the batch. - - * There is no need for an overall batch timeout because the inner - operations are synchronous and have their own timeout metadata - though transaction definitions. The whole batch (outer transaction) - may still have a timeout attribute, and then there is a corner case - where the batch operations are all successful, but because they all - took a long time the whole batch rolls back because of the timeout. - - * The context of the ongoing batch is closely linked with the - completion policy. The completion policy is pluggable into the - batch template, and acts as a factory for context objects which can - then be inspected by Client in the callback. For example: - -+--- -public class RepeatTemplate implements RepeatOperations { - - public void iterate(RepeatCallback callback) { - - // set up the batch session - RepeatContext context = completionPolicy.start(); - - while (!completionPolicy.isComplete(context)) { - - // callback gets the context as an argument - callback.doInIteration(context); - - completionPolicy.update(context); - } - - } -} -+--- - - * The example above provides Client the opportunity to inspect the - context through the callback interface. If Client is a POJO, - Framework has to create a callback and wrap it, in which case there - needs to be a global accessor for the current context or session. - The template is then responsible for registering the current context - with a <<>>. E.g.client code can look - at the session and mark it as complete if desired - (c.f. <<>>): - -+--- -public Object doMyBatch() { - - // do some processing - - // something bad happened... - RepeatContext context = RepeatSynchronizationManager.getContext(); - context.setCompleteOnly(); - -} -+--- diff --git a/src/site/apt/cases/steps.apt b/src/site/apt/cases/steps.apt deleted file mode 100644 index c0340464b..000000000 --- a/src/site/apt/cases/steps.apt +++ /dev/null @@ -1,176 +0,0 @@ - ------ - Batch: Sequential Steps Use Case - ------ - Dave Syer - ------ - January 2007 - -Use Case: Sequential Processing of Dependent Steps - -* Goal - - Compose a batch operation from a sequence of dependent steps. - Define and implement the operation only once, and allow restart - after failure without having to change configuration, and without - having to repeat steps that were successful. - - A sub-goal is to allow the progress of a batch through the steps to - be traced accurately for reporting and auditing purposes. This - requires the steps to be uniquely identified. - -* Scope - - * Simple linear sequence of steps. Slightly more complicated - requirements can be handled by putting independent steps in a - sequence (no need for splits and joins). - -* Preconditions - - * A non-trivial sequence is defined: - - * more than one step: - - * the effects of each step can be measured. - - * The sequence can be interrupted or artificially terminated in the - second or subsequent step. - -* Success - - * A non-trivial sequence executes successfully. The progress and - success of each step can be verified by the tester. - - * The same sequence is forced to fail on second step in such a way - that the first step result is not suspected of being in error, - e.g. by interrupting it. When it is restarted the first step is not - repeated, and the sequence is successful. - - * The same sequence is forced to fail on second step in such a way - that the first step result is obviously in error, even though it - completed normally. When the batch is restarted the first step - repeated, and the sequence is successful. - -* Description - - The vanilla successful case proceeds as follows: - - [[1]] Framework logs the start of a step, uniquely indentifying - the initial conditions. - - [[1]] Framework stores internal state so that initial conditions - can be re-created in the event of a restart. - - [[1]] Step execution proceeds as per one of the other use cases - (e.g. {{{file-to-database.html}Copy File to Database}}), including - transactional behaviour. - - [[1]] Client instructs Framework to store internal state needed by - further steps (e.g. cached reference data). - - [[1]] Framework logs successful completion of step, and stores - - [[1]] Repeat for next and subsequent steps. Internal state is - passed from one state to the next. - -* Variations - -** Internal Failure of Step - - If a step fails internally, e.g. because of resource becoming - temporarily unavailable, the sequence can be restarted without - repeating the previous steps. - - [[1]] Operator fixes resource problem (e.g. starts web service). - - [[1]] Operator restarts batch with no configuration or input data - changes. - - [[1]] Framework resumes batch from the last commit point of the - failed step. - - [[1]] Sequence completes normally. - - The process above could be carried out by the framework entirely (no - need for operator intervention) if a retry policy is in effect. - -** Failure of Step Owing to Bad Initial State - - If a step fails because it receives bad data from an earlier step, - the Framework cannot recover without intervention. - - [[1]] Operator attempts to restart without doing anything to fix - the problem. - - [[1]] Framework detects bad initial state immediately and fails - fast. - - If the original problem can be located and fixed (e.g. input data - for earlier step is revised): - - [[1]] Operator restarts batch signalling to framework which step - to begin with. - - [[1]] Framework locates initial state for the first step to be - executed. - - [[1]] Framework starts execution from the beginning of the desired - state. This time the input data are different, so the sequence - can complete normally. - -* Implementation - - * The need to save state for subsequent steps leads to the - introduction of a batch context concept. And the need for - initialising restarts leads to the context being serializable, - either natively or by some pluggable strategy (this is covered in - the {{{./restart.html}Restart after Failure}} use case). - - Unfortunately, the need for {{{./parallel.html}parallel processing}} - and automatic {{{./restart.html}restart}} also makes it practically - impossible for steps to handle the context at the level of a single - thread of execution, where the client needs to implement business - logic. If a step is executing in parallel, then each node needs to - be able to restart independently, but the context needs to be a - single object that can be passed on to the next step (unless all the - steps are parallelised with the same multiplicity, which might not - be efficient in general). - - Thus batch context must be defined and managed by the template or - execution handler. - - * The requirement for steps might have implications for the - implementer of the batch operation (the client). Obviously a client - defines the sequence of steps according to the business requirement, - but ideally we would like him to be unaware of the reporting and - restart infrastructure. Maybe an array of callbacks works (the - callback interface is irrelevant, except that it accepts a context - object as an argument): - -+--- -batchTemplate.iterate(new RepeatCallback[] { - - new RepeatCallback() { - public boolean doInIteration(RepeatContext context) { - // do stuff for step one - }; - }, - - new RepeatCallback() { - public boolean doInIteration(RepeatContext context) { - // do stuff for step two - the context - // is the same... - }; - } - -}); -+--- - - Notice that there is no need for the context to be set explicitly - before executing the callback. The context is handled internally to - the batch template using an analogue of the - <<>>. - - * If we prefer that clients never need to know about batch - templates, then the code above needs to be automated. This would be - where an additional domain layer might come into play - (c.f. <<>>). diff --git a/src/site/apt/cases/template.apt b/src/site/apt/cases/template.apt deleted file mode 100644 index ed359bed6..000000000 --- a/src/site/apt/cases/template.apt +++ /dev/null @@ -1,22 +0,0 @@ - ------ - Template Use Case - ------ - Dave Syer - ------ - January 2007 - -Use Case: Template - -* Goal - -* Scope - -* Preconditions - -* Success - -* Description - -* Variations - -* Implementation \ No newline at end of file diff --git a/src/site/apt/downloads.apt b/src/site/apt/downloads.apt deleted file mode 100644 index 60a3629d4..000000000 --- a/src/site/apt/downloads.apt +++ /dev/null @@ -1,133 +0,0 @@ - --------- - Downloads - --------- - Dave Syer, Ben Hale, Michael Minella - ------ - December 2007, February 2009, July 2009 - -Spring Batch Downloads - - The current GA release is <<2.2.6.RELEASE>>, the latest snapshots are <<3.0.0.BUILD-SNAPSHOT>>. The version 2.0.x and 1.x branches are now in maintenance (the last release was <<2.0.4.RELEASE>>). - -For runtime concerns and a container for running a Job as a service see the {{{http://docs.spring.io/spring-batch-admin/}Spring Batch Admin}} project and the {{{http://docs.spring.io/spring-batch-admin/getting-started.html}getting started}} link there. - -* Zip Downloads - - There is a ZIP artifact containing the release JARs called <<>>. This file contains the JAR files for the release, including source code and the samples. - - * Full releases: {{{http://docs.spring.io/downloads/nightly/release-download.php?project=BATCH}here}}. - - * Milestones: {{{http://docs.spring.io/downloads/nightly/milestone-download.php?project=BATCH}here}}. - -Source code can also be browsed and downloaded at {{{https://github.com/spring-projects/spring-batch}Github}}. - -* Maven Artifacts - - Traditional "spring-*" artifacts are deployed on the Maven central repo. Full releases in this format also go in our s3 repository, browseable {{{http://shrub.appspot.com/maven.springframework.org/release/org/springframework/batch/}here}}: - -+--------------- - - spring-releases - Spring Maven RELEASE Repository - http://repo.spring.io/release - -+--------------- - - You can see the internal and external project dependencies in the <<>> files and also in the dependency reports for each module on this website. You will probably need <<>> and <<>>. Source code is packaged in a separate jar file in the same directory, and the samples are also bundled in the same way. - - Individual dependencies can then by added like so (inside a \ element at the top level): - -+--------------- - - org.springframework.batch - spring-batch-core - 2.2.6.RELEASE - -+--------------- - - All releases are also published in the SpringSource Enterprise Repository, {{{http://www.springsource.com/repository/app/}searchable here}} and {{{http://shrub.appspot.com/repository.springsource.com/maven/bundles/release}browseable here}}. The repository is segregrated by release, milestone and snaphot releases. For full releases use these repositories: - -+--- - - com.springsource.repository.bundles.release - SpringSource Enterprise Bundle Repository - - SpringSource Bundle Releases - http://repository.springsource.com/maven/bundles/release - - false - - - - com.springsource.repository.bundles.external - SpringSource Enterprise Bundle Repository - - External Bundle Releases - http://repository.springsource.com/maven/bundles/external - - false - - -+--- - - In the SpringSource Enterprise Repository the artifacts have long, Java-package-like names: <<>>, <<>> and <<>>. They have dependencies which are in the same style, and are transitively complete within the same repository. So individual dependencies can by added like so (inside a \ element at the top level): - -+--------------- - - org.springframework.batch - org.springframework.batch.core - 2.2.6.RELEASE - -+--------------- - -* Milestone Builds - - These builds are provided for evaluation and community feedback. Spring Batch builds have a release identifier ending in "MX" where X is the milestone number, or "RCX" for a release candidate (older builds have "mX" and "rcX"). - - You can find the .ZIP downloads of the milestones {{{http://docs.spring.io/downloads/nightly/milestone-download.php?project=BATCH}here}}. - - Milestones also published in the s3 repository with Maven Central format dependencies {{{http://shrub.appspot.com/maven.springframework.org/milestone/org/springframework/batch}browseable here}}. To use them, just add the following repository to your POM (inside a \ element at the top level): - -+--------------- - - spring-s3 - Spring Maven MILESTONE Repository - http://repo.spring.io/milestone - -+--------------- - - Then individual dependencies can then by added like so (inside a \ element at the top level): - -+--------------- - - org.springframework.batch - spring-batch-core - 2.2.6.RELEASE - -+--------------- - - Milestones are also deployed to the SpringSource Enterprise Repository ({{{http://shrub.appspot.com/repository.springsource.com/maven/bundles/milestone/}browseable here}}), so use this repository if you want to depend on artifacts in the <<>> style: - -+--- - - com.springsource.repository.bundles.milestone - SpringSource Enterprise Bundle Repository - - SpringSource Bundle Milestones - http://repository.springsource.com/maven/bundles/milestone - - false - - -+--- - - Then individual dependencies can by added like so (inside a \ element at the top level): - -+--------------- - - org.springframework.batch - org.springframework.batch.core - 2.2.6.RELEASE - -+--------------- - -Snapshot Builds - - Nightly snapshots are available through the same process with slightly different URLs. See {{{./snapshots.html}here}} for details. diff --git a/src/site/apt/features.apt b/src/site/apt/features.apt deleted file mode 100644 index ab58920ac..000000000 --- a/src/site/apt/features.apt +++ /dev/null @@ -1,156 +0,0 @@ - ------ - Spring Batch Features - ------ - Dave Syer - ------ - July 2007, February 2008, January 2009 - -Spring Batch Features and Roadmap - - See also {{{./migration/2.0-highlights.html}details of main themes of 2.0}}. - -* 2.0 Features - - The following features are supported by Spring Batch 2.0: - -** Optimisation and Infrastructure - - * RepeatOperations: an abstraction for grouping repeated - operations together and moving the iteration logic into the - framework. - - * RetryOperations: an abstraction for automatic retry. - - * ItemReader abstraction and implementations for flat files, xml - streaming and simple database queries. - - * Flat files are supported with fixed length and delimited records - (input and ouput). - - * Xml is supported through Spring OXM mapping between objects and Xml - elements (input and ouput). Large files are streamed, not read as a whole. - - * Database implementations of ItemReader are provided that map a row of - a ResultSet identified by a simple (single or multiple column) - primary key. - - * ItemWriter abstraction and implementations for flat files and xml - (the Sql case is just a regular Jdbc Dao). - - * ItemReader and ItemWriter implementations are generally - ItemStreams. An ItemStream provides the facility to be restored - from a persistent ExecutionContext so that jobs can fail and be - restarted in another process. - - * For modifying an item before it is written, there is the - ItemProcessor abstraction. ItemProcessor and ItemWriter are the - two most common application developer touch points. - -** Core Domain - - * Job is the root of the core domain - it is a recipe for how to - construct and run a JobInstance. - - * A Job is composed of a list of Steps (sequential step model for - job). - - * Job is also the entry point for launching a JobExecution. - - * Step is the corresponding point for a StepExecution. Step is the - main strategy for different scaling, distribution and processing - approaches. The 2.0 release contains implementations for in-process - execution (single VM), and a PartitionStep as part of an SPI for - remote execution of steps. See below (under Execution). - - * The most commonly used implementation of Step is a wrapper for an - ItemReader and an ItemWriter. There is also a special - implementation that wraps a Tasklet, which can be used to execute a - single action like a stored procedure call. - - * FactoryBeans are provided for creating Step instances with the - most common features. See in particular - FaultTolerantStepFactoryBean for a factory that provides convenient - configuration points for skips and retries. - - * Late binding of environment properties, job parameters and - execution context values into a Step when it starts. A custom - Spring Scope takes care of deferring the initialization of - components until a step is executing. - -** Job Execution and Management - - * A simple JobLauncher to launch jobs. Start a new one or restart - one that has previously failed. This can be used by a command-line - or JMX launcher to take simple input parameters and convert them to - the form required by the Core. (Examples of both are in the Samples - module.) - - * Persistence of job meta data for management and reporting - purposes: job and step identifiers, job parameters, commit counts, - rollback counts. Execution attributes (a human readable - represenation of the state of the job - can be augmented by - developers). - - * Adjustiable exception handling strategies allowing fault - tolerance through skipping bad records. - - * Concurrent execution of chunks (a chunk is a batch of items - processed in the same transaction) through the Spring TaskExecutor - abstraction. - - * Automatic retry of a chunk and recovery for items that have - exhausted their retry count. - - * Translation of job execution result into an exit code for - schedulers running the job as an OS process. - - * A set of listener callbacks that users can implement and register - with a Step to add custom behaviour like footer records. - - * Remote chunking of steps. The step proceeds as in the single JVM - case, but each chunk is passed on to the remote processes. The - remote execution is an asynchronous listener of some sort - (e.g. message-driven component or web service). Implemented using - {{{http://projects.spring.io/spring-integration/}Spring - Integration}} in a Batch sub-project (spring-batch-integration). - - * Partitioning - steps execute concurrently and optionally in - separate processes. Feedback loop between consumers and producers - to prevent overflows. Spring Batch provides an SPI for Partitioning - and an implementation for local (multi-threaded, single JVM) - execution. - - * OSGi support. Deploy the Spring Batch framework as a set of OSGi - services. Deploy individual jobs or groups of jobs as additional - bundles that depend on the core. Spring Batch JAR files are also - OSGi bundles. - - * Non-sequential models for Job configuration (branching and - descision support). - -** Samples - - * A range of samples is available as a separate module. They all - use a common simple configuration and extend in various ways to show - the different features of the Execution module. - -* Roadmap (Beyond 2.0). - - * Issue tracking - a job is not finished until all issues with its - executions are resolved. Spring Batch can provide hooks to - integrate with internal issue tracking systems so that the lifetime - of a job can be properly managed. - - * Auditing. Implement hooks to monitor not only what jobs execute - and the result of the execution (as per 1.0 possibly with some - richer options for detailed outcome reports), but also who has - executed the job, what changes they made to runtime parameters. - -* SpringSource Enterprise Batch - - * The plan is for {{{http://www.sping.io}Spring}} to - provide an enterprise product that deals with runtime concerns, as - opposed to programming and configuration. - - * Triggering. Other runtime concerns, like monitoring and management - of jobs and historical executions. diff --git a/src/site/apt/getting-started.apt b/src/site/apt/getting-started.apt deleted file mode 100644 index 565dd5c96..000000000 --- a/src/site/apt/getting-started.apt +++ /dev/null @@ -1,90 +0,0 @@ - ------ - Spring Batch Getting Started - ------ - Dave Syer - ------ - December 2007, June 2009 - -Spring Batch Getting Started - - A convenient way to get started quickly with Spring Batch is to run the samples which are packaged in the samples module. There is also a simple command line sample (or "archetype") which has a bare bones but complete implementation of a simpel job. The source code for the samples (and the other modules) is available either from the {{{./downloads.html}.Zip assembly}} or from {{{source-repository.html}Git}}. - -* Using Spring Tool Suite (STS) - - This is the quickest way to get started. It requires an internet connection for download, and access to a Maven repository (remote or local). - - * Download STS version 3.4.* (or better) from the {{{http://spring.io/tools/sts/}Spring website}}. STS is a free Eclipse bundle with many features useful for Spring developers. - - * Go to <<Other...>>> and select <<Template Project>>> from the wizard chooser. - - * The wizard has a drop down with a list of template projects. One of them is a "Simple Spring Batch Project". Select it and follow the wizard. - - * A project is created with all dependencies and a simple input/output job configuration. It can be run using a unit test, or on the command line (see instructions in the pom.xml). - -* Using the .Zip Distribution - -** With Maven and Eclipse - - * Download the "no-dependencies" version of the distribution and unzip to create a directory <<>>>. - - * Get the m2eclipse plugin (http://m2eclipse.sonatype.org/update) - (installed in STS out of the box). If you can't or don't want to - install this plugin, you can use the - {{{http://maven.apache.org/plugins/maven-eclipse-plugin/}Maven - Eclipse Plugin}} to create the classpath entries you need. - - * Open Eclipse and create a workspace as for the non-Mavenized version. - - * Import the samples and archetype projects from the samples sub-directory in the directory you just unpacked. - - * The project should build cleanly without having to fix the dependencies. If it doesn't, make sure you are online, and maybe try building on the command line first to make sure all the dependencies are downloaded. See the {{{./building.html}building instructions}} if you run into difficulty. - - (N.B. the "archetype" is not a real Maven archetype, just a template project that can be used as a starting point for a self-contained batch job. It is the same project that can be imported into STS using the Project Template wizard.) - -** With Maven on the Command Line - - * Download the distribution as above. - - * Then run Maven in the spring-batch-samples directory, e.g. - -+--- -$ cd spring-batch-samples -$ mvn test -... -+--- - -** With Eclipse and without Maven - - Similar instructions would apply to other IDEs. - - * Download the "no-dependencies" package and unzip to create a directory <<>>>. - - * Open Eclipse and make a workspace in the directory you just created. - - * Import the <<>> project from the samples directory. - - * Find all the compile scope and non-optional runtime jar files listed in the {{{./spring-batch-core/dependencies.html}core dependencies report}} and {{{./spring-batch-infrastructure/dependencies.html}infrastructure dependencies report}}, and import them into the project. - - * Force the workspace to build (e.g. Project -> Clean...) - - * Run the unit tests in your project under src/test/java. N.B. the FootbalJobFunctionTests takes quite a long time to run. - - You can get a pretty good idea about how to set up a job by examining the unit tests in the <<>> package (in <<>>) and the configuration in <<>>. - - To launch a job from the command line instead of a unit test use the <<>> method (see Javadocs included in that class). - -* Using Maven and Git - - * Check out the Spring Batch project from Git (instructions are available {{{./source-repository.html}here}}). - - * Run Maven from the command line in the samples directory. There are additional building instructions and suggestions about what to do if it goes wrong {{{./building.html}here}}. - -* Using Gradle (for Groovy programmers) - - * There is a Groovy project template with instructions available {{{http://robokaso.github.com/Groovy-Spring-Batch-Template/}here}} - -* Migrating to 2.2.x - - As part of the update to support non-identifying job parameters ({{{https://jira.spring.io/browse/BATCH-1412}BATCH-1412}}), the database schema for the job repository was updated. To migrate your existing job repository to the new one, you'll need to execute the appropriate migration script for your platform. This script will create the new BATCH_JOB_EXECUTION_PARAMS table and migrate the parameters from the old table to the new table. The script can be found in the <<>> package. - - diff --git a/src/site/apt/index.apt b/src/site/apt/index.apt deleted file mode 100644 index b3029a07a..000000000 --- a/src/site/apt/index.apt +++ /dev/null @@ -1,59 +0,0 @@ - ------ - Spring Batch - ------ - Dave Syer, Scott Wintermute, Michael Minella - ------ - March 2007, May 2007, March 2014 - -Introduction - - Many applications within the enterprise domain require bulk processing to perform business operations in mission critical environments. These business operations include automated, complex processing of large volumes of information that is most efficiently processed without user interaction. These operations typically include time based events (e.g. month-end calculations, notices or correspondence), periodic application of complex business rules processed repetitively across very large data sets (e.g. insurance benefit determination or rate adjustments), or the integration of information that is received from internal and external systems that typically requires formatting, validation and processing in a transactional manner into the system of record. Batch processing is used to process billions of transactions every day for enterprises. - - Spring Batch is a lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems. Spring Batch builds upon the productivity, POJO-based development approach, and general ease of use capabilities people have come to know from the Spring Framework, while making it easy for developers to access and leverage more advanced enterprise services when necessary. - - Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high performance batch jobs through optimization and partitioning techniques. Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information. - - Spring Batch is part of {{{http://spring.io/projects}Spring}}. For runtime concerns and a container for running a Job as a service see the {{{http://docs.spring.io/spring-batch-admin/}Spring Batch Admin}} project. - -* Spring Batch Architecture - - Spring Batch is designed with extensibility and a diverse group of end users in mind. The figure below shows a sketch of the layered architecture that supports the extensibility and ease of use for end-user developers. - -[images/ExecutionEnvironment.png] Spring Batch Architecture showing Infrastructure and Execution Layers. Potential execution strategy implementations support different platforms and end-user goals from the same blocks of business logic in the Application Layer. - - Spring Batch provides an Infrastructure layer in the form of low level tools. There is also a simple execution environment, using the infrastructure in its implementation. The execution environment provides robust features for traceability and management of the batch lifecycle. A key goal is that the management of the batch process (locating a job and its input, starting, scheduling, restarting, and finally processing to created results) should be as easy as possible for developers. - - The Infrastructure provides the ability to batch operations together, and to retry an piece of work if there is an exception. Both requirements have a transactional flavour, and similar concepts are relevant (propagation, synchronisation). They also both lend themselves to the template programming model common in Spring, c.f. <<>>, <<>>, <<>>. - - The Core module is the batch-focused domain and implementation. It provides a robust set of integrated features including job processing statistics, job launch and restart to enable the management of the full lifecycle of traditional batch processing. - - A number of sample jobs are packaged in a separate Samples module to more clearly articulate the usage and capabilities of the Core module. - - The runtime dependencies of infrastructure and core are shown in the figure below. - -[images/RuntimeDependencies.png] Spring Batch runtime dependencies, showing how a client application (as per the samples) can be built in terms of other modules. - -* Roadmap - - The current production release version is specified {{{./downloads.html}here}}, and links are also provided to the latest development work. - - The framework is oriented around application developers not needing to know any details of the framework - there are a few application developer interfaces that can be used for convenient construction of data processing pipelines, but apart from that we support as close to a POJO programming model as is practical. This is similar to the approach taken in Spring Core in the area of DAO implementation. - - Spring Batch version 2.2.x was targeted at Java 6 with no compromises made to support earlier versions of Java. Spring Batch 3.0 also targets Java 6, however it has been developed to support language features through Java 8. - - Standardization of batch processing in the java space has occurred via {{{https://jcp.org/en/jsr/detail?id=352}JSR-352}}. Spring was a major contributor to this JSR and has since implemented this specification in Spring Batch. - - Framework tools for scaling to multiple processes have been available since Spring Batch 2.0, however additional components that help facilitate multi-process scalability previously found in Spring Batch Admin have been moved into Spring Batch as part of the 3.0 release. - - Future work in Spring Batch will focus on simplification of it's use as well as research into new use cases including pipelining and big data. - -* Background - - While open source software projects and associated communities have focused greater attention on web-based and SOA messaging-based architecture frameworks, there has been a notable lack of focus on reusable architecture frameworks to accommodate Java-based batch processing needs, despite continued needs to handle such processing within enterprise IT environments. The lack of a standard, reusable batch architecture has resulted in the proliferation of many one-off, in-house solutions developed within client enterprise IT functions. - - SpringSource and Accenture are collaborating to change this. Accenture's hands-on industry and technical experience in implementing batch architectures, SpringSource's depth of technical experience, and Spring's proven programming model together mark a natural and powerful partnership to create high-quality, market relevant software aimed at filling an important gap in enterprise Java. Both companies are also currently working with a number of clients solving similar problems developing Spring-based batch architecture solutions. This has provided some useful additional detail and real-life constraints helping to ensure the solution can be applied to the real-world problems posed by clients. For these reasons and many more, SpringSource and Accenture have teamed to collaborate on the development of Spring Batch. - - Accenture is contributing previously proprietary batch processing architecture frameworks -- based upon decades worth of experience in building batch architectures with the last several generations of platforms (i.e., COBOL/Mainframe, C++/Unix, and now Java/anywhere) -- to the Spring Batch project along with committer resources to drive support, enhancements, and the future roadmap. - - The collaborative effort between Accenture and SpringSource aims to promote the standardization of software processing approaches, frameworks, and tools that can be consistently leveraged by enterprise users when creating batch applications. Companies and government agencies desiring to deliver standard, proven solutions to their enterprise IT environments will benefit from Spring Batch. - diff --git a/src/site/apt/migration/1.0-m2-m3.apt b/src/site/apt/migration/1.0-m2-m3.apt deleted file mode 100644 index 0e7766e65..000000000 --- a/src/site/apt/migration/1.0-m2-m3.apt +++ /dev/null @@ -1,67 +0,0 @@ - ------ - Spring Batch Upgrade - ------ - Robert Kasanicky - ------ - December 2007 - -Updating Spring Batch from 1.0-m2 to 1.0-m3 - - This is a description of what needed to be done to migrate the samples from m2 to the new m3 release. - - [Tip:] if you use SpringIDE, make sure it tracks all your configuration files, -so that errors are immediately visible. - -* VARIOUS - - * OutputSource interface has been renamed to ItemWriter, implementations have been renamed correspondingly -(e.g. FlatFileOutputSource is now FlatFileItemWriter). ItemWriter no longer extends ResourceLifecycle -(which declares methods open() and close). Often you don't need to call these methods at all, in case -you do you should implement InitializingBean and DisposableBean interfaces and declare the bean -in step scope. - - * Sql renamed to Jdbc (e.g. SqlInputSource -> JdbcInputSource). - - * Database input sources split into driving and cursor packages (cursor makes a single query and iterates -over the result set, driving query for keys and then make a new query for each key). - - * ExceptionHandler interface has been changed to handle single throwable instead of a collection of throwables -and it has become responsible for deciding about step completion. See javadoc for more details. - - * FlatFileInputSources now include FieldSet mapping logic - you can inject a FieldSetMapper -into the input source, so you no longer need to handle this in ItemProvider. Therefore -FieldSetInputSource interface and FlatFileItemProvider have been removed. Where FlatFileItemProvider -was used you can use the InputSourceItemProvider and inject the mapper into the input source. - - * Validation has been removed from input sources and moved upwards to ValidatingItemProvider. - - * XML related classes have been moved from io.stax package under io.file - - * Fixed-length tokenizer accept ranges property instead of array of lengths, e.g. "2,3" -(see javadoc for more details and fixedLengthImportJob.xml for example usage). - - -* CONTAINER CONFIGURATION - - * Use the value of JobConfiguration name property as the bean id. - - * Simplest approach to update is to use the simple-container-definition.xml, -data-source-context.xml (plus hibernate-context.xml) and batch.properties -from M3 samples and replace the post-processor bean in your job xml file with -"\" - - * JobLauncher has been moved from execution.bootstrap to execution.launch - - * JobExecutor facade has been removed, it's properties are now injected directly -into SimpleJobLauncher intead of the facade itself. - - * DefaultStepExecutorFactory is now SimpleStepExecutorFactory located in simple subpackage -and needs a reference to jobRepository instead of value for StepExecutor name. - - * ScheduledJobIdentifier has a new jobKey property replaces jobRun and jobStream. - - * SimpleStepConfiguration has been moved one package up (from execution.step.simple to execution.step). - - * Transaction manager class is specified in batch.properties - - diff --git a/src/site/apt/migration/1.0-m3-m4.apt b/src/site/apt/migration/1.0-m3-m4.apt deleted file mode 100644 index f8cf4a196..000000000 --- a/src/site/apt/migration/1.0-m3-m4.apt +++ /dev/null @@ -1,59 +0,0 @@ - ------ - Spring Batch Upgrade - ------ - Robert Kasanicky - ------ - February 2008 - -Updating Spring Batch jobs from 1.0.0.m3 to 1.0.0.m4 framework - - This is a description of what needed to be done to migrate the samples -from m3 to the m4 release. - - [Tip:] if you use SpringIDE, make sure it tracks all your configuration -files, so that errors are immediately visible. - -* JOB CONFIGURATION - - * ItemProviderTasklet and RestartableItemProviderTasklet have been replaced -with ItemOrientedTasklet - - * ItemProvider/ItemProcessor pair is now ItemReader/ItemWriter - - * InputSource and ItemProvider interfaces have been merged into ItemReader -(ItemReaders can be composite when desired) - - * OutputSource and ItemProcessor interfaces have been merged into ItemWriter -(ItemTransformerItemWriter and CompositeItemTransformer provide support for -item transformations before writing to output) - - * JobConfiguration and Step Configuration are now called simply Job and Step. There is no JobExecutor or StepExecutor. - -* CONTAINER CONFIGURATION - - * JobIdentifier is replaced by JobParameters - - * JobLauncher#run(Job, JobParameters) now returns JobExecution which has -methods stop() and isRunnig() (previously part of JobLauncher) - - * Hibernate repository (JobDao and StepDao) has been removed - - * JobExecutor and StepExecutor are no longer explicitly declared -(Job and Step execute themselves) - - -* VARIOUS - - * Remember to update the database schema - - * Several moves and package renames easily fixed by IDE refactoring support -('organize imports' in Eclipse) - - * FieldSet is now an interface with DefaultFieldSet as provided implementation - - * ResourceLifecycle and Restartable interfaces have been removed, ItemStream -now covers their responsibilities - - * StatisticsProvider interface has been superceded by ExecutionAttributesProvider - - * BatchTransationSynchronizationManager has been removed. Use the regular TransactionSynchronizationManager if you need to register a synchronization. diff --git a/src/site/apt/migration/1.0-m4-m5.apt b/src/site/apt/migration/1.0-m4-m5.apt deleted file mode 100644 index 901bf04c3..000000000 --- a/src/site/apt/migration/1.0-m4-m5.apt +++ /dev/null @@ -1,49 +0,0 @@ - ------ - Spring Batch Upgrade - ------ - Robert Kasanicky - ------ - March 2008 - -Updating Spring Batch jobs from 1.0.0.m4 to 1.0.0.m5 framework - - The following is a description of what is needed to migrate the samples from m4 to the m5 release. - -* JOB CONFIGURATION - - * Tasklet's role has changed - It is no longer called iteratively, but is now dedicated for tasks that are not natural to split into read-write phases (e.g. calling stored procedure or system command). Readers and writers are now typically injected into (ItemOriented)Step. See Tasklet and TaskletStep javadoc for more details. - - * Step scope removed - lifecycle of readers and writers explicitly handled by Step. They need to be registered for the lifecycle callbacks with the step. This is automatic if using one of the new step factory beans, but only for the directly injected reader and writer. Any indirect dependencies need to be registered separately (using the streams property of the factory bean). - - * When launching from command line there is one applicaton context for job rather than parent container and child job context. CommandLineJobRunner requires only one xml file location. It is recommended to use a new ApplicationContext per job execution for other use cases involving launching multiple jobs in a single VM. The JMX demo in the samples shows this in practice. - - * SimpleFlatFileItemReader and DefaultFlatFileItemReader merged into FlatFileItemReader - - * LineAggregator is now inverse to LineTokenizer - method signature changed to 'String aggregate(FieldSet)'. - - -* CONTAINER CONFIGURATION - - * Modularized repository daos - JobInstanceDao, JobExecutionDao and StepExecutionDao instead of JobDao and StepDao. - - * Step creation handled by factories. - - -* VARIOUS - - * ItemStream now has single 'open(ExecutionContext)' rather than 'open()' and 'restoreFrom(ExecutionContext)'. - - * ItemStream no longer has mark() and reset() methods - moved to ItemReader. ItemWriter uses more intuitive clear() and flush(). - - * Interceptors renamed to Listeners e.g. RepeatInterceptor is now RepeatListener. - - * StepContext merged into ExecutionContext (previously ExecutionAttributes). Single ExecutionContext is now shared between ItemStreams instead of separate contexts being composed before save and decomposed after load. ItemStreams now have names to distinguish context keys of multiple ItemStreams of the same class. - - * Domain-oriented listeners introduced - JobListener, StepListener, ChunkListener, ItemReadListener, ItemWriteListener. - - * StepInstance removed from domain model. - - * Database schema updated. - - * JobInstance identity is now given by Job and JobParameters pair - identical JobInstances with different IDs no longer allowed (see JobInstance javadoc for more details). - diff --git a/src/site/apt/migration/1.0-m5-rc1.apt b/src/site/apt/migration/1.0-m5-rc1.apt deleted file mode 100644 index 04cdd571b..000000000 --- a/src/site/apt/migration/1.0-m5-rc1.apt +++ /dev/null @@ -1,35 +0,0 @@ - ------ - Spring Batch Upgrade - ------ - Robert Kasanicky - ------ - March 2008 - -Updating Spring Batch jobs from 1.0.0.m5 to 1.0.0.rc1 framework - - The following is a description of what is needed to migrate the samples from m5 to the rc1 release. The changes to existing job configurations in samples are minimal. Simply replacing the old version of the base launcher configuration should suffice. - - -* CONTAINER CONFIGURATION - - * The basic execution environment for the samples was renamed from "simple-container-definition.xml" to "simple-job-launcher-context.xml". - - * DefaultStepFactoryBean has been removed, SimpleStepFactoryBean offers basic configuration options. - - * SkipLimitStepFactoryBean adds additional skip configuration for specific exception types. - - -* VARIOUS - - * Core and Execution modules merged to Core - - * Heavy package renaming and moving (resolved cyclic dependencies) - - * all StepListener methods pass the StepExecution as argument - - * all JobListener methods pass the JobExecution as argument - - * JobListener was enhanced with onError(..) and onInterrupt(..) methods - - * InfrastructureException replaced with UnexpectedJobExecutionException - diff --git a/src/site/apt/migration/1.0-rc1-final.apt b/src/site/apt/migration/1.0-rc1-final.apt deleted file mode 100644 index 2286ed3b8..000000000 --- a/src/site/apt/migration/1.0-rc1-final.apt +++ /dev/null @@ -1,26 +0,0 @@ - ------ - Spring Batch Upgrade - ------ - Robert Kasanicky - ------ - March 2008 - -Updating Spring Batch jobs from 1.0.0.rc1 to 1.0.0.final framework - - Migrating from rc1 to final release does not require configuration changes. Following is a list of notable imporovements and/or changes in behavior. - - * SimpleStepFactoryBean defaults to commit interval = 1 - - * SkipLimitStepFactoryBean accepts a list of fatal exceptions (java.lang.Error by default) that cause immediate step failure, regardless of skippable settings. - - * Skip and retry are no longer exclusive. - - * An exception on read does not cause transaction rollback if the exception is skippable. - - * Checked skippable exceptions are skipped correctly - - * FlatFileItemWriter buffers output and writes to file only on flush() i.e. at the end of chunk. - - * ExitStatusExceptionClassifier interface removed - SimpleExitStatusExceptionClassifier implements JobListener instead. - - * ExecutionContext is persisted for the first time before the processing of first chunk starts, so the scenario when job fails before first chunk is commited is no longer special. diff --git a/src/site/apt/migration/1.0.0-1.0.1.apt b/src/site/apt/migration/1.0.0-1.0.1.apt deleted file mode 100644 index a09b7efa4..000000000 --- a/src/site/apt/migration/1.0.0-1.0.1.apt +++ /dev/null @@ -1,49 +0,0 @@ -Changes in version 1.0.1 (2008-04-25) - -* Bug fixes (changes made, loosely ordered by importance) - - * StepExecutionListener#afterStep(..) is called only after successful processing, onErrorInStep(..) handles failures - - * Throwing exception in StepExecutionListener#afterStep(..) causes step to fail - - * StatefulRetryStepFactoryBean honors skip configuration (ignored it before) - - * More robust skip and retry logic with informative failures - - * JdbcCursorItemReader handles resets (rollbacks) correctly - - * JdbcCursorItemReader handles multiple restarts correctly - - * Long values mapped to JDBC Types.BIGINT instead of Types.INTEGER to avoid value truncating - - * StepExecutionResourceProxy now works correctly with FlatFileItemWriter - - * JobRepositoryBean applies table prefix consistently (including sequences) - - * HibernateCursorItemReader closes stateful session correctly - - * RetryTemplate rethrows Throwables that are neither Exception nor Error instead of ignoring - - * StepExecution#itemCount value was off by one - - * TaskletAdapter returns ExitStatus.FINISHED by default instead of ExitStatus.CONTINUABLE - - * JdbcCursorItemReader works with Derby under condition verifyCurorPosition=false - - * MySQL schema uses DATETIME instead of problematic TIMESTAMP - -* Improvements - - * Cleaned up javadocs and documentation - - * StepExecutionResourceProxy#toString delegates to the proxied Resource (once it is set) - - * More informative exception messages in SpringValidator (the invalid item is included) - - * ExecutionContext and JobParameters support default values - - * Oracle schema uses more appropriate datatypes - - * Subclasses of SimpleStepFactoryBean have access to ItemOrientedStep#chunkOperations property - - * Reusable tests for item readers, repository daos and step implementations (if you need to implement any of these) diff --git a/src/site/apt/migration/1.0.1-1.1.apt b/src/site/apt/migration/1.0.1-1.1.apt deleted file mode 100644 index d122a9bfd..000000000 --- a/src/site/apt/migration/1.0.1-1.1.apt +++ /dev/null @@ -1,42 +0,0 @@ -Spring Batch 1.1 Release Notes - -* Notable new features: - - * Job-level execution context (shared among all steps) - - * MultiResourceItemReader for reading multi-file input - - * SystemCommandTasklet for executing system commands - - * FlatFileItemWriter and StaxEventItemWriter support headers - - * Maven archetype - - * Modifiable transaction attributes for ItemOrientedStep - - * StepExecutionSimpleCompletionPolicy for pulling commit interval from JobParameters - - * MapJobRepositoryFactoryBean for easy setup of in-memory repository - - * StepExecution has persistent rollbackCount, readSkipCount and writeSkipCount - - * All ItemReader implementations default to returning null in the initial call to read if no data is found to process. NoWorkFoundListener can be used to fail a step if no work was done. (e.g. input was empty) - - * LineTokenizer implementations now properly enforce formatting. For example, a fixed length line must match the maximum line length defined in the provided ranges. - - * FlatFileItemWriter must be opened before it can be written to. However, open can be called multiple times before closing. - - * All ItemReader and ItemWriter implementations now default to saving state. (i.e. saveState=true by default) - -* Other - - * StatefulRetryStepFactoryBean is deprecated - use SkipLimitStepFactoryBean instead - - -* Upgrade instructions from 1.0.1 to 1.1 - - * update the database schema using the update script (or create a fresh schema) - note that 1.0.x jobs won't work with 1.1 schema - - * use the updated simple-job-launcher-context.xml (or remove TX advice for repository - it is applied automatically, and remove beans 'jobRegistry' and 'jobRegistryBeanPostProcessor') - - * jobs should run without modification diff --git a/src/site/apt/migration/1.1-1.1.1.apt b/src/site/apt/migration/1.1-1.1.1.apt deleted file mode 100644 index 13ded3977..000000000 --- a/src/site/apt/migration/1.1-1.1.1.apt +++ /dev/null @@ -1,27 +0,0 @@ -Spring Batch 1.1.1 Release Notes - -* Bugfixes: - - * FlatFileItemReader restart broken for non-default RecordSeparatorPolicy (record > 1 line) - - * JdbcCursorItemReader fails to restart after rollback on first chunk - - * Throwing an Exception from a SkipListener caused unpredictable behavior - - * StepExecution is saved before trying to save ExecutionContext - - * DefaultFieldSet should clone the tokens before exposing them in getValues() - - -* Improvements - - * Configurable RetryPolicy in SkipLimitStepFactoryBean - - -* Documentation updates - - * Updated 'Getting Started' page - - * Fixed missing images from the html reference documentation - - * Added description how to access JobExecution and StepExecution from Tasklets \ No newline at end of file diff --git a/src/site/apt/migration/1.1-2.0-m1.apt b/src/site/apt/migration/1.1-2.0-m1.apt deleted file mode 100644 index d8238e578..000000000 --- a/src/site/apt/migration/1.1-2.0-m1.apt +++ /dev/null @@ -1,16 +0,0 @@ -Spring Batch 2.0-m1 Release Notes - -* Bugfixes: - - * [BATCH-737] - JdbcCursorItemReader will spin through entire resultset if numberOfProcessRows=0 - * [BATCH-732] - FlatFileItemReader doesn't take "firstLineIsHeader" flag into account when restarting * [BATCH-735] - Getting Started page should be updated * [BATCH-734] - ItemReaders and ItemWriters using Resource(s) should check for file during ItemStream#open * [BATCH-778] - MapJobRepositoryFactoryBean shouldn't require transactionManager * [BATCH-693] - Refactor samples along domain contours * [BATCH-761] - StaxEventItemWriter writes extra end document tag with Woodstox 3.2.6 * [BATCH-765] - StepExecution should be saved on every commit - * [BATCH-757] - remove DelegatingItemWriter * [BATCH-766] - Insufficient error handling in case of a missing resource for a org.springframework.batch.item.xml.StaxEventItemWriter - * [BATCH-727] - Move all POMs in trunk to 2.0.0.CI-SNAPSHOT * [BATCH-744] - restart.count is always 0 in FlatFileItemWriter * [BATCH-741] - DefaultFieldSet should clone the tokens before exposing them in getValues() - -* Improvements - - * [BATCH-671] - Upgrade JobParameters and ExecutionContext for Java 5 * [BATCH-770] - Make ItemTransformer a first class citizen and rename as ItemProcessor * [BATCH-278] - Allow FixedLengthLineAggregator to be configured with different padding/alignment for specific columns * [BATCH-709] - Change all collections to use generics * [BATCH-581] - Add filter capability to item oriented paradigm * [BATCH-743] - ExportedJobLauncher should be able to stop running batches on an individual basis * [BATCH-230] - Recoverable and ItemProvider.recover() abstractions refactored into correct place in chunk-oriented framework * [BATCH-745] - strong typing in AggregateItemReader * [BATCH-544] - Configurable RetryPolicy in SkipLimitStepFactoryBean * [BATCH-354] - Create JPA ItemReader/Writer * [BATCH-758] - Generify ExceptionClassifier and ExceptionClassifierSupport * [BATCH-300] - Improve typesafety of ItemProvider/Processor paradigm * [BATCH-753] - Listener exception handling * [BATCH-274] - Support Callable * [BATCH-712] - Upgrade ItemReaders to use Parameterized types * [BATCH-711] - Upgrade ItemWriter and implementations to use parameterized types * [BATCH-756] - Upgrade JdbcExecutionContextDao to use enums * [BATCH-672] - Upgrade samples to Java 5.0 * [BATCH-710] - Upgrade unit tests to use Spring Test Java 5 features * [BATCH-518] - clean up the *Or* repository methods * [BATCH-662] - simplify FlatFileItemReader * [BATCH-728] - Add remove(key) method to ExecutionContext class * [BATCH-570] - Job.getSteps() does not need to be exposed in the interface * [BATCH-668] - JobRepository needs to distinguish between save and update of execution context - -* Documentation updates - - * [BATCH-768] - Update documentation for M1 * [BATCH-586] - Documentation for the walkthrough of samples * [BATCH-769] - Create documentation for JPA Reader * [BATCH-689] - Document how to access StepExecution and JobExecution in Tasklet \ No newline at end of file diff --git a/src/site/apt/migration/1.1.1-1.1.2.apt b/src/site/apt/migration/1.1.1-1.1.2.apt deleted file mode 100644 index 9d7e2ef82..000000000 --- a/src/site/apt/migration/1.1.1-1.1.2.apt +++ /dev/null @@ -1,16 +0,0 @@ -Spring Batch 1.1.2 Release Notes - -* Bugfixes: - - * STEP_EXECUTION table is now updated after every chunk - - * StaxEventItemWriter throws informative error for non-existing Resource, and only does it on open (so it will work with MultResourceItemReader) - - * In a multi-threaded step, the lock that is taken while the step executio nis being updated cannot be inadvertently released by another thread if it fails - - -* Improvements - - * StaxEventItemWriter#endDocument(..) can be overriden (allows users to fix problems with Woodstox end tag auto-insertions) - - * Javadoc included in the distribution diff --git a/src/site/apt/migration/1.1.2-1.1.3.apt b/src/site/apt/migration/1.1.2-1.1.3.apt deleted file mode 100644 index ab2134d73..000000000 --- a/src/site/apt/migration/1.1.2-1.1.3.apt +++ /dev/null @@ -1,56 +0,0 @@ -Release Notes - Spring Batch - Version 1.1.3 - - -* Bug Fixes - - * {{{http://jira.spring.io/browse/BATCH-725}BATCH-725}} - The description of DelegatingItemReader in Appendix A( List of ItemReaders) - - * {{{http://jira.spring.io/browse/BATCH-811}BATCH-811}} - StepExecutionResourceProxy should throw an exception if a job paramter key in the path isn't found - - * {{{http://jira.spring.io/browse/BATCH-812}BATCH-812}} - StepExecutionResourceProxy should use a different JobParametersConverter - - * {{{http://jira.spring.io/browse/BATCH-820}BATCH-820}} - Storing a Blob with JdbcExecutionContextDao in DB2 - - * {{{http://jira.spring.io/browse/BATCH-831}BATCH-831}} - id counter in MapJobInstanceDao should be declared static - - * {{{http://jira.spring.io/browse/BATCH-832}BATCH-832}} - DefaultTransactionAttribute is inappropriate for TaskletStep - - * {{{http://jira.spring.io/browse/BATCH-833}BATCH-833}} - TransactionAttributes swallows Exceptions - - * {{{http://jira.spring.io/browse/BATCH-838}BATCH-838}} - TimeoutTerminationPolicy does not terminate when eof is encountered - - * {{{http://jira.spring.io/browse/BATCH-839}BATCH-839}} - Reference doc reference deprecated code: 'StatefulRetryStepFactoryBean' - - * {{{http://jira.spring.io/browse/BATCH-847}BATCH-847}} - FaultTolerantChunkOrientedTasklet loses chunks when non-skippable exceptions thrown in read phase - - * {{{http://jira.spring.io/browse/BATCH-857}BATCH-857}} - map daos need to be truly transactional for correct restart - - * {{{http://jira.spring.io/browse/BATCH-866}BATCH-866}} - Reference manual has invalid references to org.springframework.batch.io.file package - - * {{{http://jira.spring.io/browse/BATCH-870}BATCH-870}} - Cannot add description to empty ExitStatus - - * {{{http://jira.spring.io/browse/BATCH-884}BATCH-884}} - SkipLimitStep does not fail if exception occurs - - * {{{http://jira.spring.io/browse/BATCH-892}BATCH-892}} - Thread visibility issues in repeat template - - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-802}BATCH-802}} - Incorrect metadata in fixed-length file example - - * {{{http://jira.spring.io/browse/BATCH-809}BATCH-809}} - fixedLenghtTokenizer problem with 1.1.2 - - * {{{http://jira.spring.io/browse/BATCH-828}BATCH-828}} - org.springframework.batch.item.file.MultiResourceItemReader should allow for no resources - - * {{{http://jira.spring.io/browse/BATCH-841}BATCH-841}} - insufficient logging in AbstractStep - - * {{{http://jira.spring.io/browse/BATCH-844}BATCH-844}} - Lacking of DAO's property setting in JobRepositoryFactoryBean - - * {{{http://jira.spring.io/browse/BATCH-881}BATCH-881}} - Update meta data schema to limit primary key values to Java Long sizes - - * {{{http://jira.spring.io/browse/BATCH-885}BATCH-885}} - Reference Doc Appendix B. Meta-Data Schema outdated - - -* Refactoring - - * {{{http://jira.spring.io/browse/BATCH-810}BATCH-810}} - Need to add DB2MainframeSequenceMaxValueIncrementer to DefaultDataFieldMaxValueIncrementerFactory diff --git a/src/site/apt/migration/2.0-highlights.apt b/src/site/apt/migration/2.0-highlights.apt deleted file mode 100644 index 7a4f2b89b..000000000 --- a/src/site/apt/migration/2.0-highlights.apt +++ /dev/null @@ -1,165 +0,0 @@ - ------ - Spring Batch 2.0 Highlights - ------ - Dave Syer - ------ - January 2009 - -Spring Batch 2.0 Highlights - - Here we outline the main themes of Spring Batch 2.0, and highlight the changes from 1.x. - -* Spring Batch 2.0 Themes - - The four main themes of the new release are - - * Java 5 (mandatory) and Spring 3.0 (optional) - - * Non-sequential execution - - * Scalability - - * Configuration: annotations and XML namespace - - so we'll cover each of those areas separately and describe what they mean and the impact of the changes on Spring Batch existing users. There is more detail below for features that are already implemented, which is mostly in the first category with some enabling features in other areas. - - There are no changes to the physical layout of the project in Spring Batch 2.0.0.M2 (same old downloads, same basic layout of Java packages). We have not removed any features, but we have taken the opportunity to revise a couple of APIs, and there are some minor changes for people updating projects from 1.x. Spring Batch is immature enough and we were adding some pretty big features, so we decided a major version change was a good opportunity to have a bit of a clean out. We don't expect anyone to have any difficulty upgrading, and if you are an existing user this page will help you to get the measure of the changes. - -* Java 5 - - As you may know, Spring 3.0 is going to be the first major release of Spring to target Java 5 exclusively (I'll leave it to Juergen and Arjen to clarify that in more detail). Now that Sun has put an "{{{http://java.dzone.com/articles/rip%E2%80%A6jdk-14}End of Service Life}}" stamp on the JDK 1.4 it seems appropriate, and there are some great new features on Spring 3.0 that we want to take advantage of. - - Since Spring 3.0 took a little longer to release than we had initially hoped we did some work in 2.0.0 to provide the late binding features independent of Spring 3.0. The 2.0.0 and 2.0.1 releases of Spring Batch actually do not work with Spring 3.0, but 2.0.2 should. The expressions in step scoped beans will use the weaker, but very similar, expression language from Spring Batch instead of the full Spring EL. In a future release of Spring Batch we will be able to fully support Spring EL in late binding expressions. - -** Type Safety - - Most of the work in the 2.0.0.M1 release of Spring Batch went into converting the existing code to Java 5, taking advantage of generics and parameterised types wherever we could. This gives users of the framework a much nicer programming experience, allowing compile time checks for type safety and ultimately reducing maintenance costs for projects using Spring Batch. For instance the in the <<>>, one of the central interfaces and user extension points in Spring Batch, we now have a typesafe <<>> method: - -+--- -public interface ItemReader { - S read(); -} -+--- - - A further point to note here is that the old (1.x) framework callbacks <<>> and <<>> have gone from this interface, making it more friendly to end users, and preventing misunderstanding about what the framework requires and when. The same concerns (or mark and reset) are now handled internally in the <<>> implementations that the framework provides. - -** Chunk-oriented Processing - - Similar changes, and one slightly more radical, have also occurred in the partner <<>> interface, used by the framework for writing data: - -+--- -public interface ItemWriter { - void write(List items); -} -+--- - - The old framework callbacks for <<>> and <<>> have gone from this interface too, and to compensate for that, the <<>> method has a new signature. The bottom line here is that we have moved to a chunk-oriented processing paradigm internally to the framework. This is actually much more natural in a batch framework than the old item-oriented approach because for performance reasons we often need to buffer and flush, and the old interface made that awkward for users. Now you can do all the batching you need inside the <<>> method. - -** Step Factory Bean Changes - - A side effect of the chunk-oriented approach to processing is a change in the step factory bean implementations. The old <<>> has been renamed to <<>>, and it can still be used for most common use cases as a replacement for the old factory bean. By default it creates a step implementation that buffers input items across rollbacks, so that the new <<>> and <<>> interfaces work properly with non-transactional input sources (like files). For input sources that re-present the items after a rollback, clients have to set a flag in the factory bean (<<>> is the name of the flag as of M2) - <<>> is the only relevant reader in the framework and not many projects use it so this isn't a big change. - -** Business Processing - - A related new feature is that there is a new kid on the block in the form of the <<>>: - -+---- -public interface ItemProcessor { - T process(S item); -} -+---- - - In 1.x the transformation between input items of type <<>> and output items of type <<>> had to be hidden inside one of the other participants (usually the <<>>). Now we have genericised this concern and placed it at the same level of importance in the framework as its siblings, <<>> and <<>>. Users of 1.x might recognise the traces of the old <<>> interface here, which has now been removed. - -** A More Useful Tasklet Interface - - Many people, looking at Spring Batch 1.x, have asked "what if my business logic is not reading and writing?" To answer this question more satisfactorily we have modified the <<>> interface. In Spring Batch 1.x it is fairly bland - little more than a <<>> in fact, but in 2.0 we have given it some more flexibility and slotted it more into the mainstream of the framework (e.g. the central chunk-oriented step implementation is now implemented as a <<>>). Here is the new interface: - -+---- -public interface Tasklet { - ExitStatus execute(StepContribution contribution, - AttributeAccessor attributes); -} -+---- - - The idea is that the tasklet can now contribute more back to the enclosing step, and this makes it a much more flexible platform for implementing business logic. The <<>> was already part of the 1.x API, but it wasn't very publicly exposed. Its role is to collect updates to the current <<>> without the programmer having to worry about concurrent modifications in another thread. This also tells us that the <<>> will be called repeatedly (instead of just once per step in the 1.x framework), and so it can be used to carry out a greater range of business processing tasks. The <<>> is a chunk-scoped bag of key-value pairs. The tasklet can use this to store intermediate results that will be preserved across a rollback. - -** Late Binding of Job and Step Attributes - - Late binding of <<>> and <<>> attributes to step components is possible in a very generic way. This is a much requested feature, and we have some workarounds for special cases in 1.x, like the <<>> for binding to a filename as an input parameter to a job. A more generic solution available in Spring Batch 2.0 is to allow those step attributes to be bound to arbitrary components, by defining them in an appropriate Spring scope, e.g. - -+---- - - - - - ... - - - ... - -+---- - - The item reader needs to be bound to a file name that is only available at runtime. To do this we have declared it as scope="step" and used the Spring EL binding pattern <<<#{...}>>> to bind in a job parameter. The same pattern works with step and job level execution context attributes (binding at step execution time). - - Step scoped beans are also a good solution to the old Spring Batch problem of how to keep your steps thread safe. If a step relies on a stateful component like a <<>>, then it only has to define that component as scope="step" and the framework creates a lazy initializing proxy for it, and it will be created as needed once per step execution. There's still noting wrong with creating a new <<>> for each job execution, which is the current best practice in 1.x for keeping threads from colliding across jobs. But now step scope gives you another option, and one that is probably easier for most Spring users to get to grips with. - -* Spring 3.0 - - Spring Batch 2.0 depends on Spring 2.5.6 (the lastest stable version at the time the development of Spring Batch was in progress). The plan is to add a Spring 3.0 dependence for Spring Batch 2.1 (while keeping the option of 2.5.6). This provides some useful new features in particular in the configuration of jobs and steps using late binding with Spring Expression Language (EL), which has the same syntax as we are using for late binding in Spring Batch 2.0, but has more features and is rather more flexible. - -* Non-sequential Execution - - In 1.x the model of a job was always as a linear sequence of steps, and if one step failed, then the job failed. Although many jobs still fit that pattern so it hasn't gone away, in 2.0 we are lifting that restriction by introducing some new features. These are planned for the M3 release so the implementation details might change, but the idea is to support three features: - - * Conditional execution: branching to a different step based on the <<>> of the last one. This includes the ability to branch on a FAILED status, which implies that a step failure is no longer fatal for a job. - - * Pause execution and wait for explicit instruction to proceed. This is useful for instance where there is a business rule that forces manual intervention to check the validity of business critical data. - - * Parallel execution of multiple steps. Where steps are independent the user can specify which branches can be executed in parallel. - - These features are available through the custom XML namespace described briefly below. - -* Scalability - - Spring Batch 1.x was always intended as a single VM, possibly multi-threaded model, but we built a lot of features into it that support parallel execution in multiple processes. Many projects have successfully implemented a scalable solution relying on the quality of service features of Spring Batch to ensure that processing only happens in the correct sequence. In 2.0 we expose those features more explicitly. There are two approaches to scalability, and we support both: remote chunking, and partitioning. - -** Remote Chunking - - Remote chunking is a technique for dividing up the work of a step without any explicit knowledge of the structure of the data. Any input source can be split up dynamically by reading it in a single process (as per normal in 1.x) and sending the items as a chunk to a remote worker process. The remote process implements a listener pattern, responding to the request, processing the data and sending an asynchronous reply. The transport for the request and reply has to be durable with guaranteed delivery and a single consumer, and those features are readily available with any JMS implementation. But Spring Batch is building the remote chunking feature on top of {{{http://projects.spring.io/spring-integration/}Spring Integration}}, so actually it is agnostic to the actual implementation of the message middleware. - -** Partitioning - - Partitioning is an alternative approach which in contrast depends on having some knowledge of the structure of the input data, like a range of primary keys, or the name of a file to process. The advantage of this model is that the processors of each element in a partition can act as if they are a single step in a normal Spring Batch job. They don't have to implement any special or new patterns, which makes them easy to configure and test. Partitioning in principle is more scalable than remote chunking because there is no serialization bottleneck arising from reading all the input data in one place. - - In Spring Batch 2.0 partitioning is supported by two interfaces: <<>> and <<>>. The <<>> is the one that knows about the execution fabric - it has to transmit requests to remote steps and collect the results using whatever grid or remoting technology is available. <<>> is an SPI, and we provide one implementation out of the box for local execution through a <<>>. This will be useful immediately to a number of projects we have seen where parallel processing of heavily IO bound tasks is required, since in those cases remote execution only complicates the deployment and doesn't necessarily help much with the performance. Other implementations will be specific to the execution fabric, e.g. one of the grid providers (IBM, Oracle, Terracotta, Appistry etc.), and we don't want to imply a preference for any of those over the others in Spring Batch. - - SpringSource is planning an Enterprise Batch product that will provide a full runtime solution for partitioning and remote chunking, as well as admin and scheduling concerns. - -* Configuration: annotations and XML namespace - - The idea behind using annotations to implement batch logic is by analogy with Spring @MVC. The net effect is that instead of having to implement and possibly register a bunch of interfaces (reader, writer, processor, listeners, etc.) you would just annotate a POJO and plug it into a step. There are method level annotations corresponding to the various interfaces, and parameter level annotations and factory methods corresponding to job, step and chunk level attributes (a bit like <<<@ModelParameter>>> and <<<@RequestParameter>>> in Spring @MVC. - - A XML namespace for Spring Batch makes configuration of common things even easier. For example, the <<>> we mentioned above has an XML configuration option, so a simple conditional execution might look like this: - -+---- - - - - - - - - - -+---- - - The first step ("gamesLoad") is followed immediately by "playerLoad", but if that fails, then we can go to an alternative step ("compensate") instead of finishing the job normally with the "summarize" step. The name= attribute of the <<<<step>>> element in the XML is a bean reference, so the implementation of <<>> is defined elsewhere (possibly through annotations). - -* Database Schema Changes - - There are a couple of tidying up tasks and extensions to the data model in the meta data schema. Unfortunately we cannot provide update scripts for moving from 1.x to 2.0 because the differences cannot be bridged using plain SQL. Upgrading an existing database would require the old schema to be dumped and re-loaded with a custom job. Our recommendation is to leave the old data alone and start fresh with 2.0: the benefit is that the new APIs definitely make it easier to navigate and interact with the meta data. For those of you who are new to Spring Batch, some of the key benefits of the framework are the quality of service features like restartability and idempotence (process business data once and only once). We implement these features through shared state in a relational database (in most use cases), and the definition of the data model in this database has changed slightly in 2.0. - - The main changes are to do with the storage of <<>>, which used to be centralised in one table, even though the context can be associated either with a <<>> or a <<>>. The new model will be more popular with DBAs because it makes the relationships more transparent in the DDL. We also started storing the context values in JSON, to make them easier to read and track for human users (the context for a single entity is all stored in one row in a table, instead of many). - - We have also added some more statistics for the counting and accounting of items executed and skipped, splitting out counts for total items read, processed and written at each stage. For steps (or tasklets) that do not split their execution into read, process, write, this is more comprehensive than is needed, but for the majority use case it is more appropriate than just storing an overall item count. diff --git a/src/site/apt/migration/2.0-m1-m2.apt b/src/site/apt/migration/2.0-m1-m2.apt deleted file mode 100644 index dd50527cf..000000000 --- a/src/site/apt/migration/2.0-m1-m2.apt +++ /dev/null @@ -1,76 +0,0 @@ -Spring Batch 2.0-m2 Release Notes - - - -* Bugfixes: - - * [BATCH-682] - Use SoftReference and/or expiry to store entries in RetryContextCache implementation(s) - * [BATCH-764] - Truncate flatfile in restart scenarios. - * [BATCH-776] - StaxEventItemWriter headers should not have to be the same type as the T that the writer is parameterised with - * [BATCH-782] - Synchronization issue in ItemOrientedStep if exception is throw in chunk processing - * [BATCH-790] - SQL error caused by changes to JdbcExecutionContextDao - * [BATCH-795] - JdbcJobExecutionDao output sorting - * [BATCH-807] - Serialization bug in JobExecution - * [BATCH-812] - StepExecutionResourceProxy should use a different JobParametersConverter - * [BATCH-813] - SingleColumnJdbcKeyGeneratorIntegrationTests fails in Eclipse - * [BATCH-814] - JobRepository should not require Step or Job (only their names) - * [BATCH-822] - New WRITE_COUNT should count items instead of chunks - * [BATCH-830] - DelegatingItemReader should be removed - * [BATCH-831] - id counter in MapJobInstanceDao should be declared static - * [BATCH-832] - DefaultTransactionAttribute is inappropriate for TaskletStep - * [BATCH-833] - TransactionAttributes swallows Exceptions - * [BATCH-835] - sql error "column ambiguously defined" in JdbcJobInstanceDao - * [BATCH-838] - TimeoutTerminationPolicy does not terminate when eof is encountered - * [BATCH-839] - Reference doc reference deprecated code: 'StatefulRetryStepFactoryBean' - * [BATCH-843] - FlatFileItemWriter handling of failure in LineAggregator - * [BATCH-847] - FaultTolerantChunkOrientedTasklet loses chunks when non-skippable exceptions thrown in read phase - * [BATCH-856] - JobExecution status isn't being updated when Step fails. - * [BATCH-865] - CompositeItemProcessor should handle null properly - -* Improvements - - * [BATCH-401] - aspect-oriented handling of job interruption logic - * [BATCH-453] - Killed batches cannot be restarted - * [BATCH-592] - RFC: buffer read items in ItemHandler instead of ItemReader - * [BATCH-640] - FieldSetMapper.mapLine() should contain the line number - * [BATCH-719] - API should provide access to original input line in flat file outside of error scenario - * [BATCH-755] - Include Javadocs in distribution - * [BATCH-762] - Change ExecutionContext storage strategy - * [BATCH-763] - Create callback for header and footer writing in xml and flat files - * [BATCH-772] - Upgrade CommandLineJobRunner to use args4j - * [BATCH-775] - Throw exception if ExecutionContext is modified during processing. - * [BATCH-779] - RFC: make FieldSetMapper and LineAggregator extend ItemProcessor - * [BATCH-785] - Fix Parallel Sample to use a batch update for process indicator - * [BATCH-792] - Automatically detect database type in JobRepositoryFactoryBean - * [BATCH-796] - typos in javadoc @links and comments - * [BATCH-802] - Incorrect metadata in fixed-length file example - * [BATCH-825] - Modify JobLauncher contract to not throw exception on job failure. - * [BATCH-826] - Create callback for header and footer reading in xml and flat files - * [BATCH-828] - org.springframework.batch.item.file.MultiResourceItemReader should allow for no resources - * [BATCH-841] - insufficient logging in AbstractStep - * [BATCH-844] - Lacking of DAO's property setting in JobRepositoryFactoryBean - * [BATCH-863] - introduce LineMapper interface to encapsulate string-to-item mapping - * [BATCH-864] - rename SkipLimitStepFactoryBean - * [BATCH-774] - Split item count into read/write/filter - * [BATCH-829] - add persistent processSkipCount to StepExecution - * [BATCH-810] - Need to add DB2MainframeSequenceMaxValueIncrementer to DefaultDataFieldMaxValueIncrementerFactory - * [BATCH-8] - Determine approach for handling file creation/update in restart scenarios - * [BATCH-220] - Chunk-oriented approach to processing - * [BATCH-575] - FlatFileItemReader default charset should mimic java's default charset behavior - * [BATCH-675] - API Analysis - * [BATCH-759] - ItemReader refactoring - * [BATCH-773] - Refactor and extend ExportedJobLauncher to JobOperator - * [BATCH-806] - Resurrect ResourceLineReader - * [BATCH-821] - remove EventSerializer/Deserializer abstractions and use Marshaller/Unmarshaller directly - * [BATCH-827] - Create Sample job for reading and writing headers and footers - * [BATCH-845] - integration tests for database autodetection - - - -* Documentation updates - - * [BATCH-767] - Update documentation for M2 - * [BATCH-823] - Confusing explanation - * [BATCH-718] - Add section on FlatFileItemReader error handling - * [BATCH-784] - Refactor testing chapter to reflect Spring Testing framework changes. - * [BATCH-850] - Create documentation for JdbcPagingItemReader and related classes diff --git a/src/site/apt/migration/2.0-m2-m3.apt b/src/site/apt/migration/2.0-m2-m3.apt deleted file mode 100644 index dcf8a35b8..000000000 --- a/src/site/apt/migration/2.0-m2-m3.apt +++ /dev/null @@ -1 +0,0 @@ -Spring Batch 2.0-m3 Release Notes * Bug * {{{http://jira.spring.io/browse/BATCH-837}BATCH-837}} - BIGINT datatype is not in Sybase but schema-sybase.sql is using it * {{{http://jira.spring.io/browse/BATCH-853}BATCH-853}} - broken transactional item processing * {{{http://jira.spring.io/browse/BATCH-857}BATCH-857}} - map daos need to be truly transactional for correct restart * {{{http://jira.spring.io/browse/BATCH-887}BATCH-887}} - onSkipInProcess called multiple times for same item using FaultTolerantChunkOrientedTasklet * {{{http://jira.spring.io/browse/BATCH-889}BATCH-889}} - SkipLimitStepFactoryBean should be FaultTolerantStepFactoryBean * {{{http://jira.spring.io/browse/BATCH-892}BATCH-892}} - Thread visibility issues in repeat template * {{{http://jira.spring.io/browse/BATCH-895}BATCH-895}} - Fix XML schema so that only top-level elements are allowed at top level (i.e. job). * {{{http://jira.spring.io/browse/BATCH-897}BATCH-897}} - Version is not rehydrated from database in JobInstance or JobExecution * {{{http://jira.spring.io/browse/BATCH-912}BATCH-912}} - Thread safety issue in JobRegistryBackgroundJobRunner * {{{http://jira.spring.io/browse/BATCH-917}BATCH-917}} - Concurrent modification of execution context in tasklet step * {{{http://jira.spring.io/browse/BATCH-921}BATCH-921}} - ExecutionContext keys are not unique enough in partition components * {{{http://jira.spring.io/browse/BATCH-925}BATCH-925}} - StaxEventItemWriter doesn't reset restart flag on close * {{{http://jira.spring.io/browse/BATCH-926}BATCH-926}} - vague skip limit for concurrent chunks * {{{http://jira.spring.io/browse/BATCH-931}BATCH-931}} - Write failures don't fail immediately. * {{{http://jira.spring.io/browse/BATCH-939}BATCH-939}} - Make step scope work with aop-auto-proxy * Improvement * {{{http://jira.spring.io/browse/BATCH-21}BATCH-21}} - OutputResource abstraction for file / stream output * {{{http://jira.spring.io/browse/BATCH-63}BATCH-63}} - Custom namespace for Job and related (Step, and maybe some *Reader/Writer) * {{{http://jira.spring.io/browse/BATCH-282}BATCH-282}} - Make input parameters easier to access from ItemReaders, etc. * {{{http://jira.spring.io/browse/BATCH-341}BATCH-341}} - Parameter generation strategy * {{{http://jira.spring.io/browse/BATCH-783}BATCH-783}} - No logging for item oriented step in case of exception occured in chunk processing * {{{http://jira.spring.io/browse/BATCH-797}BATCH-797}} - Refactor Map daos into another repository implementation. * {{{http://jira.spring.io/browse/BATCH-809}BATCH-809}} - fixedLenghtTokenizer problem with 1.1.2 * {{{http://jira.spring.io/browse/BATCH-848}BATCH-848}} - Determine best way tto support a paging iBATIS reader * {{{http://jira.spring.io/browse/BATCH-869}BATCH-869}} - End Time of a step or a job always null when read in a StepExecutionListener or a JobExecutionListener * {{{http://jira.spring.io/browse/BATCH-872}BATCH-872}} - RFC: Should FileWriterCallback have two methods, one for headers and one for footers? * {{{http://jira.spring.io/browse/BATCH-878}BATCH-878}} - AbstractMethodInvokingDelegator is not abstract * {{{http://jira.spring.io/browse/BATCH-881}BATCH-881}} - Update meta data schema to limit primary key values to Java Long sizes * {{{http://jira.spring.io/browse/BATCH-886}BATCH-886}} - RFC: consolidate JobInstance launching logic * {{{http://jira.spring.io/browse/BATCH-888}BATCH-888}} - skip listeners should be called when chunk is about to commit * {{{http://jira.spring.io/browse/BATCH-894}BATCH-894}} - RFC: move ExitStatus up into Core? * {{{http://jira.spring.io/browse/BATCH-896}BATCH-896}} - "DRY" FaultTolerantTasklet implementations * {{{http://jira.spring.io/browse/BATCH-900}BATCH-900}} - Retreive null values from the ExecutionContext * {{{http://jira.spring.io/browse/BATCH-907}BATCH-907}} - Integer support in ExecutionContext * {{{http://jira.spring.io/browse/BATCH-913}BATCH-913}} - Remove the JdkConcurrent* special classes * {{{http://jira.spring.io/browse/BATCH-930}BATCH-930}} - rename ItemSkipPolicy * {{{http://jira.spring.io/browse/BATCH-938}BATCH-938}} - Clean up DelimitedLineAggregator implementation * New Feature * {{{http://jira.spring.io/browse/BATCH-34}BATCH-34}} - Support for multiple I/O files in a single jobRun for a particular scheduleDate. * {{{http://jira.spring.io/browse/BATCH-679}BATCH-679}} - Non-sequential execution * {{{http://jira.spring.io/browse/BATCH-808}BATCH-808}} - Provide named parameter support to JdbcCursorItemReader * {{{http://jira.spring.io/browse/BATCH-874}BATCH-874}} - Annotation support * {{{http://jira.spring.io/browse/BATCH-903}BATCH-903}} - Create test project * {{{http://jira.spring.io/browse/BATCH-910}BATCH-910}} - Create a sample job for JobParametersIncrementer * {{{http://jira.spring.io/browse/BATCH-927}BATCH-927}} - Add JobParametersIncrementer to job namespace element * {{{http://jira.spring.io/browse/BATCH-932}BATCH-932}} - Add reflection-based Field Extractor * Refactoring * {{{http://jira.spring.io/browse/BATCH-911}BATCH-911}} - Consolidate Samples * Task * {{{http://jira.spring.io/browse/BATCH-624}BATCH-624}} - Create contribution page * {{{http://jira.spring.io/browse/BATCH-673}BATCH-673}} - Add new Java 5.0 features * {{{http://jira.spring.io/browse/BATCH-798}BATCH-798}} - Tidy up chunk processing and retry * {{{http://jira.spring.io/browse/BATCH-871}BATCH-871}} - Create FactoryBean for FlatFileItemReader * {{{http://jira.spring.io/browse/BATCH-893}BATCH-893}} - Remove the HibernateAwareItemWriter? * {{{http://jira.spring.io/browse/BATCH-904}BATCH-904}} - Create a sample job for non sequential execution. * {{{http://jira.spring.io/browse/BATCH-916}BATCH-916}} - JobOperator#startNewInstance should inspect last execution status * {{{http://jira.spring.io/browse/BATCH-922}BATCH-922}} - Why is there always one more commit than seems necessary? * Sub-task * {{{http://jira.spring.io/browse/BATCH-264}BATCH-264}} - Dependencies among jobs * {{{http://jira.spring.io/browse/BATCH-676}BATCH-676}} - Create sample job for 'non sequential step execution' * {{{http://jira.spring.io/browse/BATCH-726}BATCH-726}} - Pass a resource pattern to MultiResourceItemReader as a JobParameter * {{{http://jira.spring.io/browse/BATCH-733}BATCH-733}} - Upgrade StepExecutionResourceProxy to be able to use values from job execution context. * {{{http://jira.spring.io/browse/BATCH-801}BATCH-801}} - Add support for passing parameters from execution context * {{{http://jira.spring.io/browse/BATCH-816}BATCH-816}} - Make sure all dependencies are part of the Enterprise Repository * {{{http://jira.spring.io/browse/BATCH-817}BATCH-817}} - Change project names to correspond with bundle names * {{{http://jira.spring.io/browse/BATCH-858}BATCH-858}} - Pause / resume of Job * {{{http://jira.spring.io/browse/BATCH-875}BATCH-875}} - Pull jobRepository.save() out of Step implementations and put it in the driving Job * {{{http://jira.spring.io/browse/BATCH-879}BATCH-879}} - Decision states: not a regular step, just a volatile decision based on information in the JobExecution. * {{{http://jira.spring.io/browse/BATCH-880}BATCH-880}} - Suspend after step and wait for user input * {{{http://jira.spring.io/browse/BATCH-890}BATCH-890}} - Stop transition in XML namespace * {{{http://jira.spring.io/browse/BATCH-891}BATCH-891}} - Create Annotations * {{{http://jira.spring.io/browse/BATCH-905}BATCH-905}} - MultiResourceItemReader should be more dynamic in nature \ No newline at end of file diff --git a/src/site/apt/migration/2.0-m3-m4.apt b/src/site/apt/migration/2.0-m3-m4.apt deleted file mode 100644 index fda63a6d7..000000000 --- a/src/site/apt/migration/2.0-m3-m4.apt +++ /dev/null @@ -1,171 +0,0 @@ -Spring Batch 2.0.0.M4 Release Notes - -* Bug - - - * {{{http://jira.spring.io/browse/BATCH-923}BATCH-923}} - Missing dependency / repository breaks build on fresh checkout - - * {{{http://jira.spring.io/browse/BATCH-946}BATCH-946}} - NullPointerException in MapStepExecutionDao.getStepExecutions - - * {{{http://jira.spring.io/browse/BATCH-948}BATCH-948}} - MapJobInstanceDao.getLastJobInstances ignores jobName parameter - - * {{{http://jira.spring.io/browse/BATCH-950}BATCH-950}} - Exception during rollback hides root cause - - * {{{http://jira.spring.io/browse/BATCH-951}BATCH-951}} - MapJobInstanceDao.getLastJobInstances doesn't return the last job instance - - * {{{http://jira.spring.io/browse/BATCH-952}BATCH-952}} - StagingItemReader is not restartable - - * {{{http://jira.spring.io/browse/BATCH-954}BATCH-954}} - Failure on job stop - - * {{{http://jira.spring.io/browse/BATCH-957}BATCH-957}} - Optional dependencies included by default with new m3 pom - - * {{{http://jira.spring.io/browse/BATCH-959}BATCH-959}} - Get rid of compiler warnings in samples - - * {{{http://jira.spring.io/browse/BATCH-960}BATCH-960}} - Redundant test cases in samples? - - * {{{http://jira.spring.io/browse/BATCH-963}BATCH-963}} - ExecutionContext modifications in ItemStream.close(ExecutionContext) are not persisted - - * {{{http://jira.spring.io/browse/BATCH-969}BATCH-969}} - FlatFileItemWriters interference in CompositeItemWriter - - * {{{http://jira.spring.io/browse/BATCH-979}BATCH-979}} - Insert Apache license header in Java sources (where missing) - - * {{{http://jira.spring.io/browse/BATCH-991}BATCH-991}} - Getting PSQLException: ERROR: column "serialized_context" is of type bytea but expression is of type oid - - * {{{http://jira.spring.io/browse/BATCH-994}BATCH-994}} - BackOffPolicy is not applied for exceptions that cause rollback - - * {{{http://jira.spring.io/browse/BATCH-995}BATCH-995}} - unclear retry configuration in FaultTolerantStepFactoryBean - - * {{{http://jira.spring.io/browse/BATCH-996}BATCH-996}} - use default retryLimit == 1 (not 0) in *StepFactoryBean - - * {{{http://jira.spring.io/browse/BATCH-997}BATCH-997}} - EXIT_CODE and EXIT_MESSAGE out of synch for step - - * {{{http://jira.spring.io/browse/BATCH-998}BATCH-998}} - PDF of Reference Documentation does not contain images of figures - - * {{{http://jira.spring.io/browse/BATCH-999}BATCH-999}} - JobExecution ExecutionContext should not be persisted by Step? - - * {{{http://jira.spring.io/browse/BATCH-1001}BATCH-1001}} - Make jobs restartable by default - - * {{{http://jira.spring.io/browse/BATCH-1002}BATCH-1002}} - Default behavior for a Job should be failure if a step fails - - * {{{http://jira.spring.io/browse/BATCH-1003}BATCH-1003}} - spring-batch-2.0.xsd should not allow "listeners" element on "tasklet" - - * {{{http://jira.spring.io/browse/BATCH-1004}BATCH-1004}} - Using namespace to define a step does not store step name - - * {{{http://jira.spring.io/browse/BATCH-1005}BATCH-1005}} - startLimit and allowStartIfComplete cannot be set in the namespace - - * {{{http://jira.spring.io/browse/BATCH-1006}BATCH-1006}} - Namespace does not allow for variables (ie, ${varname}) - - * {{{http://jira.spring.io/browse/BATCH-1007}BATCH-1007}} - JobRepository default is inconsistent between job and step - - * {{{http://jira.spring.io/browse/BATCH-1021}BATCH-1021}} - AssertFile.assertFileEquals(File,File) parameters in the wrong order - - * {{{http://jira.spring.io/browse/BATCH-1031}BATCH-1031}} - FlatFileItemReader should identify missing resource in warning - - -* Improvement - - - * {{{http://jira.spring.io/browse/BATCH-883}BATCH-883}} - Document JobOperator.start - - * {{{http://jira.spring.io/browse/BATCH-919}BATCH-919}} - Clean up FaultTolerant* - - * {{{http://jira.spring.io/browse/BATCH-945}BATCH-945}} - Add support for step and job name in late binding - - * {{{http://jira.spring.io/browse/BATCH-964}BATCH-964}} - Add fetchSize property to JdbcPagingItemReader - - * {{{http://jira.spring.io/browse/BATCH-967}BATCH-967}} - DRY cleanup of StepParser - - * {{{http://jira.spring.io/browse/BATCH-968}BATCH-968}} - Refactor step/simple-task/item-task elements in the core namespace - - * {{{http://jira.spring.io/browse/BATCH-970}BATCH-970}} - JdbcCursorItemReader executes outside of main transaction - - * {{{http://jira.spring.io/browse/BATCH-974}BATCH-974}} - Change Tasklet interface to use StepContext rather than AttributeAccessor - - * {{{http://jira.spring.io/browse/BATCH-985}BATCH-985}} - (Skiplistener) improve doumentation and/or provide sample for saving skipped lines - - * {{{http://jira.spring.io/browse/BATCH-988}BATCH-988}} - MethodInvokingTaskletAdapter (via AbstractMethodInvokingDelegator) only allows specification of targetObject's declared methods - - * {{{http://jira.spring.io/browse/BATCH-993}BATCH-993}} - Slightly confusing use of *Dao in sample configuration in documentation, where *ItemWriter would be clearer - - * {{{http://jira.spring.io/browse/BATCH-1009}BATCH-1009}} - Automatically register ItemReadListener, ItemWriteListener and ItemProcessListener - - * {{{http://jira.spring.io/browse/BATCH-1015}BATCH-1015}} - ItemListenerSupport should implement ItemProcessListener - - * {{{http://jira.spring.io/browse/BATCH-1020}BATCH-1020}} - Create Loop Flow Sample - - * {{{http://jira.spring.io/browse/BATCH-1024}BATCH-1024}} - FlowJob's start state should be the first state listed in the config - - * {{{http://jira.spring.io/browse/BATCH-1032}BATCH-1032}} - Modify AbstractJobTests in test project to be able to launch FlowJob steps individually - - -* New Feature - - - * {{{http://jira.spring.io/browse/BATCH-677}BATCH-677}} - Partitioning enablement (SPI). - - * {{{http://jira.spring.io/browse/BATCH-941}BATCH-941}} - Create a sample job to highlight late binding. - - * {{{http://jira.spring.io/browse/BATCH-958}BATCH-958}} - Batch Ibatis Update Item Writer - - * {{{http://jira.spring.io/browse/BATCH-965}BATCH-965}} - Create non-delegating ItemWriters for JPA and Hibernate - - * {{{http://jira.spring.io/browse/BATCH-980}BATCH-980}} - Add SystemPropertyInitializer - - * {{{http://jira.spring.io/browse/BATCH-986}BATCH-986}} - Provide factory bean for SqlPagingQueryProvider - - * {{{http://jira.spring.io/browse/BATCH-987}BATCH-987}} - Create JobRepositoryTestUtils - - * {{{http://jira.spring.io/browse/BATCH-989}BATCH-989}} - Add support for named queries on HibernateCursorItemReader - - * {{{http://jira.spring.io/browse/BATCH-1016}BATCH-1016}} - Create listener to promote items from Step ExecutionContext to Job ExecutionContext - - * {{{http://jira.spring.io/browse/BATCH-1033}BATCH-1033}} - Create a PrefixMatchingCompositeLineMapper - - -* Refactoring - - - * {{{http://jira.spring.io/browse/BATCH-956}BATCH-956}} - Remove pause and wait functionality - - * {{{http://jira.spring.io/browse/BATCH-962}BATCH-962}} - refactor TaskletStep's exception handling for better clarity - - * {{{http://jira.spring.io/browse/BATCH-982}BATCH-982}} - Update all samples to use batch namespace - - * {{{http://jira.spring.io/browse/BATCH-983}BATCH-983}} - Remove StepExecutionResourceProxy in favor of late-binding - - * {{{http://jira.spring.io/browse/BATCH-1012}BATCH-1012}} - BatchListenerFactoryHelper: two if-statements, identical conditions - - * {{{http://jira.spring.io/browse/BATCH-1019}BATCH-1019}} - Create one sample without the namespace - - * {{{http://jira.spring.io/browse/BATCH-1025}BATCH-1025}} - Move PatternMatcher to infrastructure project - - * {{{http://jira.spring.io/browse/BATCH-1026}BATCH-1026}} - Rename ExitStatus.FINISHED to ExitStatus.COMPLETED - - * {{{http://jira.spring.io/browse/BATCH-1045}BATCH-1045}} - Move DataSourceInitializer to the test project's "main" folder - - -* Task - - - * {{{http://jira.spring.io/browse/BATCH-674}BATCH-674}} - Upgrade reference documentation - - * {{{http://jira.spring.io/browse/BATCH-961}BATCH-961}} - integration tests for JobOperator - - * {{{http://jira.spring.io/browse/BATCH-971}BATCH-971}} - add database writers to iosample - - * {{{http://jira.spring.io/browse/BATCH-1035}BATCH-1035}} - Add Late Binding to Docs - - -* Sub-task - - - * {{{http://jira.spring.io/browse/BATCH-53}BATCH-53}} - Aggregation of execution context when partitioning - - * {{{http://jira.spring.io/browse/BATCH-234}BATCH-234}} - Revise documentation to reflect chunk-oriented approach - - * {{{http://jira.spring.io/browse/BATCH-607}BATCH-607}} - FlatFileItemWriter section needs additional details - - * {{{http://jira.spring.io/browse/BATCH-730}BATCH-730}} - HibernateCursorItemReader Parameters - - * {{{http://jira.spring.io/browse/BATCH-920}BATCH-920}} - ChunkContext in StepContextRepeatCallback is unused - diff --git a/src/site/apt/migration/2.0-m4-rc1.apt b/src/site/apt/migration/2.0-m4-rc1.apt deleted file mode 100644 index 7d028e20e..000000000 --- a/src/site/apt/migration/2.0-m4-rc1.apt +++ /dev/null @@ -1,135 +0,0 @@ -Spring Batch 2.0.0.RC1 Release Notes - -* Bug - - - * {{{http://jira.spring.io/browse/BATCH-1089}BATCH-1089}} - Getting Started page should be updated - - * {{{http://jira.spring.io/browse/BATCH-1088}BATCH-1088}} - NamespaceHandler no handle all XML tags - - * {{{http://jira.spring.io/browse/BATCH-1087}BATCH-1087}} - ClassPathXmlJobRegistry does not accept patterns for resources - - * {{{http://jira.spring.io/browse/BATCH-1086}BATCH-1086}} - JdbcJobExecutionDao.getRunningJobExecutions() ignores jobName - - * {{{http://jira.spring.io/browse/BATCH-1085}BATCH-1085}} - Should adding next entities mean that the next attribute cannot be used? - - * {{{http://jira.spring.io/browse/BATCH-1084}BATCH-1084}} - Change "status" attribute of and to "exit-code" - - * {{{http://jira.spring.io/browse/BATCH-1083}BATCH-1083}} - Use RowMapper instead of ParameterizedRowMapper for public API - - * {{{http://jira.spring.io/browse/BATCH-1082}BATCH-1082}} - If file reader is lenient about resource existing on startup, it should also check when it is closed - - * {{{http://jira.spring.io/browse/BATCH-1081}BATCH-1081}} - Add task-executor= to - - * {{{http://jira.spring.io/browse/BATCH-1080}BATCH-1080}} - make a top-level element - - * {{{http://jira.spring.io/browse/BATCH-1078}BATCH-1078}} - Maven Build - ClassNotFoundException: com.springsource.util.math.Sets - - * {{{http://jira.spring.io/browse/BATCH-1077}BATCH-1077}} - Update docs to reflect changes in statuses - - * {{{http://jira.spring.io/browse/Update}Update}} - docs to reflect changes in statuses - - * {{{http://jira.spring.io/browse/BATCH-1076}BATCH-1076}} - Add a test case to show how a can restart on the step it failed on - - * {{{http://jira.spring.io/browse/BATCH-1075}BATCH-1075}} - allow-start-if-complete and start-limit should be on , not - - * {{{http://jira.spring.io/browse/BATCH-1073}BATCH-1073}} - on element, "listeners" must be disallowed when "ref" attribute is specified - - * {{{http://jira.spring.io/browse/BATCH-1071}BATCH-1071}} - JobInterruptedException needs to be on the fatal list - - * {{{http://jira.spring.io/browse/BATCH-1070}BATCH-1070}} - Add 'strict' property to BeanWrapperFieldSetMapper to allow suppression of errors - - * {{{http://jira.spring.io/browse/BATCH-1069}BATCH-1069}} - Update docs to show top-level element - - * {{{http://jira.spring.io/browse/BATCH-1068}BATCH-1068}} - Update samples to use top-level element - - * {{{http://jira.spring.io/browse/BATCH-1067}BATCH-1067}} - Problems with the way 'split' element handles EndStates - - * {{{http://jira.spring.io/browse/BATCH-1066}BATCH-1066}} - Modify namespace so that if "next" attribute is used, then no transition elements will be allowed. - - * {{{http://jira.spring.io/browse/BATCH-1064}BATCH-1064}} - Namespace end transition names don't match their corresponding statuses - - * {{{http://jira.spring.io/browse/BATCH-1063}BATCH-1063}} - Fix image sizes - - * {{{http://jira.spring.io/browse/BATCH-1062}BATCH-1062}} - Add namespace declaration information to docs - - * {{{http://jira.spring.io/browse/BATCH-1061}BATCH-1061}} - FlowJob.getLastStepExecution() puts arguments into isLater() in the wrong order - - * {{{http://jira.spring.io/browse/BATCH-1059}BATCH-1059}} - BATCH_JOB_INSTANCE.JOB_KEY ignores Date milliseconds - - * {{{http://jira.spring.io/browse/BATCH-1057}BATCH-1057}} - Residual from 1.x left over in AbstractItemWriter - - * {{{http://jira.spring.io/browse/BATCH-1056}BATCH-1056}} - Proofread documentation - - * {{{http://jira.spring.io/browse/BATCH-1055}BATCH-1055}} - Add section on filtering to docs - - * {{{http://jira.spring.io/browse/BATCH-1054}BATCH-1054}} - Maven Build - incompatible bundle manifest version - - * {{{http://jira.spring.io/browse/BATCH-1053}BATCH-1053}} - Add getStep(String) to Job interface - - * {{{http://jira.spring.io/browse/BATCH-1052}BATCH-1052}} - Write Common Pattern section about SystemCommandTasklet - - * {{{http://jira.spring.io/browse/BATCH-1051}BATCH-1051}} - Write Common Pattern section about multi-line records - - * {{{http://jira.spring.io/browse/BATCH-1050}BATCH-1050}} - SimpleJobExplorer doesn't retrieve StepExecutions of running JobExecutions using MapStepExecutionDao - - * {{{http://jira.spring.io/browse/BATCH-1049}BATCH-1049}} - Add compile scope to spring-test in spring-batch-test - - * {{{http://jira.spring.io/browse/BATCH-1048}BATCH-1048}} - Add site docos for the Test project - - * {{{http://jira.spring.io/browse/BATCH-1047}BATCH-1047}} - CommandLineJobRunner should use JobOperator - - * {{{http://jira.spring.io/browse/BATCH-1043}BATCH-1043}} - Add chapter on scaling (partitioning, etc) to docs - - * {{{http://jira.spring.io/browse/BATCH-1041}BATCH-1041}} - Create section in documentation about launching from within a web container - - * {{{http://jira.spring.io/browse/BATCH-1040}BATCH-1040}} - Add cross referencing to documentation - - * {{{http://jira.spring.io/browse/BATCH-1037}BATCH-1037}} - Change namespace to set job-repository only on job - - * {{{http://jira.spring.io/browse/BATCH-1034}BATCH-1034}} - Add StepScope to application context automatically in the parser - - * {{{http://jira.spring.io/browse/BATCH-1030}BATCH-1030}} - FlowJob replays failed steps on restart, even if the failure did not fail the job - - * {{{http://jira.spring.io/browse/BATCH-1028}BATCH-1028}} - JdbcCursorItemReader driverSupportsAbsolute property defaults to false - - * {{{http://jira.spring.io/browse/BATCH-1027}BATCH-1027}} - PassThroughFieldExtractor should have a unit test - - * {{{http://jira.spring.io/browse/BATCH-1023}BATCH-1023}} - File writing related interfaces need more javadoc - - * {{{http://jira.spring.io/browse/BATCH-1013}BATCH-1013}} - Using the batch namespace, steps can't be defined outside of the "job" tag. - - * {{{http://jira.spring.io/browse/BATCH-1011}BATCH-1011}} - Need distinction between "stop" and "end" transitions? - - * {{{http://jira.spring.io/browse/BATCH-1010}BATCH-1010}} - StepFactoryBeans cleanup - - * {{{http://jira.spring.io/browse/BATCH-1008}BATCH-1008}} - Elements in namespace are order-dependent - - * {{{http://jira.spring.io/browse/BATCH-1000}BATCH-1000}} - Add timeout to TaskExecutorPartitionHandler - - * {{{http://jira.spring.io/browse/BATCH-955}BATCH-955}} - Update XML schema to be tooling friendly - - * {{{http://jira.spring.io/browse/BATCH-949}BATCH-949}} - JdbcCursorItemReader: property name for "mapper"? - - * {{{http://jira.spring.io/browse/BATCH-942}BATCH-942}} - Obvious JobLocator implementation - - * {{{http://jira.spring.io/browse/BATCH-909}BATCH-909}} - Turn off getWarnings() call in JdbcCursorItemReader when ignoreWarnings is true - - * {{{http://jira.spring.io/browse/BATCH-882}BATCH-882}} - Create section in documentation highlighting key changes between 1.x and 2.0 - - * {{{http://jira.spring.io/browse/BATCH-851}BATCH-851}} - Remove DrivingQueryItemReader support in favor of PagingItemReaders - - * {{{http://jira.spring.io/browse/BATCH-819 Create}BATCH-819 Create}} - separate CI builds for artifacts in Maven Central and Enterprise Repository - - * {{{http://jira.spring.io/browse/BATCH-818 Create}BATCH-818 Create}} - and test ivy and maven files needed for build - - * {{{http://jira.spring.io/browse/BATCH-793}BATCH-793}} - Creating a new ApplicationContext per Job needs refactoring - - * {{{http://jira.spring.io/browse/BATCH-690}BATCH-690}} - Move drop table statements to separate script - - * {{{http://jira.spring.io/browse/BATCH-659}BATCH-659}} - unused classes deprecation/removal - - * {{{http://jira.spring.io/browse/BATCH-618}BATCH-618}} - DefaultJobParametersConverter does not parse parameters of type double - - * {{{http://jira.spring.io/browse/BATCH-583}BATCH-583}} - Figures missing from PDF docs - diff --git a/src/site/apt/migration/2.0-rc1-rc2.apt b/src/site/apt/migration/2.0-rc1-rc2.apt deleted file mode 100644 index 250b663ca..000000000 --- a/src/site/apt/migration/2.0-rc1-rc2.apt +++ /dev/null @@ -1,152 +0,0 @@ -Spring Batch 2.0.0.RC2 Release Notes - -* Issues - - * {{{http://jira.spring.io/browse/BATCH-1165}BATCH-1165}} - Allow 'id' and 'ref' to exist together on <*-listener/> - - * {{{http://jira.spring.io/browse/BATCH-1164}BATCH-1164}} - Putting scope="step" on a listener causes failure - - * {{{http://jira.spring.io/browse/BATCH-1163}BATCH-1163}} - In Batch xsd, elements in should be unordered - - * {{{http://jira.spring.io/browse/BATCH-1162}BATCH-1162}} - In Batch xsd, elements in should be unordered - - * {{{http://jira.spring.io/browse/BATCH-1161}BATCH-1161}} - Throw error if a flow has no steps - - * {{{http://jira.spring.io/browse/BATCH-1160}BATCH-1160}} - In Batch xsd, stepType and flowStepType should be unordered - - * {{{http://jira.spring.io/browse/BATCH-1159}BATCH-1159}} - PROCESS_SKIP_COUNT seems not to ever get written to database - - * {{{http://jira.spring.io/browse/BATCH-1157}BATCH-1157}} - Add max count parameter to counting item readers - - * {{{http://jira.spring.io/browse/BATCH-1154}BATCH-1154}} - TaskletElementParser can't predict which StepFactoryBean to use - - * {{{http://jira.spring.io/browse/BATCH-1153}BATCH-1153}} - listener element should only have an "id" when defined at the top level - - * {{{http://jira.spring.io/browse/BATCH-1152}BATCH-1152}} - Allow comma and newline as delimiters in exception lists in namespace - - * {{{http://jira.spring.io/browse/BATCH-1151}BATCH-1151}} - Add IDE support to in xsd - - * {{{http://jira.spring.io/browse/BATCH-1147}BATCH-1147}} - StepExecution getFilterCount always return 0 - - * {{{http://jira.spring.io/browse/BATCH-1145}BATCH-1145}} - Conflicts if both and have a "parent" attribute - - * {{{http://jira.spring.io/browse/BATCH-1144}BATCH-1144}} - Create top-level element - - * {{{http://jira.spring.io/browse/BATCH-1143}BATCH-1143}} - Standalone should not be allowed to have "tasklet" attribute and together - - * {{{http://jira.spring.io/browse/BATCH-1142}BATCH-1142}} - In the xsd, should be moved from "flowType" to "job" - - * {{{http://jira.spring.io/browse/BATCH-1141}BATCH-1141}} - Rename CompositeExecutionJobListener to CompositeJobExecutionListener - - * {{{http://jira.spring.io/browse/BATCH-1139}BATCH-1139}} - Add "parent" attribute to - - * {{{http://jira.spring.io/browse/BATCH-1138}BATCH-1138}} - Add "parent" attribute to - - * {{{http://jira.spring.io/browse/BATCH-1136}BATCH-1136}} - Add setListeners(StepExecutionListener[]) to TaskletStep - - * {{{http://jira.spring.io/browse/BATCH-1135}BATCH-1135}} - Create top-level element - - * {{{http://jira.spring.io/browse/BATCH-1134}BATCH-1134}} - Create a superclass for StepListenerParser and JobExecutionListenerParser - - * {{{http://jira.spring.io/browse/BATCH-1132}BATCH-1132}} - Add "parent" attribute to - - * {{{http://jira.spring.io/browse/BATCH-1131}BATCH-1131}} - It is not possible to set transaction-attributes for a tasklet step - - * {{{http://jira.spring.io/browse/BATCH-1130}BATCH-1130}} - Ensure Ordered is respected by generated listeners - - * {{{http://jira.spring.io/browse/BATCH-1129}BATCH-1129}} - Problems with exception classifications - - * {{{http://jira.spring.io/browse/BATCH-1128}BATCH-1128}} - Make sure WRITE_COUNT and ROLLBACK_COUNT are being updated correctly - - * {{{http://jira.spring.io/browse/BATCH-1127}BATCH-1127}} - Add contextual line number information for exceptions thrown by FlatFileItemReader - - * {{{http://jira.spring.io/browse/BATCH-1126}BATCH-1126}} - StepScope does not apply to twice nested inner beans - - * {{{http://jira.spring.io/browse/BATCH-1125}BATCH-1125}} - NoWorkFoundStepExecutionListener doesn't fail the step - - * {{{http://jira.spring.io/browse/BATCH-1124}BATCH-1124}} - Fix error message that occurs when the same annotation is used twice on one method - - * {{{http://jira.spring.io/browse/BATCH-1123}BATCH-1123}} - ExecutionContextPromotionListener may perform promotion multiple times - - * {{{http://jira.spring.io/browse/BATCH-1122}BATCH-1122}} - StaxEventWriter.startDocument() needs to be protected - - * {{{http://jira.spring.io/browse/BATCH-1121}BATCH-1121}} - Documentation should cover the 'no work found' scenario - - * {{{http://jira.spring.io/browse/BATCH-1120}BATCH-1120}} - Allow completion policy to be set on step - - * {{{http://jira.spring.io/browse/BATCH-1119}BATCH-1119}} - afterWrite() will only be called if an exception is raised during throttling - - * {{{http://jira.spring.io/browse/BATCH-1118}BATCH-1118}} - Listener annotation with wrong signature fails too late and too quietly - - * {{{http://jira.spring.io/browse/BATCH-1117}BATCH-1117}} - onWriteError should be called with only the bad item - - * {{{http://jira.spring.io/browse/BATCH-1116}BATCH-1116}} - Create section on MetaDataInstanceFactory in testing chapter - - * {{{http://jira.spring.io/browse/BATCH-1113}BATCH-1113}} - query for JdbcJobExecutionDao.findRunningJobExecutions is broken - - * {{{http://jira.spring.io/browse/BATCH-1112}BATCH-1112}} - Remove cycle in infrastructure database/support - - * {{{http://jira.spring.io/browse/BATCH-1111}BATCH-1111}} - ChunkListener called before WriteListener - - * {{{http://jira.spring.io/browse/BATCH-1110}BATCH-1110}} - Defer EntityManager flushing and clearing in JpaPagingItemReader - - * {{{http://jira.spring.io/browse/BATCH-1109}BATCH-1109}} - Generalise PrefixMatching* to PatternMatching* - - * {{{http://jira.spring.io/browse/BATCH-1108}BATCH-1108}} - Add composite ItemWriter/Processor based on Classifier - - * {{{http://jira.spring.io/browse/BATCH-1107}BATCH-1107}} - Fix Date conversion in PlaceholderTargetSource - - * {{{http://jira.spring.io/browse/BATCH-1106}BATCH-1106}} - SqlPagingQueryProviderFactoryBean ascending should default to true - - * {{{http://jira.spring.io/browse/BATCH-1105}BATCH-1105}} - Namespace error in documentation - - * {{{http://jira.spring.io/browse/BATCH-1104}BATCH-1104}} - Wrong stax version in spring-batch-parent-2.0.0.RC1.pom, is 1.2 should be 1.2.0 - - * {{{http://jira.spring.io/browse/BATCH-1103}BATCH-1103}} - Add partioning sample - - * {{{http://jira.spring.io/browse/BATCH-1102}BATCH-1102}} - Classes with "listener" annotations should be auto-registered - - * {{{http://jira.spring.io/browse/BATCH-1101}BATCH-1101}} - Remove StepScope bean definition from samples that don't need it - - * {{{http://jira.spring.io/browse/BATCH-1099}BATCH-1099}} - Make writer in skip sample stateful - - * {{{http://jira.spring.io/browse/BATCH-1098}BATCH-1098}} - Check @AfterWrite is only called once per item - - * {{{http://jira.spring.io/browse/BATCH-1097}BATCH-1097}} - Add late binding to some io samples - - * {{{http://jira.spring.io/browse/BATCH-1096}BATCH-1096}} - Add late binding to some io samples - - * {{{http://jira.spring.io/browse/BATCH-1093}BATCH-1093}} - Make AbstractJobTests.makeUniqueJobParameters() public - - * {{{http://jira.spring.io/browse/BATCH-1092}BATCH-1092}} - Fix naming conventions for exit status in - - * {{{http://jira.spring.io/browse/BATCH-1091}BATCH-1091}} - Add strict flag to file readers (flat and XML). - - * {{{http://jira.spring.io/browse/BATCH-1072}BATCH-1072}} - Update docs to reflect attribute change in step element - - * {{{http://jira.spring.io/browse/BATCH-1065}BATCH-1065}} - "BATCH-1011 - - * {{{http://jira.spring.io/browse/Update documentation to explain end/fail/pause transitions" - * {{{http://jira.spring.io/browse/BATCH-976}BATCH-976}} - Provide automatic batch database schema installation utility - - * {{{http://jira.spring.io/browse/BATCH-937}BATCH-937}} - Make sure JobRepository can be proxied - - * {{{http://jira.spring.io/browse/BATCH-935}BATCH-935}} - Use NumberFormat when parsing real numbers - - * {{{http://jira.spring.io/browse/BATCH-918}BATCH-918}} - Duplicate jar files in *-with-dependencies.zip - - * {{{http://jira.spring.io/browse/BATCH-902}BATCH-902}} - Revise FAQ on web site - - * {{{http://jira.spring.io/browse/BATCH-794}BATCH-794}} - Align with SpringSource Enterprise Repository - - * {{{http://jira.spring.io/browse/BATCH-632}BATCH-632}} - Move Tasklet interface from core to infrastructure - - * {{{http://jira.spring.io/browse/BATCH-573}BATCH-573}} - Delegating streams and listeners (e.g. HibernateAwareItemWriter) should delegate those interfaces to their delegates. - - * {{{http://jira.spring.io/browse/BATCH-501}BATCH-501}} - Core and Infrastructure still have circular dependency - - * {{{http://jira.spring.io/browse/BATCH-470}BATCH-470}} - RFC: Can all ExceptionHandlers be replaced by a combination of making Repeat/RetryListeners more robust and rewriting as Listeners? - - * {{{http://jira.spring.io/browse/BATCH-394}BATCH-394}} - If FieldSet is an interface it needs a factory, otherwise existing clients are tied to specific implementations - - * {{{http://jira.spring.io/browse/BATCH-22}BATCH-22}} - Find alternative to ThreadLocal for RepeatSynchronizationManager diff --git a/src/site/apt/migration/2.0-rc2-rc3.apt b/src/site/apt/migration/2.0-rc2-rc3.apt deleted file mode 100644 index 29aee3d69..000000000 --- a/src/site/apt/migration/2.0-rc2-rc3.apt +++ /dev/null @@ -1,27 +0,0 @@ -Spring Batch 2.0.0.RC3 Release Notes - -* Issues - - * {{{http://jira.spring.io/browse/BATCH-1168}BATCH-1168}} - Bad ERROR_LOG definition in business-schema-mysql.sql - - * {{{http://jira.spring.io/browse/BATCH-1169}BATCH-1169}} - Incorrect system property name in data-source-context.xml - - * {{{http://jira.spring.io/browse/BATCH-1171}BATCH-1171}} - Interrupted step does not fail job. - - * {{{http://jira.spring.io/browse/BATCH-1174}BATCH-1174}} - Late binding of jobParameters does not work if late binding expression is not preceded or trailed by string - - * {{{http://jira.spring.io/browse/BATCH-1176}BATCH-1176}} - Update documentation section 5.2.2. Example Tasklet implementation - - * {{{http://jira.spring.io/browse/BATCH-1178}BATCH-1178}} - with "ref=" silently ignores other attributes - - * {{{http://jira.spring.io/browse/BATCH-1180}BATCH-1180}} - Error occurs if parent= attribute appears on inline without tasket - - * {{{http://jira.spring.io/browse/BATCH-1181}BATCH-1181}} - element always assumes the step is a TaskletStep - - * {{{http://jira.spring.io/browse/BATCH-1175}BATCH-1175}} - Update Validator interface for Java 5 - - * {{{http://jira.spring.io/browse/BATCH-1183}BATCH-1183}} - Implement toString() on Step Implementations - - * {{{http://jira.spring.io/browse/BATCH-1179}BATCH-1179}} - Remove ref= attribute from in favor of parent= - - * {{{http://jira.spring.io/browse/BATCH-1184}BATCH-1184}} - DelegatingStep is not used. It should be removed. diff --git a/src/site/apt/migration/2.0-rc3-release.apt b/src/site/apt/migration/2.0-rc3-release.apt deleted file mode 100644 index 19779267d..000000000 --- a/src/site/apt/migration/2.0-rc3-release.apt +++ /dev/null @@ -1,49 +0,0 @@ -Spring Batch 2.0.0.RELEASE Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1170}BATCH-1170}} - When using FixedLengthTokenizer and FixedLengthLineAggregator, can not read the record correctly with parameters like [p:columns="1-9,10-19,20-29,30-39,40-49"] in the configuration file. - - * {{{http://jira.spring.io/browse/BATCH-1185}BATCH-1185}} - Job slows when step scope is used - - * {{{http://jira.spring.io/browse/BATCH-1187}BATCH-1187}} - Step shouldn't exit with status=EXECUTING - - * {{{http://jira.spring.io/browse/BATCH-1188}BATCH-1188}} - Build fails for bundlor SNAPSHOT used for Batch since it conflicts with more recent one - - * {{{http://jira.spring.io/browse/BATCH-1192}BATCH-1192}} - Error in documentation section 4.2.3 - In-Memory Repository - - * {{{http://jira.spring.io/browse/BATCH-1196}BATCH-1196}} - ExecutionContext not re-hydrated by JdbcJobExecutionDao - - * {{{http://jira.spring.io/browse/BATCH-1197}BATCH-1197}} - Rerunning a job sometimes creates new job instance - - * {{{http://jira.spring.io/browse/BATCH-1198}BATCH-1198}} - processSkipCount and filterCount mixed up - - * {{{http://jira.spring.io/browse/BATCH-1201}BATCH-1201}} - Listener Annotations don't allow parameters to be subtypes of expected types - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1095}BATCH-1095}} - Throw exception if late binding fails - - * {{{http://jira.spring.io/browse/BATCH-1150}BATCH-1150}} - Update StepExecutionPreparedStatementSetter to no longer be a listener - - * {{{http://jira.spring.io/browse/BATCH-1172}BATCH-1172}} - Register RangeArrayPropertyEditor automatically - - * {{{http://jira.spring.io/browse/BATCH-1177}BATCH-1177}} - Allow ValidatingItemProcessor to filter items on ValidationException - - * {{{http://jira.spring.io/browse/BATCH-1189}BATCH-1189}} - By default, all exceptions should be fatal - - * {{{http://jira.spring.io/browse/BATCH-1190}BATCH-1190}} - Navigation pane for Modules pages have bad links - - * {{{http://jira.spring.io/browse/BATCH-1191}BATCH-1191}} - site:deploy - Missing distribution management information in the project - - * {{{http://jira.spring.io/browse/BATCH-1200}BATCH-1200}} - Update JavaDocs for Listener Annotations - -* Task - - * {{{http://jira.spring.io/browse/BATCH-834}BATCH-834}} - Review stop signal handling at JobExecution - - * {{{http://jira.spring.io/browse/BATCH-1042}BATCH-1042}} - Add 'Whats New in 2.0" chapter to docs - - * {{{http://jira.spring.io/browse/BATCH-1194}BATCH-1194}} - Swicth Eclipse meta data to m2eclipse - - * {{{http://jira.spring.io/browse/BATCH-1195}BATCH-1195}} - Add "Common Pattern" for passing data from one step to another diff --git a/src/site/apt/migration/2.0.0-2.0.1.apt b/src/site/apt/migration/2.0.0-2.0.1.apt deleted file mode 100644 index 5a2338fb1..000000000 --- a/src/site/apt/migration/2.0.0-2.0.1.apt +++ /dev/null @@ -1,88 +0,0 @@ -Spring Batch 2.0.1.RELEASE Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1203]}} - Correct ChunkOrientedTasklet.setBuffering javadoc - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1204]}} - Error in FieldSetMapper documentation - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1205]}} - When readCount % commitInterval == 0, commitCount is one more than it should be - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1208]}} - late-binding not being resolved in - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1210]}} - AbstractStep overwrites custom exit status for STOPPED steps - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1212]}} - Incorrect link in Documentation - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1213]}} - Defaults in xsd override parent attributes - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1214]}} - CoreNamespaceUtils.addRangePropertyEditor fails with Spring 3.0 - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1215]}} - Docs refer to non-existent class SimpleDelegatingPagingQueryProvider - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1218]}} - item streams won't get registered if ItemStream reader is used with step - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1223]}} - Maven Build - ClassNotFoundException: com.springsource.util.osgi.manifest.ManifestFactory - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1225]}} - FlatFileItemWriter and StaxEventItemWriter do not restart in the right place - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1230]}} - scope "step" does not work together with Annotation "@BeforeStep" - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1234]}} - ExitStatus.FINISHED should be ExitStatus.COMPLETED - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1236]}} - Fix namespace errors in Readers and Writers chapter - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1240]}} - ItemStream is not registered when defined in step scope - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1241]}} - SystemCommandTasklet package name is not accurate - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1244]}} - Documentation error for skip-limit - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1245]}} - StaxEventItemWriter writes extra end document tag with Woodstox 3.2.9 plus - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1249]}} - Add files to .springBeans in samples project - - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1172]}} - Register RangeArrayPropertyEditor automatically - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1202]}} - Improve error message when neither commit-interval nor chunk-completion-policy are specified on a chuck (xml namespace) - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1216]}} - Adding the possiblity to set the throttle limit in the spring batch name space - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1217]}} - Suggest use .doubleValue() value in DefaultFieldSet.readDouble(..) - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1219]}} - JmsItemReader and -Writer should check for proper settings on JmsTemplate - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1220]}} - Apply consistent debug logging in framework-provided ItemWriter implementations - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1221]}} - Use batch namespace in simple cli template / archetype - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1228]}} - Possibility to modify proxyTargetClass property of StepScope - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1233]}} - Confusing docs in section 4.1 on non-default job repo id for nested step element - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1247]}} - Clean up multilineOrderJob sample - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1248]}} - Remove default from "merge" attribute in XSD - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1250]}} - should disallow , , and if abstract=true - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1251]}} - Use standard JPQL in JPA sample - - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1226]}} - Add assertLineCount method to AssertFile - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1238]}} - Add ItemProcessorAdapter similar to Item*Adapter - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1243]}} - Expose the current resource of MultiResourceItemReader - - -* Task - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-724]}} - create tests for non-default table prefix - - * {{{http://jira.spring.io/browse/BATCH-1203}[BATCH-1211]}} - Update samples docs on website diff --git a/src/site/apt/migration/2.0.1-2.0.2.apt b/src/site/apt/migration/2.0.1-2.0.2.apt deleted file mode 100644 index 20ba76dae..000000000 --- a/src/site/apt/migration/2.0.1-2.0.2.apt +++ /dev/null @@ -1,122 +0,0 @@ -Spring Batch 2.0.2.RELEASE Release Notes - - -* Sub-task - - *{{{http://jira.spring.io/browse/BATCH-1327}[BATCH-1327]}} - Prevent re-processing and re-writing on rollback after non-skippable and non-retryable exception - - * {{{http://jira.spring.io/browse/BATCH-1331}[BATCH-1331]}} - Fatal exceptions that are also marked as no-rollback - - * {{{http://jira.spring.io/browse/BATCH-1332}[BATCH-1332]}} - Skippable exceptions on write that are also marked as no-rollback cause a rollback, and double processing of item (writer and skip listener) - - * {{{http://jira.spring.io/browse/BATCH-1333}[BATCH-1333]}} - Support for retry of non-skippable subclasses of skippable exceptions - - * {{{http://jira.spring.io/browse/BATCH-1334}[BATCH-1334]}} - Exception marked as no-rollback but not skippable should not cause skips - - * {{{http://jira.spring.io/browse/BATCH-1335}[BATCH-1335]}} - Pathological cases of no-rollback-for-exceptions on framework panic exceptions - - - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1232}[BATCH-1232]}} - Sybase 12.5 compatiblity when writing to the spring batch context tables - - * {{{http://jira.spring.io/browse/BATCH-1264}[BATCH-1264]}} - NPE in StepParserStepFactoryBean#configureTaskletStep() #289 when omitting "isolation" for <transaction-attributes> - - * {{{http://jira.spring.io/browse/BATCH-1272}[BATCH-1272]}} - Write skips do not work in a multi-threaded step - - * {{{http://jira.spring.io/browse/BATCH-1278}[BATCH-1278]}} - RepeatTemplate aborts early if multiple threads throw ignorable exceptions - - * {{{http://jira.spring.io/browse/BATCH-1280}[BATCH-1280]}} - JobParserJobFactoryBean should be a singleton - - * {{{http://jira.spring.io/browse/BATCH-1282}[BATCH-1282]}} - JobRegistryBeanPostProcessor skips jobs in XML namespace unless they are injected as dependency - - * {{{http://jira.spring.io/browse/BATCH-1284}[BATCH-1284]}} - Partition Step Stop is incorrectly setting the BatchStatus to COMPLETED. - - * {{{http://jira.spring.io/browse/BATCH-1287}[BATCH-1287]}} - JobRegistryBeanPostProcessor is checking for Job instead of JobParserJobFactoryBean - - * {{{http://jira.spring.io/browse/BATCH-1289}[BATCH-1289]}} - Null pointer in CoreNamespaceUtils.rangeArrayEditorAlreadyDefined() - - * {{{http://jira.spring.io/browse/BATCH-1301}[BATCH-1301]}} - ItemStream is not being opened correctly for multi-threaded Step when scope="step" - - * {{{http://jira.spring.io/browse/BATCH-1304}[BATCH-1304]}} - Filter counter not incremented whenever there's a skip - - * {{{http://jira.spring.io/browse/BATCH-1308}[BATCH-1308]}} - FixedLengthTokenizer's 'names' property may not have spaces - - * {{{http://jira.spring.io/browse/BATCH-1313}[BATCH-1313]}} - loopFlowSample's LimitDecider returns "COMPLETE" instead of "COMPLETED" - - * {{{http://jira.spring.io/browse/BATCH-1314}[BATCH-1314]}} - FFIW in tradeJob is pointing to classpath instead of the target - - * {{{http://jira.spring.io/browse/BATCH-1315}[BATCH-1315]}} - Section 2.3 Configuration Enhancements contains invalid example - - * {{{http://jira.spring.io/browse/BATCH-1318}[BATCH-1318]}} - Ensure exception classes are behaving correctly - - * {{{http://jira.spring.io/browse/BATCH-1319}[BATCH-1319]}} - Small memory leak in StepSynchronizationManager - - - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1262}[BATCH-1262]}} - org.springframework.batch.item.file.transform.DefaultFieldSet#readBigDecimal doesn't use supplied numberFormat - - * {{{http://jira.spring.io/browse/BATCH-1267}[BATCH-1267]}} - Make sure jmsTemplate is not null in JmsItemReader - - * {{{http://jira.spring.io/browse/BATCH-1268}[BATCH-1268]}} - Remove dependency on commons lang - - * {{{http://jira.spring.io/browse/BATCH-1270}[BATCH-1270]}} - Update documentation for formatting consistency - - * {{{http://jira.spring.io/browse/BATCH-1275}[BATCH-1275]}} - ExecutionContextPromotionListener contains duplicate assertion - - * {{{http://jira.spring.io/browse/BATCH-1276}[BATCH-1276]}} - Change Common Pattern "Writing a Summary Footer" to use AfterWrite for updating total. - - * {{{http://jira.spring.io/browse/BATCH-1285}[BATCH-1285]}} - Raise an exception if a step cannot be reached. - - * {{{http://jira.spring.io/browse/BATCH-1299}[BATCH-1299]}} - Add processSkipCount in StepExecution#getSummary() - - * {{{http://jira.spring.io/browse/BATCH-1302}[BATCH-1302]}} - Tidy up samples - remove prefixes for namespaces like beans: - - * {{{http://jira.spring.io/browse/BATCH-1305}[BATCH-1305]}} - Add download page link to the batch home page - - * {{{http://jira.spring.io/browse/BATCH-1310}[BATCH-1310]}} - SimpleJobExplorer should return null when a StepExecution cannot be found - - * {{{http://jira.spring.io/browse/BATCH-1311}[BATCH-1311]}} - SimpleJobExplorer should return null when a StepExecution cannot be found - - * {{{http://jira.spring.io/browse/BATCH-1312}[BATCH-1312]}} - Improve error messages for skip/retry configurations - - - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1253}[BATCH-1253]}} - Ability to throttle the number of rows returned by a HibernateCursorItemReader - - * {{{http://jira.spring.io/browse/BATCH-1279}[BATCH-1279]}} - Add default constructor to ValidatingItemProcessor for those preferring setter injection - - * {{{http://jira.spring.io/browse/BATCH-1288}[BATCH-1288]}} - Typo in CallableTaskletAdapter JavaDoc - - * {{{http://jira.spring.io/browse/BATCH-1295}[BATCH-1295]}} - Provide ability to pass job's ExecutionContext into AbstractJobTests.launchStep() - - * {{{http://jira.spring.io/browse/BATCH-1297}[BATCH-1297]}} - Add null check for FlatFileItemReader in case resource exists on close, but not on open(!) - - * {{{http://jira.spring.io/browse/BATCH-1303}[BATCH-1303]}} - Support Spring 3.0 expression language in beans that are not step scoped - - * {{{http://jira.spring.io/browse/BATCH-1306}[BATCH-1306]}} - DelimitedLineAggregator might skip null objects - - * {{{http://jira.spring.io/browse/BATCH-1309}[BATCH-1309]}} - Added a 'strict' property to ExecutionContextPromotionListener to ensure the key is present - - * {{{http://jira.spring.io/browse/BATCH-1317}[BATCH-1317]}} - Add flag to FlatFileItemWriter to delete empty files - - * {{{http://jira.spring.io/browse/BATCH-1320}[BATCH-1320]}} - New line special character in Header - - * {{{http://jira.spring.io/browse/BATCH-1321}[BATCH-1321]}} - Upgrade MANIFEST to allow Spring 3.0 to be used optionally - - * {{{http://jira.spring.io/browse/BATCH-1325}[BATCH-1325]}} - Add more convenience methods to JobRepositoryTestUtils - - * {{{http://jira.spring.io/browse/BATCH-1336}[BATCH-1336]}} - Add -restart and -next options to CommandLineJobRunner - - - -* Task - - * {{{http://jira.spring.io/browse/BATCH-1271}[BATCH-1271]}} - Add a note about bean scope for batch parameters usage - - diff --git a/src/site/apt/migration/2.0.2-2.0.3.apt b/src/site/apt/migration/2.0.2-2.0.3.apt deleted file mode 100644 index 73310dad1..000000000 --- a/src/site/apt/migration/2.0.2-2.0.3.apt +++ /dev/null @@ -1,33 +0,0 @@ -Spring Batch 2.0.2.RELEASE Release Notes - - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1341}[BATCH-1341]}} - DataSourceInitializer throws ArrayOutOfBoundException when any destroyScript is specified - - * {{{http://jira.spring.io/browse/BATCH-1345}[BATCH-1345]}} - Fix error message for when <tasklet/> has no ref= or <chunk/> - - * {{{http://jira.spring.io/browse/BATCH-1351}[BATCH-1351]}} - An empty <*-exception-classes/> list does not override parent's list - - * {{{http://jira.spring.io/browse/BATCH-1354}[BATCH-1354]}} - Infinite loop caused by throwing an Error from the ItemWriter of a skippable step - - * {{{http://jira.spring.io/browse/BATCH-1355}[BATCH-1355]}} - Step scope causes type= attribute of <value/> to be ignored - - * {{{http://jira.spring.io/browse/BATCH-1362}[BATCH-1362]}} - Threads spinning doing nothing at end of multi-threaded Step - - * {{{http://jira.spring.io/browse/BATCH-1363}[BATCH-1363]}} - Job stopped in split state does not finish with status = STOPPED - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1342}[BATCH-1342]}} - Check for valid parameter arguments in CommandLineJobRunner - - * {{{http://jira.spring.io/browse/BATCH-1359}[BATCH-1359]}} - Throw helpful error from JdbcCursorItemReader if read() called before open() - - * {{{http://jira.spring.io/browse/BATCH-1360}[BATCH-1360]}} - Throw helpful error from if Tasklet.execute() returns null - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1361}[BATCH-1361]}} - Support for maps in PassThroughFieldExtractor - - * {{{http://jira.spring.io/browse/BATCH-1370}[BATCH-1370]}} - Bind to non-scalar map entry values in step scope - diff --git a/src/site/apt/migration/2.0.3-2.0.4.apt b/src/site/apt/migration/2.0.3-2.0.4.apt deleted file mode 100755 index 7f79b522b..000000000 --- a/src/site/apt/migration/2.0.3-2.0.4.apt +++ /dev/null @@ -1,19 +0,0 @@ -Spring Batch 2.1.0.M1 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1392}[BATCH-1392]}} - Throttle limit is not parsed in ChunkElementParser - - * {{{http://jira.spring.io/browse/BATCH-1397}[BATCH-1397]}} - Late binding only happens once per ApplicationContext if expression is in substring - - * {{{http://jira.spring.io/browse/BATCH-1401}[BATCH-1401]}} - All inserts of JobId should be of Types.BIGINT - - * {{{http://jira.spring.io/browse/BATCH-1408}[BATCH-1408]}} - SimpleJobLauncher package wrong in user guide - - * {{{http://jira.spring.io/browse/BATCH-1410}[BATCH-1410]}} - Isolation Level in the example in user guide is not supported - - * {{{http://jira.spring.io/browse/BATCH-1417}[BATCH-1417]}} - Error in FlatFileItemReader when RecordSeparatorPolicy.preProcess readLine returns null - - * {{{http://jira.spring.io/browse/BATCH-1420}[BATCH-1420]}} - Late Binding only happens first time when using inner bean definition with collection property - - * {{{http://jira.spring.io/browse/BATCH-1423}[BATCH-1423]}} - Upon job restart, step with FlatFileItemReader doesn't honor skippable-exception-classes diff --git a/src/site/apt/migration/2.0.x-2.1.0.M1.apt b/src/site/apt/migration/2.0.x-2.1.0.M1.apt deleted file mode 100644 index ed14be19e..000000000 --- a/src/site/apt/migration/2.0.x-2.1.0.M1.apt +++ /dev/null @@ -1,78 +0,0 @@ -Spring Batch 2.1.0.M1 Release Notes - -* Sub-task - - * {{{http://jira.spring.io/browse/BATCH-1298}[BATCH-1298]}} - no-rollback-exception-classes ignored by non-chunk-oriented TaskletStep - - * {{{http://jira.spring.io/browse/BATCH-1366}[BATCH-1366]}} - Syntactic sugar for CompositeItemProcessor and CompositeItemWriter in namespace - - * {{{http://jira.spring.io/browse/BATCH-1367}[BATCH-1367]}} - Syntactic sugar for Item*Adapter in namespace - - * {{{http://jira.spring.io/browse/BATCH-1368}[BATCH-1368]}} - Update docs to remove syntax - - * {{{http://jira.spring.io/browse/BATCH-1381}[BATCH-1381]}} - Update docs for and in exception lists - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1390}[BATCH-1390]}} - ExecutionContextPromotionListener erases previous step - - * {{{http://jira.spring.io/browse/BATCH-1392}[BATCH-1392]}} - Throttle limit is not parsed in ChunkElementParser - - * {{{http://jira.spring.io/browse/BATCH-1397}[BATCH-1397]}} - Late binding only happens once per ApplicationContext if expression is in substring - - * {{{http://jira.spring.io/browse/BATCH-1408}[BATCH-1408]}} - SimpleJobLauncher Package wrong - - * {{{http://jira.spring.io/browse/BATCH-1410}[BATCH-1410]}} - Isolation Level in the Example is not supported - - * {{{http://jira.spring.io/browse/BATCH-1413}[BATCH-1413]}} - A typo in the 11.8 of reference documentation - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-630}[BATCH-630]}} - Possibility to trim input line and fields in Fieldset in LineTokenizer - - * {{{http://jira.spring.io/browse/BATCH-742}[BATCH-742]}} - Inclusion of a ResourceItemReader that will return resources (such as files in a directory) instead of records from a single resource. - - * {{{http://jira.spring.io/browse/BATCH-915}[BATCH-915]}} - Call open() lazily in MultiResourceItemReader to allow resources to be skipped - - * {{{http://jira.spring.io/browse/BATCH-1323}[BATCH-1323]}} - Modify skip/retry/no-rollback exception class configurations to allow for exclude/include - - * {{{http://jira.spring.io/browse/BATCH-1339}[BATCH-1339]}} - Move task-executor attribute up from to - - * {{{http://jira.spring.io/browse/BATCH-1357}[BATCH-1357]}} - Allow empty , , and lists - - * {{{http://jira.spring.io/browse/BATCH-1375}[BATCH-1375]}} - Give CompositeItemProcessor's and CompositeItemWriter's property the same name (delegates) - - * {{{http://jira.spring.io/browse/BATCH-1404}[BATCH-1404]}} - archetype update - - * {{{http://jira.spring.io/browse/BATCH-1409}[BATCH-1409]}} - More efficient use of pool threads in repeat template (hence multi-threaded steps) - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1277}[BATCH-1277]}} - Add JobParametersBuilder.addJobParameter(String key, JobParameter parameter) - - * {{{http://jira.spring.io/browse/BATCH-1348}[BATCH-1348]}} - Allow inlining of reader/writer/processor into - - * {{{http://jira.spring.io/browse/BATCH-1350}[BATCH-1350]}} - Add back (much simplified) StepExecutionResourceProxy - - * {{{http://jira.spring.io/browse/BATCH-1356}[BATCH-1356]}} - Line reader for binary files - - * {{{http://jira.spring.io/browse/BATCH-1358}[BATCH-1358]}} - Copy InfiniteLoopIncrementer into core, and rename it to RunIdIncrementer - - * {{{http://jira.spring.io/browse/BATCH-1385}[BATCH-1385]}} - Composite elements do not honour @Order annotations - - * {{{http://jira.spring.io/browse/BATCH-1389}[BATCH-1389]}} - Thread safety in *PagingReader - - * {{{http://jira.spring.io/browse/BATCH-1406}[BATCH-1406]}} - Avoid deadlock with database pool and multithreaded step when throttle limit is too high. - - * {{{http://jira.spring.io/browse/BATCH-1415}[BATCH-1415]}} - Execution context cannot be saved on Oracle (UTF8) when context length is between 2000 and 2500 characters - -* Refactoring - - * {{{http://jira.spring.io/browse/BATCH-973}[BATCH-973]}} - Switch RetryPolicy back to Throwable instead of Exception as in 1.x - - * {{{http://jira.spring.io/browse/BATCH-1414}[BATCH-1414]}} - Move schema scripts to a package - -* Task - - * {{{http://jira.spring.io/browse/BATCH-1391}[BATCH-1391]}} - Tidy up skip sample. - diff --git a/src/site/apt/migration/2.1.0-2.1.1.apt b/src/site/apt/migration/2.1.0-2.1.1.apt deleted file mode 100644 index ac539064f..000000000 --- a/src/site/apt/migration/2.1.0-2.1.1.apt +++ /dev/null @@ -1,80 +0,0 @@ -Spring Batch 2.1.1 Release Notes - -* Sub-task - - * {{{http://jira.spring.io/browse/BATCH-1520}[BATCH-1520]}} - Allow null ItemWriter as long as ItemProcessor is provided - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1503}[BATCH-1503]}} - JobExecution marked COMPLETE on failure to save step execution metadata - - * {{{http://jira.spring.io/browse/BATCH-1507}[BATCH-1507]}} - FlowJob.getStep() only looks at state names, not step names - - * {{{http://jira.spring.io/browse/BATCH-1510}[BATCH-1510]}} - List of stepnames incomplete for nested flow job - - * {{{http://jira.spring.io/browse/BATCH-1513}[BATCH-1513]}} - HibernateItemReaderHelper requires queryProvider field to be an instance of AbstractHibernateQueryProvider - - * {{{http://jira.spring.io/browse/BATCH-1522}[BATCH-1522]}} - Intermittent failure of FaultTolerantStepFactoryBean in multi-threaded test - - * {{{http://jira.spring.io/browse/BATCH-1525}[BATCH-1525]}} - ExitStatus description can be null when re-hyrated from Oracle - - * {{{http://jira.spring.io/browse/BATCH-1526}[BATCH-1526]}} - Memory leak in web deployments because ThreadLocal is not nulled out in ChunkMonitor - - * {{{http://jira.spring.io/browse/BATCH-1528}[BATCH-1528]}} - Namespace context partition element requires bean with name "transactionManager" - - * {{{http://jira.spring.io/browse/BATCH-1533}[BATCH-1533]}} - API change and is not reflected in API and documentation examples - - * {{{http://jira.spring.io/browse/BATCH-1540}[BATCH-1540]}} - Typo in the user guide: "directlory" - - * {{{http://jira.spring.io/browse/BATCH-1542}[BATCH-1542]}} - Thread safety in JobExecution and StepExecution collections - - * {{{http://jira.spring.io/browse/BATCH-1545}[BATCH-1545]}} - FlatFileItemWriter logs as JdbcBatchItemWriter - - * {{{http://jira.spring.io/browse/BATCH-1546}[BATCH-1546]}} - Some issues with pagination in Oracle - - * {{{http://jira.spring.io/browse/BATCH-1547}[BATCH-1547]}} - ExecutionContextPromotionListener strict flag misinterpreted in listener code - - * {{{http://jira.spring.io/browse/BATCH-1551}[BATCH-1551]}} - Db2PagingQueryProvider needs an alias in the jump to subquery - - * {{{http://jira.spring.io/browse/BATCH-1552}[BATCH-1552]}} - Typo on Use Case page of website - -* Defect - - * {{{http://jira.spring.io/browse/BATCH-1550}[BATCH-1550]}} - Section 5.2.1 references TaskletAdapter class, but it should be MethodInvokingTaskletAdapter - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1530}[BATCH-1530]}} - Let job-repository assign id to itself by default. - - * {{{http://jira.spring.io/browse/BATCH-1531}[BATCH-1531]}} - Restart of a partitioned Step should not call Partitioner - - * {{{http://jira.spring.io/browse/BATCH-1535}[BATCH-1535]}} - Extend SQL scripts to provide exit code limit of 100 chars - - * {{{http://jira.spring.io/browse/BATCH-1536}[BATCH-1536]}} - Negative skip count in SkipPolicy - - * {{{http://jira.spring.io/browse/BATCH-1537}[BATCH-1537]}} - Modify JdbcPagingItemReader to use startAfterValue on restart - - * {{{http://jira.spring.io/browse/BATCH-1541}[BATCH-1541]}} - Make MapJobRepository work for multi-threaded steps and jobs - - * {{{http://jira.spring.io/browse/BATCH-1553}[BATCH-1553]}} - Restart of partitioned job should prevent starting multiple step execution instances for a partition - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1307}[BATCH-1307]}} - MapJobRepository with multi-threaded parallel steps (split in job) - - * {{{http://jira.spring.io/browse/BATCH-1508}[BATCH-1508]}} - Make ApplicationContext ids unique and identifiable in ClasspathXmlApplicationContextsFactoryBean - - * {{{http://jira.spring.io/browse/BATCH-1527}[BATCH-1527]}} - Add "-stopAll" to CommandLineJobRunner - - * {{{http://jira.spring.io/browse/BATCH-1529}[BATCH-1529]}} - Explicit protection against exceptions in SkipPolicy to prevent infinite loop in RetryTemplate - - * {{{http://jira.spring.io/browse/BATCH-1559}[BATCH-1559]}} - Ability to promote FlowStep execution context to its constituent steps - -* Refactoring - - * {{{http://jira.spring.io/browse/BATCH-1534}[BATCH-1534]}} - JobLauncherTestUtils.setJob should take the interfacetype Job as argument rather than AbstractJob - -* Task - - * {{{http://jira.spring.io/browse/BATCH-1548}[BATCH-1548]}} - XMLStream Documentation Error - diff --git a/src/site/apt/migration/2.1.0.M1-2.1.0.M2.apt b/src/site/apt/migration/2.1.0.M1-2.1.0.M2.apt deleted file mode 100644 index 645a83447..000000000 --- a/src/site/apt/migration/2.1.0.M1-2.1.0.M2.apt +++ /dev/null @@ -1,59 +0,0 @@ -Spring Batch 2.1.0.M2 Release Notes - - -Release Notes - Spring Batch - Version 2.1.0.M2 - -* Sub-task - - * {{{http://jira.spring.io/browse/BATCH-1400}[BATCH-1400]}} - Specify schema location for imports in xsd - - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1401}[BATCH-1401]}} - All inserts of JobId should be of Types.BIGINT - - * {{{http://jira.spring.io/browse/BATCH-1420}[BATCH-1420]}} - Late Binding only happens first time when using inner bean definition with collection property - - * {{{http://jira.spring.io/browse/BATCH-1427}[BATCH-1427]}} - SimpleRetryExceptionHandler treats AbstractStep$FatalException as non-fatal - - * {{{http://jira.spring.io/browse/BATCH-1432}[BATCH-1432]}} - Error in chpt. 7.1 "Multithreaded step" - - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1395}[BATCH-1395]}} - Remove or deprecate old application context creation pattern - - * {{{http://jira.spring.io/browse/BATCH-1398}[BATCH-1398]}} - Initialize ClassPathXmlJobRegistry only after application context is ready - - * {{{http://jira.spring.io/browse/BATCH-1424}[BATCH-1424]}} - Documentation of annotations in section 5.1.11 needs expanding - - * {{{http://jira.spring.io/browse/BATCH-1426}[BATCH-1426]}} - RetryTemplate calls BackOffPolicy even when retry will not occur. - - * {{{http://jira.spring.io/browse/BATCH-1429}[BATCH-1429]}} - Allow DelimitedLineTokenizer to handle malformed file/lines gracefully. - - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1265}[BATCH-1265]}} - Add default value support for Dates in FieldSet - - * {{{http://jira.spring.io/browse/BATCH-1300}[BATCH-1300]}} - Add description element to and - - * {{{http://jira.spring.io/browse/BATCH-1399}[BATCH-1399]}} - Expose StepExecutionAggregator as a strategy interface in PartitionStep - - * {{{http://jira.spring.io/browse/BATCH-1416}[BATCH-1416]}} - Namespace support for max varchar length in execution context and execution daos - - * {{{http://jira.spring.io/browse/BATCH-1421}[BATCH-1421]}} - Add method to get all job names to JobExplorer - - * {{{http://jira.spring.io/browse/BATCH-1428}[BATCH-1428]}} - Add support for lobhandler in job repository name space / factory bean - - * {{{http://jira.spring.io/browse/BATCH-1433}[BATCH-1433]}} - IteratorItemReader - - -* Refactoring - - * {{{http://jira.spring.io/browse/BATCH-1369}[BATCH-1369]}} - Change semantics of @AfterChunk to execute outside transaction - - * {{{http://jira.spring.io/browse/BATCH-1419}[BATCH-1419]}} - Change is-reader-transactional-queue to reader-transactional in - - - diff --git a/src/site/apt/migration/2.1.0.M2-2.1.0.M3.apt b/src/site/apt/migration/2.1.0.M2-2.1.0.M3.apt deleted file mode 100644 index 8d28f288f..000000000 --- a/src/site/apt/migration/2.1.0.M2-2.1.0.M3.apt +++ /dev/null @@ -1,68 +0,0 @@ -Spring Batch 2.1.0.M3 Release Notes - - -Release Notes - Spring Batch - Version 2.1.0.M3 - -* Sub-task - - * {{{http://jira.spring.io/browse/BATCH-1439}[BATCH-1439]}} - Make step names unique inside a job - - * {{{http://jira.spring.io/browse/BATCH-1443}[BATCH-1443]}} - Add JobStep: a Step implementation that executes a Job - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1442}[BATCH-1442]}} - Stopping a job with two parallel steps is only stopping one of the steps - - * {{{http://jira.spring.io/browse/BATCH-1444}[BATCH-1444]}} - ChunkMonitor warning message about stream state is inaccurate - - * {{{http://jira.spring.io/browse/BATCH-1452}[BATCH-1452]}} - Stream closed exception when combining MultiResourceItemWriter and FlatFileItemWriter with footer callback - - * {{{http://jira.spring.io/browse/BATCH-1453}[BATCH-1453]}} - OraclePagingQueryProvider generates wrong queries for pages - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-509}[BATCH-509]}} - Add support for dates in ExecutionContext - - * {{{http://jira.spring.io/browse/BATCH-981}[BATCH-981]}} - Use Woodstox instead of ref impl of StaX - - * {{{http://jira.spring.io/browse/BATCH-1281}[BATCH-1281]}} - Make ItemProcessor semantics optionally non-transactional and run-once - - * {{{http://jira.spring.io/browse/BATCH-1316}[BATCH-1316]}} - JobParameters throws NullPointerException on missing key - - * {{{http://jira.spring.io/browse/BATCH-1434}[BATCH-1434]}} - Corner case: job with step that repeats via a transition in a flow only executes the step once - - * {{{http://jira.spring.io/browse/BATCH-1448}[BATCH-1448]}} - BeanWrapperFieldSetMapper should throw BindException (so the errors can be accessed) - - * {{{http://jira.spring.io/browse/BATCH-1449}[BATCH-1449]}} - Option to disable transactional behavior of FlatFileItemWriter - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1246}[BATCH-1246]}} - Add support for a JSON Reader from text files which are JSON formatted - - * {{{http://jira.spring.io/browse/BATCH-1344}[BATCH-1344]}} - Allow autowired to be disabled in AbstractJobTests - - * {{{http://jira.spring.io/browse/BATCH-1347}[BATCH-1347]}} - Restartable look-ahead (peekable) ItemReader - - * {{{http://jira.spring.io/browse/BATCH-1380}[BATCH-1380]}} - Make a top-level element, so it can be shared or strategised in a job - - * {{{http://jira.spring.io/browse/BATCH-1411}[BATCH-1411]}} - Allow a Job to specify its required JobParameters - - * {{{http://jira.spring.io/browse/BATCH-1436}[BATCH-1436]}} - Allow inner bean for configuration of tasklet - - * {{{http://jira.spring.io/browse/BATCH-1437}[BATCH-1437]}} - Support for CallbackPreferringPlatformTransactionManager (and for native TX in WAS) - - * {{{http://jira.spring.io/browse/BATCH-1446}[BATCH-1446]}} - Add convenience method to ExitStatus for capturing stack trace - - * {{{http://jira.spring.io/browse/BATCH-1447}[BATCH-1447]}} - Ensure that JobLauncher fails a job if the task executor cannot run it - - * {{{http://jira.spring.io/browse/BATCH-1454}[BATCH-1454]}} - Create a standard component that can poll for a step or job finishing - -Refactoring - - * {{{http://jira.spring.io/browse/BATCH-1394}[BATCH-1394]}} - Migrate StepScope to Spring 3.0.0 - - * {{{http://jira.spring.io/browse/BATCH-1450}[BATCH-1450]}} - Make Map Daos store data in instance variables (instead of static) - -* Task - - * {{{http://jira.spring.io/browse/BATCH-1451}[BATCH-1451]}} - Upgrade Hibernate to 3.3 diff --git a/src/site/apt/migration/2.1.0.M3-2.1.0.M4.apt b/src/site/apt/migration/2.1.0.M3-2.1.0.M4.apt deleted file mode 100644 index 38e8c73ff..000000000 --- a/src/site/apt/migration/2.1.0.M3-2.1.0.M4.apt +++ /dev/null @@ -1,36 +0,0 @@ -Spring Batch 2.1.0.M4 Release Notes - - -Release Notes - Spring Batch - Version 2.1.0.M4 - -* Sub-task - - * {{{http://jira.spring.io/browse/BATCH-1456}[BATCH-1456]}} - Detect spring-batch-2.0.xsd and raise an exception in the namespace parsers - - * {{{http://jira.spring.io/browse/BATCH-1458}[BATCH-1458]}} - Add FlowStep: a Step implementation that executes a flow - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1460}[BATCH-1460]}} - Rownum clauses are illegal in DerbyPagingQueryProvider (plus additional fix to Oracle) - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-585}[BATCH-585]}} - Improve coverage of examples of listener implementations in user guide - - * {{{http://jira.spring.io/browse/BATCH-924}[BATCH-924]}} - BeanWrapperFieldSetMapper could create child objects if they are null when needed - - * {{{http://jira.spring.io/browse/BATCH-1259}[BATCH-1259]}} - Ensure that skips in the processor cause items to be reprocessed at most once. - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-992}[BATCH-992]}} - Alternative fault-tolerant step implementation - - * {{{http://jira.spring.io/browse/BATCH-1372}[BATCH-1372]}} - Namespace support for partitioning - - * {{{http://jira.spring.io/browse/BATCH-1407}[BATCH-1407]}} - Integration tests for core (including multi-threaded long running tests) - -* Task - - * {{{http://jira.spring.io/browse/BATCH-834}[BATCH-834]}} - Review stop signal handling at JobExecution - - * {{{http://jira.spring.io/browse/BATCH-1457}[BATCH-1457]}} - remove tiger profile from archetype's pom.xml diff --git a/src/site/apt/migration/2.1.0.M4-2.1.0.RC1.apt b/src/site/apt/migration/2.1.0.M4-2.1.0.RC1.apt deleted file mode 100644 index d1f5883c8..000000000 --- a/src/site/apt/migration/2.1.0.M4-2.1.0.RC1.apt +++ /dev/null @@ -1,97 +0,0 @@ -Spring Batch 2.1.0.RC1 Release Notes - -* Sub-task - - * {{{http://jira.spring.io/browse/BATCH-873}[BATCH-873]}} - Ensure SkipPolicies are generic and extendable - - * {{{http://jira.spring.io/browse/BATCH-929}[BATCH-929]}} - Deferrable Constraints cause unrecoverable errors - - * {{{http://jira.spring.io/browse/BATCH-1382}[BATCH-1382]}} - Publish spring-batch-2.1.xsd - - * {{{http://jira.spring.io/browse/BATCH-1387}[BATCH-1387]}} - Fix validation errors in core and samples - - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1371}[BATCH-1371]}} - Rename spring-batch-2.0.xsd to spring-batch-2.1.xsd - - * {{{http://jira.spring.io/browse/BATCH-1418}[BATCH-1418]}} - Upon job restart, step with FlatFileItemReader doesn't honor skippable-exception-classes - - * {{{http://jira.spring.io/browse/BATCH-1422}[BATCH-1422]}} - HibernateCursorItemReader causes OutOfMemoryError when skipping large sets of data - - * {{{http://jira.spring.io/browse/BATCH-1463}[BATCH-1463]}} - Late binding broken for inner beans with Spring 3. - - * {{{http://jira.spring.io/browse/BATCH-1467}[BATCH-1467]}} - Samples: environment switching does not work on command line (pom typo) - - * {{{http://jira.spring.io/browse/BATCH-1469}[BATCH-1469]}} - org.apache.commons.lang.SerializationException: java.lang.ClassNotFoundException using samples in WebLogic - - * {{{http://jira.spring.io/browse/BATCH-1471}[BATCH-1471]}} - Typo in FaultTolerantStepFactoryBean - - * {{{http://jira.spring.io/browse/BATCH-1473}[BATCH-1473]}} - Components that create application contexts should look for *Aware in the infrastructure beans it copies down to the child context - - * {{{http://jira.spring.io/browse/BATCH-1476}[BATCH-1476]}} - Filter counts too high when write skips happen - - * {{{http://jira.spring.io/browse/BATCH-1477}[BATCH-1477]}} - Allow excludes (as well as includes) in retryable exceptions - - * {{{http://jira.spring.io/browse/BATCH-1482}[BATCH-1482]}} - SaveState default value wrong in reference guide - - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1340}[BATCH-1340]}} - Add Support for Native Queries to Jpa/Hibernate readers - - * {{{http://jira.spring.io/browse/BATCH-1374}[BATCH-1374]}} - Mention the JobRegistryBeanPostProcessor in the reference guide - - * {{{http://jira.spring.io/browse/BATCH-1376}[BATCH-1376]}} - CommandLineJobRunner -restart should accept executionId as parameter. - - * {{{http://jira.spring.io/browse/BATCH-1462}[BATCH-1462]}} - MultiResourceItemReader / delegate should skip directories - - * {{{http://jira.spring.io/browse/BATCH-1464}[BATCH-1464]}} - Allow for use of PersistenceExceptionTranslator on JpaItemWriter - - * {{{http://jira.spring.io/browse/BATCH-1465}[BATCH-1465]}} - Unwrap exceptions in AbstractMethodInvokingDelegator - - * {{{http://jira.spring.io/browse/BATCH-1472}[BATCH-1472]}} - Allow for use of PersistenceExceptionTranslator on JpaItemWriter - - * {{{http://jira.spring.io/browse/BATCH-1478}[BATCH-1478]}} - Add auto registration of StepScope to all the top-level elements in XML - - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-729}[BATCH-729]}} - Supporting stored procedures in an ItemReader - - * {{{http://jira.spring.io/browse/BATCH-1239}[BATCH-1239]}} - Add email-sending item writer - - * {{{http://jira.spring.io/browse/BATCH-1377}[BATCH-1377]}} - StaxEventItemWriter: Handle namespace for the root tag - - * {{{http://jira.spring.io/browse/BATCH-1430}[BATCH-1430]}} - StaxEventItemWriter: Declare additional namespaces at the top-level element - - * {{{http://jira.spring.io/browse/BATCH-1441}[BATCH-1441]}} - BackOffPolicy cannot be set on a parent of an XML (namespaced) 'step' - - * {{{http://jira.spring.io/browse/BATCH-1468}[BATCH-1468]}} - StaxEventItemReader: optionally provide QName or namespace declaration for fragment element - - * {{{http://jira.spring.io/browse/BATCH-1474}[BATCH-1474]}} - Add registry management features to JobLoader - - * {{{http://jira.spring.io/browse/BATCH-1475}[BATCH-1475]}} - Allow a JobParametersValidator to be specified as an inner bean definition (as well as a reference) - - * {{{http://jira.spring.io/browse/BATCH-1479}[BATCH-1479]}} - Make AbstractMethodInvokingDelegate more lax in the types of arguments it accepts - - * {{{http://jira.spring.io/browse/BATCH-1480}[BATCH-1480]}} - Allow method adapter for Tasklet to be configured in namespace - - * {{{http://jira.spring.io/browse/BATCH-1481}[BATCH-1481]}} - Support injection of step-scoped dependencies into unit tests - - * {{{http://jira.spring.io/browse/BATCH-1483}[BATCH-1483]}} - Make the JobParametersValidator instance accessible from the Job interface - - * {{{http://jira.spring.io/browse/BATCH-1484}[BATCH-1484]}} - Add a getter for JobParametersValidator in AbstractJob - - * {{{http://jira.spring.io/browse/BATCH-1486}[BATCH-1486]}} - Add HibernatePagingItemReader - - -* Task - - * {{{http://jira.spring.io/browse/BATCH-724}[BATCH-724]}} - create tests for non-default table prefix - - * {{{http://jira.spring.io/browse/BATCH-1466}[BATCH-1466]}} - Migrate Spring Batch Integration into the Admin project - - * {{{http://jira.spring.io/browse/BATCH-1470}[BATCH-1470]}} - Remove commons-lang dependency - - diff --git a/src/site/apt/migration/2.1.0.RC1-2.1.0.apt b/src/site/apt/migration/2.1.0.RC1-2.1.0.apt deleted file mode 100755 index 4b84bcfd0..000000000 --- a/src/site/apt/migration/2.1.0.RC1-2.1.0.apt +++ /dev/null @@ -1,34 +0,0 @@ -Spring Batch 2.1.0 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1490}[BATCH-1490]}} - StaxEventItemWriter outputs invalid xml if step handling is failed and retried when handling the first chunk of data - - * {{{http://jira.spring.io/browse/BATCH-1494}[BATCH-1494]}} - FetchSize not accessible in HibernateCursorItemReader - - * {{{http://jira.spring.io/browse/BATCH-1497}[BATCH-1497]}} - SqlServerPagingQueryProvider should use an alias for the inner query in a jump-to-item query - - * {{{http://jira.spring.io/browse/BATCH-1498}[BATCH-1498]}} - JdbcPagingItemReader does not apply parameter values correctly on restart - - * {{{http://jira.spring.io/browse/BATCH-1499}[BATCH-1499]}} - SqlServerPagingQueryProvider needs an alias in the jump to subquery - - * {{{http://jira.spring.io/browse/BATCH-1502}[BATCH-1502]}} - HibernatePagingItemReader doesn't close sessions - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1402}[BATCH-1402]}} - MapJobRegistry throws DuplicateJobException when the same job factory instance is registered twice - - * {{{http://jira.spring.io/browse/BATCH-1493}[BATCH-1493]}} - Step listeners detected and invoked twice - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1496}[BATCH-1496]}} - Expose retry-policy in namespace configuration - -* Refactoring - - * {{{http://jira.spring.io/browse/BATCH-1393}[BATCH-1393]}} - Migrate StepScope to Spring 3.0.0 - -* Task - - * {{{http://jira.spring.io/browse/BATCH-1488}[BATCH-1488]}} - Tests and documentation for StoredProcedureItemReader - diff --git a/src/site/apt/migration/2.1.1-2.1.2.apt b/src/site/apt/migration/2.1.1-2.1.2.apt deleted file mode 100644 index 91cab7924..000000000 --- a/src/site/apt/migration/2.1.1-2.1.2.apt +++ /dev/null @@ -1,47 +0,0 @@ -Spring Batch 2.1.2 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1543}[BATCH-1543]}} - OrderedComposite cannot register two items with the same order - - * {{{http://jira.spring.io/browse/BATCH-1558}[BATCH-1558]}} - Error in Programmatic Flow Decisions documentation - - * {{{http://jira.spring.io/browse/BATCH-1564}[BATCH-1564]}} - incorrect apachemq artifactId - - * {{{http://jira.spring.io/browse/BATCH-1566}[BATCH-1566]}} - ExecutionContext.isDirty() is not very accurate - - * {{{http://jira.spring.io/browse/BATCH-1567}[BATCH-1567]}} - When step encounters error saving ExecutionContext it tries to stop the job but fails - - * {{{http://jira.spring.io/browse/BATCH-1571}[BATCH-1571]}} - PostgresPagingQueryProvider generateJumpToItemQuery generates bad SQL - - * {{{http://jira.spring.io/browse/BATCH-1573}[BATCH-1573]}} - End transition states will cause the batch job to finish with an Unknown status if the namespace prefix is used. - - * {{{http://jira.spring.io/browse/BATCH-1574}[BATCH-1574]}} - TaskExecutor configuration ignored in 2.1 namespace for with no - - * {{{http://jira.spring.io/browse/BATCH-1587}[BATCH-1587]}} - DefaultFieldSetFactory is not setting the numberFormat in the enhance() call - - * {{{http://jira.spring.io/browse/BATCH-1588}[BATCH-1588]}} - Job Excecution Listener - XML Namespace parsing fails for methods named different to "beforeJob", "afterJob" - - * {{{http://jira.spring.io/browse/BATCH-1590}[BATCH-1590]}} - OraclePagingQueryProvider.generateJumpToItemQuery generates an incorrect query - - * {{{http://jira.spring.io/browse/BATCH-1591}[BATCH-1591]}} - Documentation: StepListener is a marker interface so it cannot be applied directly to a step - - * {{{http://jira.spring.io/browse/BATCH-1594}[BATCH-1594]}} - StepListenerSupport implements method onErrorInStep which is not declared in any of the implemented interfaces - -* Defect - - * {{{http://jira.spring.io/browse/BATCH-1569}[BATCH-1569]}} - MultiResourceItemReader.getCurrentResource cause java.lang.ArrayIndexOutOfBoundsException when .read() was not called - - * {{{http://jira.spring.io/browse/BATCH-1582}[BATCH-1582]}} - DefaultStepExecutionAggregator can simply ignore null or empty input - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1568}[BATCH-1568]}} - Implement SkipListener in StepListenerSupport - - * {{{http://jira.spring.io/browse/BATCH-1575}[BATCH-1575]}} - Parallel job test case missing in 2.1 - - * {{{http://jira.spring.io/browse/BATCH-1578}[BATCH-1578]}} - Mismatch between JavaDoc and enum elements in BatchStatus - - * {{{http://jira.spring.io/browse/BATCH-1589}[BATCH-1589]}} - Have RunIDIncrementer reuse given parameters - - * {{{http://jira.spring.io/browse/BATCH-1593}[BATCH-1593]}} - XML configuration: p-namespace does not work on inline tasklet bean element diff --git a/src/site/apt/migration/2.1.2-2.1.3.apt b/src/site/apt/migration/2.1.2-2.1.3.apt deleted file mode 100644 index 42c85d85d..000000000 --- a/src/site/apt/migration/2.1.2-2.1.3.apt +++ /dev/null @@ -1,59 +0,0 @@ -Spring Batch 2.1.3 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1572}[BATCH-1572]}} - Step not failing on org.springframework.transaction.UnexpectedRollbackException - - * {{{http://jira.spring.io/browse/BATCH-1579}[BATCH-1579]}} - Problems with null job parameters and late binding - - * {{{http://jira.spring.io/browse/BATCH-1597}[BATCH-1597]}} - DirectPoller only works with timeout in milliseconds - - * {{{http://jira.spring.io/browse/BATCH-1598}[BATCH-1598]}} - JobRepositoryTestUtils delete job execution fails if there is another execution with the same job instance - - * {{{http://jira.spring.io/browse/BATCH-1600}[BATCH-1600]}} - CommandLineJobRunner cannot stop a Job execution that was restarted - - * {{{http://jira.spring.io/browse/BATCH-1601}[BATCH-1601]}} - The "initialized" field in org.springframework.batch.test.DataSourceInitializer shouldn't be static. - - * {{{http://jira.spring.io/browse/BATCH-1602}[BATCH-1602]}} - Empty string JobParameter would be re-hydrated as null by Oracle - - * {{{http://jira.spring.io/browse/BATCH-1603}[BATCH-1603]}} - MultiResourceItemReader infinite read/exception loop after a failed delegate.open() when skip policy is very lax - - * {{{http://jira.spring.io/browse/BATCH-1605}[BATCH-1605]}} - HippyMethodInvoker candidate arguments repeated - - * {{{http://jira.spring.io/browse/BATCH-1615}[BATCH-1615]}} - MultiResourceItemReader infinite read/exception loop after NonTransientDataAccessResourceException - - * {{{http://jira.spring.io/browse/BATCH-1616}[BATCH-1616]}} - A custom partitioner no longer restart the job properly upon failure - - * {{{http://jira.spring.io/browse/BATCH-1618}[BATCH-1618]}} - MultiResourceItemWriter creates an empty file if the number of item to write is a multiple of itemCountLimitPerResource - - * {{{http://jira.spring.io/browse/BATCH-1619}[BATCH-1619]}} - BadSqlGrammarException accessing Executions page with Apache Derby 10.6 datasource - - * {{{http://jira.spring.io/browse/BATCH-1620}[BATCH-1620]}} - FlowStep never fails - - * {{{http://jira.spring.io/browse/BATCH-1621}[BATCH-1621]}} - Add attribute - - * {{{http://jira.spring.io/browse/BATCH-1623}[BATCH-1623]}} - A chunk configured with processor-transactional="true" shouldn't require a retry- or skip-limit - - * {{{http://jira.spring.io/browse/BATCH-1624}[BATCH-1624]}} - Spring Batch Website documentation - fix link to Spring Integration - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-836}[BATCH-836]}} - CompositeItemWriter should also implement ItemStream - - * {{{http://jira.spring.io/browse/BATCH-1531}[BATCH-1531]}} - Restart of a partitioned Step should not call Partitioner - - * {{{http://jira.spring.io/browse/BATCH-1556}[BATCH-1556]}} - JobLauncher sequence diagrams have wrong message (call) labels - - * {{{http://jira.spring.io/browse/BATCH-1604}[BATCH-1604]}} - Update docs to describe use of Unicode characters in JobRepository - - * {{{http://jira.spring.io/browse/BATCH-1608}[BATCH-1608]}} - Javadocs: declare that readDate might throw NullPointerException when value is empty - - * {{{http://jira.spring.io/browse/BATCH-1609}[BATCH-1609]}} - Javadocs: DefaultFieldSet.readAndTrim does not throw a NullPointerException as stated by the Javadoc - - * {{{http://jira.spring.io/browse/BATCH-1614}[BATCH-1614]}} - More informative log message for ClassPathXmlApplicationContextFactory.ResourceXmlApplicationContext - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1495}[BATCH-1495]}} - Detect possible overrun and memory issues when skip limit is not reached but reader skips so many records that the chunk never completes - - * {{{http://jira.spring.io/browse/BATCH-1622}[BATCH-1622]}} - Support transaction propagation properly in ResourcelessTransactionManager diff --git a/src/site/apt/migration/2.1.3-2.1.4.apt b/src/site/apt/migration/2.1.3-2.1.4.apt deleted file mode 100644 index 85d80c7cd..000000000 --- a/src/site/apt/migration/2.1.3-2.1.4.apt +++ /dev/null @@ -1,55 +0,0 @@ -Spring Batch 2.1.4 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1572}[BATCH-1572]}} - Step not failing on org.springframework.transaction.UnexpectedRollbackException - - * {{{http://jira.spring.io/browse/BATCH-1632}[BATCH-1632]}} - DefaultFieldSet#readBigDecimal(String, BigDecimal) and NumberFormatException - - * {{{http://jira.spring.io/browse/BATCH-1633}[BATCH-1633]}} - Dependency injection problem with step scoped anonymous inner bean - - * {{{http://jira.spring.io/browse/BATCH-1637}[BATCH-1637]}} - OraclePagingQueryProvider adds an extra column to the jump to page query - - * {{{http://jira.spring.io/browse/BATCH-1638}[BATCH-1638]}} - Possible NullPointerException when using no-rollback - - * {{{http://jira.spring.io/browse/BATCH-1639}[BATCH-1639]}} - Oracle jumpToItemQuery needs a tweak (again) - - * {{{http://jira.spring.io/browse/BATCH-1640}[BATCH-1640]}} - File writers do not behave correctly on rollback - - * {{{http://jira.spring.io/browse/BATCH-1643}[BATCH-1643]}} - Unpredictable binding in BeanWrapperFieldSetMapper because of "fuzzy" property matching - - * {{{http://jira.spring.io/browse/BATCH-1647}[BATCH-1647]}} - Inner bean with a late binding parameter in the constructor does not work - - * {{{http://jira.spring.io/browse/BATCH-1648}[BATCH-1648]}} - Paging query for IbatisPagingItemReader in reference documentation is incorrect - - - -* Defect - - - * {{{http://jira.spring.io/browse/BATCH-1629}[BATCH-1629]}} - FaultTolerantChunkProcessor contains dangerous log statements - - * {{{http://jira.spring.io/browse/BATCH-1631}[BATCH-1631]}} - Typos on Spring Batch home page - - - -* Improvement - - - * {{{http://jira.spring.io/browse/BATCH-1627}[BATCH-1627]}} - SpringValidator - include Binding Results with the thrown ValidationException - - * {{{http://jira.spring.io/browse/BATCH-1630}[BATCH-1630]}} - Add defensive logging conditionals in performance critical areas of the code base. - - * {{{http://jira.spring.io/browse/BATCH-1634}[BATCH-1634]}} - Documentation: custom tableprefix for JobExplorer - - * {{{http://jira.spring.io/browse/BATCH-1636}[BATCH-1636]}} - AutomaticJobRegistar should implement the Ordered interface - - * {{{http://jira.spring.io/browse/BATCH-1650}[BATCH-1650]}} - Override GroupAwareJob#toString method - - - -* New Feature - - - * {{{http://jira.spring.io/browse/BATCH-1628}[BATCH-1628]}} - Add job parameters via properties file in CommandLineJobRunner - diff --git a/src/site/apt/migration/2.1.4-2.1.5.apt b/src/site/apt/migration/2.1.4-2.1.5.apt deleted file mode 100644 index d61b804e1..000000000 --- a/src/site/apt/migration/2.1.4-2.1.5.apt +++ /dev/null @@ -1,5 +0,0 @@ -Spring Batch 2.1.5 Release Notes - -* Bug - - * {{{https://jira.spring.io/browse/BATCH-1683}[BATCH-1683]}} - CommandLineJobRunner hangs waiting for input on stdin diff --git a/src/site/apt/migration/2.1.5-2.1.6.apt b/src/site/apt/migration/2.1.5-2.1.6.apt deleted file mode 100644 index eba3c1c11..000000000 --- a/src/site/apt/migration/2.1.5-2.1.6.apt +++ /dev/null @@ -1,54 +0,0 @@ -Spring Batch 2.1.6 Release Notes - -* Sub-task - - * {{{https://jira.spring.io/browse/BATCH-1672}[BATCH-1672]}} - When appendAllowed is true, file is not created (in the first time). - - * {{{https://jira.spring.io/browse/BATCH-1687}[BATCH-1687]}} - Fix documentation for Step Listeners - - * {{{https://jira.spring.io/browse/BATCH-1688}[BATCH-1688]}} - Add to and - -* Bug - - * {{{https://jira.spring.io/browse/BATCH-1635}[BATCH-1635]}} - Spring Batch and Hibernate Search do not work together - - * {{{https://jira.spring.io/browse/BATCH-1654}[BATCH-1654]}} - StepExecution.equals() should consider id as well as name and jobExecution - - * {{{https://jira.spring.io/browse/BATCH-1656}[BATCH-1656]}} - Infinite loop on no-rollback-for exception when skipLimit is reached due to exception in ItemProcessor - - * {{{https://jira.spring.io/browse/BATCH-1657}[BATCH-1657]}} - ORDER BY clause missing from paging queries for Derby - - * {{{https://jira.spring.io/browse/BATCH-1659}[BATCH-1659]}} - FileUtils setUpOutputFile fails on NAS from linux - - * {{{https://jira.spring.io/browse/BATCH-1670}[BATCH-1670]}} - Nested splits lead to invalid flow definition - - * {{{https://jira.spring.io/browse/BATCH-1671}[BATCH-1671]}} - static methods are not public in ExecutionContextTestUtils - - * {{{https://jira.spring.io/browse/BATCH-1680}[BATCH-1680]}} - Simple cli sample hangs because of wrong dependency - - * {{{https://jira.spring.io/browse/BATCH-1681}[BATCH-1681]}} - Restarting a job that generates XML output using StaxEventItemWriter with Woodstox fails - -* Defect - - * {{{https://jira.spring.io/browse/BATCH-1677}[BATCH-1677]}} - Error Documentation in pointcut expression declaration - - * {{{https://jira.spring.io/browse/BATCH-1678}[BATCH-1678]}} - Inheriting from a Parent Job - -* Improvement - - * {{{https://jira.spring.io/browse/BATCH-1661}[BATCH-1661]}} - FlatFileItemReader always logs as ERROR non data lines even though the row should be skipped - - * {{{https://jira.spring.io/browse/BATCH-1662}[BATCH-1662]}} - FieldSetFactory inconsistent parameter ordering create method - - * {{{https://jira.spring.io/browse/BATCH-1665}[BATCH-1665]}} - Provide MultiResourceItemReader property controlling whether or not it fails when there are "no resources to read" - - * {{{https://jira.spring.io/browse/BATCH-1668}[BATCH-1668]}} - Check for existing transaction when job is started (and fail if present by default) - -* New Feature - - * {{{https://jira.spring.io/browse/BATCH-1224}[BATCH-1224]}} - Appending functionality in FlatFileItemwriter - - * {{{https://jira.spring.io/browse/BATCH-1509}[BATCH-1509]}} - Allow a step inside a partition to be specified as an inner bean definition (as well as a reference) - - * {{{https://jira.spring.io/browse/BATCH-1514}[BATCH-1514]}} - Support for the tag in the partition element - diff --git a/src/site/apt/migration/2.1.6-2.1.7.apt b/src/site/apt/migration/2.1.6-2.1.7.apt deleted file mode 100644 index eaf0c8653..000000000 --- a/src/site/apt/migration/2.1.6-2.1.7.apt +++ /dev/null @@ -1,36 +0,0 @@ -Spring Batch 2.1.7 Release Notes - -* Bug - - - * {{{https://jira.spring.io/browse/BATCH-1705}[BATCH-1705]}} - CommandLineJobRunner fails if standard input not available - - * {{{https://jira.spring.io/browse/BATCH-1707}[BATCH-1707]}} - MapJobInstanceDao.getJobInstances(String jobName, int start, int count) does not work - - * {{{https://jira.spring.io/browse/BATCH-1709}[BATCH-1709]}} - BeanWrapperFieldSetMapper race condition in cache - - * {{{https://jira.spring.io/browse/BATCH-1712}[BATCH-1712]}} - Inline step definitions clash if multiple instances share a TaskExecutorPartitionHandler - - * {{{https://jira.spring.io/browse/BATCH-1717}[BATCH-1717]}} - Failure in RetryPolicy leads to infinite loop in Step - -* Improvement - - - * {{{https://jira.spring.io/browse/BATCH-1693}[BATCH-1693]}} - Add RemoteStepExecutionAggregator to update step executions from the repository during partition processing - - * {{{https://jira.spring.io/browse/BATCH-1713}[BATCH-1713]}} - The step execution context is not deserialized by default and no API to do it effectively - -* New Feature - - - * {{{https://jira.spring.io/browse/BATCH-1396}[BATCH-1396]}} - Late binding of commit-interval, retry-limit, skip-limit, e.g. bound from job parameters. - - * {{{https://jira.spring.io/browse/BATCH-1696}[BATCH-1696]}} - DelimitedLineTokenizer always trims the input data - - * {{{https://jira.spring.io/browse/BATCH-1708}[BATCH-1708]}} - Inefficient (and unnecessary?) locking in TaskletStep and CompositeItemStream - -* Refactoring - - - * {{{https://jira.spring.io/browse/BATCH-1532}[BATCH-1532]}} - Use Spring 3.0 OXM instead of SWS 1.5 - diff --git a/src/site/apt/migration/2.1.7-2.1.8.apt b/src/site/apt/migration/2.1.7-2.1.8.apt deleted file mode 100644 index dd0fe3e3e..000000000 --- a/src/site/apt/migration/2.1.7-2.1.8.apt +++ /dev/null @@ -1,39 +0,0 @@ -Spring Batch 2.1.8 Release Notes - - -* Bug - - * {{{https://jira.spring.io/browse/BATCH-1725}[BATCH-1725]}} - SubclassClassifier should use ConcurrentHashMap - - * {{{https://jira.spring.io/browse/BATCH-1727}[BATCH-1727]}} - Child contexts created by AutomaticJobRegistrar cannot easily use PropertyPlaceholderConfigurer - - * {{{https://jira.spring.io/browse/BATCH-1738}[BATCH-1738]}} - StaxEventItemReader stops reading when exception occurs during unmarshalling - - * {{{https://jira.spring.io/browse/BATCH-1739}[BATCH-1739]}} - Inheriting from parent step with skip-limit/retry-limit causes IllegalArgumentException when the inheriting bean doesn't define exception-classes. - - * {{{https://jira.spring.io/browse/BATCH-1742}[BATCH-1742]}} - HippyMethodInvoker fails when target uses method overloading and there is no exact match for arguments - - * {{{https://jira.spring.io/browse/BATCH-1743}[BATCH-1743]}} - Use step scope for PartitionHandler (so gridSize can be a job parameter) - broken in 2.1.7. - - * {{{https://jira.spring.io/browse/BATCH-1744}[BATCH-1744]}} - Revert retry-limit and skip-limit changes from BATCH-1396. - -* Improvement - - * {{{https://jira.spring.io/browse/BATCH-1316}[BATCH-1316]}} - JobParameters throws NullPointerException on missing key - - * {{{https://jira.spring.io/browse/BATCH-1719}[BATCH-1719]}} - The step execution context is not deserialized for getJobExecutions() and findRunningJobExecutions() - - * {{{https://jira.spring.io/browse/BATCH-1721}[BATCH-1721]}} - Replace + inside of StringBuilder.append() call in FlatFileItemWriter - - * {{{https://jira.spring.io/browse/BATCH-1722}[BATCH-1722]}} - ExecutionContextUserSupport refers to ItemStream in code and documentation - - * {{{https://jira.spring.io/browse/BATCH-1730}[BATCH-1730]}} - Flow based step cannot be repeated/ restarted within a partition - -* New Feature - - * {{{https://jira.spring.io/browse/BATCH-1737}[BATCH-1737]}} - DelimitedLineTokenizer. Specify which fields from a row you want to read - -* Pruning - - * {{{https://jira.spring.io/browse/BATCH-1741}[BATCH-1741]}} - Update javadoc for HibernateItemWriter - diff --git a/src/site/apt/migration/2.1.8-2.1.9.apt b/src/site/apt/migration/2.1.8-2.1.9.apt deleted file mode 100644 index a44d9ddd4..000000000 --- a/src/site/apt/migration/2.1.8-2.1.9.apt +++ /dev/null @@ -1,81 +0,0 @@ -Spring Batch 2.1.9 Release Notes - -* Bug - - * {{{https://jira.spring.io/browse/BATCH-1751}[BATCH-1751]}} - Not possible to use property-placeholder values in batch-attributes - - * {{{https://jira.spring.io/browse/BATCH-1756}[BATCH-1756]}} - Make round-trip <<>> work for double parameters - - * {{{https://jira.spring.io/browse/BATCH-1761}[BATCH-1761]}} - Only first item in chunk is re-processed on retry of failed write - - * {{{https://jira.spring.io/browse/BATCH-1772}[BATCH-1772]}} - missing closing xml tag in spring batch html user guide: 5.1.1. Configuring a Step - - * {{{https://jira.spring.io/browse/BATCH-1775}[BATCH-1775]}} - Inner beans of same type inside <<<>>> elements with scope ="step" leads to mistaken override of bean definitions - - * {{{https://jira.spring.io/browse/BATCH-1776}[BATCH-1776]}} - Batch Src Build unable to find FoundryLogic.vpp - - * {{{https://jira.spring.io/browse/BATCH-1783}[BATCH-1783]}} - Throwing exceptions inside a ChunkListener results in endless loop - - * {{{https://jira.spring.io/browse/BATCH-1798}[BATCH-1798]}} - MultiResourceItemReader fails on Restart if read() method was not called. - - * {{{https://jira.spring.io/browse/BATCH-1804}[BATCH-1804]}} - Retry does not work if additional exception occurs in the ItemWriter during scan for failure - - * {{{https://jira.spring.io/browse/BATCH-1812}[BATCH-1812]}} - ItemWriteListener does not work as expected, not called when writer runs in "recoverer" - - * {{{https://jira.spring.io/browse/BATCH-1813}[BATCH-1813]}} - BeanWrapperFieldSetMapper properties caching is broken - - * {{{https://jira.spring.io/browse/BATCH-1821}[BATCH-1821]}} - Possible mistake in current batch documentation - - * {{{https://jira.spring.io/browse/BATCH-1822}[BATCH-1822]}} - Job execution marked as STOPPED when exception occurs while committing StepExecution - - * {{{https://jira.spring.io/browse/BATCH-1826}[BATCH-1826]}} - Null pointer exception if optional parameter of type DATE is null - - * {{{https://jira.spring.io/browse/BATCH-1840}[BATCH-1840]}} - job execution continues when step is in status unknown - - * {{{https://jira.spring.io/browse/BATCH-1841}[BATCH-1841]}} - Upgrading to spring batch 2.1.8 causes error in processing xml configuration - - * {{{https://jira.spring.io/browse/BATCH-1848}[BATCH-1848]}} - JdbcPagingItemReader does not support table or column aliases due to sortKey being used in where clause, order by clause and for retrieval of result set column - - * {{{https://jira.spring.io/browse/BATCH-1852}[BATCH-1852]}} - Very quick (lt 1ms) jobs are poorly identified - -* Defect - - * {{{https://jira.spring.io/browse/BATCH-1753}[BATCH-1753]}} - Problems With FlatFileItemWriter: error while trying to restart an execution - -* Improvement - - * {{{https://jira.spring.io/browse/BATCH-1760}[BATCH-1760]}} - JobConfigurationRegistry referenced in MapJobRegistry comments - - * {{{https://jira.spring.io/browse/BATCH-1764}[BATCH-1764]}} - Correct JavaDoc for HibernateItemWriter - - * {{{https://jira.spring.io/browse/BATCH-1769}[BATCH-1769]}} - FlatFileItemReader javadocs - - * {{{https://jira.spring.io/browse/BATCH-1777}[BATCH-1777]}} - org.springframework.batch.core.converter.DefaultJobParametersConverter not safe for use with certain Locales - - * {{{https://jira.spring.io/browse/BATCH-1800}[BATCH-1800]}} - AbstractItemCountingItemStreamItemReader could implement ItemStreamReader interface instead of ItemStream and ItemReader - - * {{{https://jira.spring.io/browse/BATCH-1805}[BATCH-1805]}} - Clarify JavaDoc for JobParametersConverter - - * {{{https://jira.spring.io/browse/BATCH-1806}[BATCH-1806]}} - Javadoc for FlowExecutionStatus - - * {{{https://jira.spring.io/browse/BATCH-1815}[BATCH-1815]}} - RunIdIncrementer goes against java best practices - - * {{{https://jira.spring.io/browse/BATCH-1818}[BATCH-1818]}} - JobInterruptedException should not be logged - - * {{{https://jira.spring.io/browse/BATCH-1830}[BATCH-1830]}} - Don't log the JobInterruptedException when stopping a job - - * {{{https://jira.spring.io/browse/BATCH-1834}[BATCH-1834]}} - allow nested tasklets to be specified in the schema - - * {{{https://jira.spring.io/browse/BATCH-1861}[BATCH-1861]}} - Concurrency Support for in-memory repositories - - * {{{https://jira.spring.io/browse/BATCH-1862}[BATCH-1862]}} - Update README to reflect Maven 3.0 works - - * {{{https://jira.spring.io/browse/BATCH-1867}[BATCH-1867]}} - StaxEventItemWriter should be easier to override - - * {{{https://jira.spring.io/browse/BATCH-1874}[BATCH-1874]}} - provide a regex based line mapper - - * {{{https://jira.spring.io/browse/BATCH-1881}[BATCH-1881]}} - force sync to underlying file system in FlatFileItemWriter and StaxEventItemWriter - -* New Feature - - * {{{https://jira.spring.io/browse/BATCH-1758}[BATCH-1758]}} - Round trip <<>> broken for short Strings in PropertiesConverter diff --git a/src/site/apt/migration/2.1.9-2.2.0.M1.apt b/src/site/apt/migration/2.1.9-2.2.0.M1.apt deleted file mode 100644 index 5933f4830..000000000 --- a/src/site/apt/migration/2.1.9-2.2.0.M1.apt +++ /dev/null @@ -1,106 +0,0 @@ -Spring Batch 2.2.0.M1 Release Notes - -* Bug - - * {{{https://jira.spring.io/browse/BATCH-1697}[BATCH-1697]}} - TaskletStep not marked as FAILED when FlatFileItemWriter fails to append footer - - * {{{https://jira.spring.io/browse/BATCH-1745}[BATCH-1745]}} - XSD inconsistency: allow-start-if-complete is not allowed on non-tasklet step - - * {{{https://jira.spring.io/browse/BATCH-1773}[BATCH-1773]}} - Step-scoped annotation based listener is not called - - * {{{https://jira.spring.io/browse/BATCH-1774}[BATCH-1774]}} - NullPointerException on RepeateTemplate - - * {{{https://jira.spring.io/browse/BATCH-1780}[BATCH-1780]}} - Code exception is masked by a batch exception - - * {{{https://jira.spring.io/browse/BATCH-1795}[BATCH-1795]}} - ExponentialBackOffPolicy and BackOffContext - - * {{{https://jira.spring.io/browse/BATCH-1799}[BATCH-1799]}} - Exception in flush of file output ItemWriters does not abort a step/job - - * {{{https://jira.spring.io/browse/BATCH-1884}[BATCH-1884]}} - JobLauncherIntegrationTests failing - - * {{{https://jira.spring.io/browse/BATCH-1890}[BATCH-1890]}} - Fix broken JDK5 build after Spring 3.1.2 - - * {{{https://jira.spring.io/browse/BATCH-1903}[BATCH-1903]}} - SQL compatibility breakage with HSQL - - * {{{https://jira.spring.io/browse/BATCH-1916}[BATCH-1916]}} - RecordSeparatorPolicy#isEndOfRecord wrong javadoc? - - * {{{https://jira.spring.io/browse/BATCH-1920}[BATCH-1920]}} - Add sample for new AMQPItemReader & Writer - - * {{{https://jira.spring.io/browse/BATCH-1948}[BATCH-1948]}} - StepScope doesn't work properly with proxyTargetClass=true in @Bean definitions - - * {{{https://jira.spring.io/browse/BATCH-1950}[BATCH-1950]}} - Fix bootstrap process - -* Improvement - - * {{{https://jira.spring.io/browse/BATCH-1667}[BATCH-1667]}} - StepExecutionListener ExitStatus not persisted and not accessible for other listeners - - * {{{https://jira.spring.io/browse/BATCH-1691}[BATCH-1691]}} - Allow to define groupBy for SqlPaginingQueryProviderFactoryBean - - * {{{https://jira.spring.io/browse/BATCH-1718}[BATCH-1718]}} - CompositeRetryPolicy by default is pessimistic - - * {{{https://jira.spring.io/browse/BATCH-1854}[BATCH-1854]}} - Create marker interface to be used by MultiResourceItemReader to inject the resource an item was read from. - - * {{{https://jira.spring.io/browse/BATCH-1887}[BATCH-1887]}} - Cleanup maven warnings - - * {{{https://jira.spring.io/browse/BATCH-1889}[BATCH-1889]}} - SqlFire support - - * {{{https://jira.spring.io/browse/BATCH-1891}[BATCH-1891]}} - Migrate usage of deprecated classes - - * {{{https://jira.spring.io/browse/BATCH-1904}[BATCH-1904]}} - Upgrade support of Hibernate to Hibernate 4 - - * {{{https://jira.spring.io/browse/BATCH-1928}[BATCH-1928]}} - Convert deprecated classes from the org.springframework.jdbc.core.simple package in samples - - * {{{https://jira.spring.io/browse/BATCH-1929}[BATCH-1929]}} - Convert deprecated classes from the org.springframework.jdbc.core.simple package in core-tests - - * {{{https://jira.spring.io/browse/BATCH-1931}[BATCH-1931]}} - Convert deprecated classes from the org.springframework.jdbc.core.simple package in infrastructure-tests - -* New Feature - - * {{{https://jira.spring.io/browse/BATCH-1666}[BATCH-1666]}} - Add abort(long executionId) convenience method to JobOperator - - * {{{https://jira.spring.io/browse/BATCH-1667}[BATCH-1667]}} - StepExecutionListener ExitStatus not persisted and not accessible for other listeners - - * {{{https://jira.spring.io/browse/BATCH-1684}[BATCH-1684]}} - Allow serializer to be injected into JobRepository (ExecutionContextDao) - - * {{{https://jira.spring.io/browse/BATCH-1685}[BATCH-1685]}} - Upgrade minimum support level for Spring to 3.1.2 - - * {{{https://jira.spring.io/browse/BATCH-1694}[BATCH-1694]}} - Add StepLocatorStepFactoryBean - - * {{{https://jira.spring.io/browse/BATCH-1714}[BATCH-1714]}} - Change ChunkListener interface and semantics to be called after rollback as well as commit - - * {{{https://jira.spring.io/browse/BATCH-1749}[BATCH-1749]}} - JdbcPagingItemReader query fails when specifying multiple columns in sortKey - - * {{{https://jira.spring.io/browse/BATCH-1869}[BATCH-1869]}} - Need a line tokenizer to parse the line based on string (multi character) delimiter than a single character delimiter - - * {{{https://jira.spring.io/browse/BATCH-1882}[BATCH-1882]}} - AMQP ItemReader and ItemWriter - - * {{{https://jira.spring.io/browse/BATCH-1911}[BATCH-1911]}} - Provide a Step registry to be able to locate a step by its name on (namely) remote nodes - - * {{{https://jira.spring.io/browse/BATCH-1912}[BATCH-1912]}} - Provide a base PartitionHandler so that other implementations can benefit from a shared base implementation - - * {{{https://jira.spring.io/browse/BATCH-1918}[BATCH-1918]}} - @Configuration support for batch (e.g. @EnableBatchProcessing) - - * {{{https://jira.spring.io/browse/BATCH-1935}[BATCH-1935]}} - Add quick start maven archetype - -* Task - - * {{{https://jira.spring.io/browse/BATCH-1883}[BATCH-1883]}} - Bump spring-amqp Version to 1.1.2 - - * {{{https://jira.spring.io/browse/BATCH-1938}[BATCH-1938]}} - Update to support Spring 3.2.0.RELEASE - - * {{{https://jira.spring.io/browse/BATCH-1943}[BATCH-1943]}} - Add ChunkContext to existing ChunkListener methods - -* Refactoring - - * {{{https://jira.spring.io/browse/BATCH-1895}[BATCH-1895]}} - Remove batch retry and depend on spring-retry. - - * {{{https://jira.spring.io/browse/BATCH-1897}[BATCH-1897]}} - Remove ant files from batch. - - * {{{https://jira.spring.io/browse/BATCH-1915}[BATCH-1915]}} - Change minimum compiler level to 1.6 and use @Override everywhere - - * {{{https://jira.spring.io/browse/BATCH-1919}[BATCH-1919]}} - Switch to using namespace in samples - - * {{{https://jira.spring.io/browse/BATCH-1940}[BATCH-1940]}} - Replace org.springframework.batch.support.JdbcTestUtils with org.springframework.test.jdbc.JdbcTestUtils - - * {{{https://jira.spring.io/browse/BATCH-1949}[BATCH-1949]}} - Remove explicit checks for Spring 3 in StepScope - diff --git a/src/site/apt/migration/2.2.0-2.2.1.apt b/src/site/apt/migration/2.2.0-2.2.1.apt deleted file mode 100755 index 40288aa03..000000000 --- a/src/site/apt/migration/2.2.0-2.2.1.apt +++ /dev/null @@ -1,28 +0,0 @@ -Spring Batch 2.2.1 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-1849}[BATCH-1849]}} - Item was not picked up after restarting a failed job!!! - - * {{{http://jira.spring.io/browse/BATCH-1973}[BATCH-1973]}} - processor-transactional="false" in chunk definition does not have stable behavior - - * {{{http://jira.spring.io/browse/BATCH-2036}[BATCH-2036]}} - Output incorrect when using processor-transactional="false" and skips. - - * {{{http://jira.spring.io/browse/BATCH-2038}[BATCH-2038]}} - DerbyPagingQueryProvider does not work with Derby 10.10.1.1 - - * {{{http://jira.spring.io/browse/BATCH-2050}[BATCH-2050]}} - AbstractItemCountingItemStreamItemReader.read() shouldn't be final - - * {{{http://jira.spring.io/browse/BATCH-2054}[BATCH-2054]}} - StaxEventItemWriter fails on a NullPointerException with Spring OXM 3.2.x. - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1984}[BATCH-1984]}} - CompositeItemProcessor.setDelegates argument has limiting generic type - - * {{{http://jira.spring.io/browse/BATCH-2052}[BATCH-2052]}} - StaxEventItemWriter should only force sync once per chunk - - * {{{http://jira.spring.io/browse/BATCH-2069}[BATCH-2069]}} - Relax OSGI dependencies on nosql jars - -* Task - - * {{{http://jira.spring.io/browse/BATCH-2056}[BATCH-2056]}} - Update 'What's New' in Reference Document - diff --git a/src/site/apt/migration/2.2.0.M1-2.2.0.RC1.apt b/src/site/apt/migration/2.2.0.M1-2.2.0.RC1.apt deleted file mode 100644 index 236771225..000000000 --- a/src/site/apt/migration/2.2.0.M1-2.2.0.RC1.apt +++ /dev/null @@ -1,74 +0,0 @@ -Spring Batch 2.2.0.RC1 Release Notes - -* Bug - - * {{{https://jira.spring.io/browse/BATCH-1676}[BATCH-1676]}} - Inconsistencies in XSD and documentation for Listeners within Step - - * {{{https://jira.spring.io/browse/BATCH-1720}[BATCH-1720]}} - Remote steps should not be consulted for isAllowedStartIfComplete() etc. - - * {{{https://jira.spring.io/browse/BATCH-1788}[BATCH-1788]}} - Update chapter 4.5.6 on aborting jobs in documentation - - * {{{https://jira.spring.io/browse/BATCH-1847}[BATCH-1847]}} - scope="step" inheritance from parent bean definitions causes odd effects - - * {{{https://jira.spring.io/browse/BATCH-1856}[BATCH-1856]}} - ExtendedConnectionDataSourceProxy compilation error in JDK 7 - - * {{{https://jira.spring.io/browse/BATCH-1908}[BATCH-1908]}} - Inefficient storage of StepExecutionContexts when using partitioning - - * {{{https://jira.spring.io/browse/BATCH-1924}[BATCH-1924]}} - Restarting a stopped job in COMPLETED state prevents progress - - * {{{https://jira.spring.io/browse/BATCH-1951}[BATCH-1951]}} - StepScoped proxies not being created with proxyMode=TARGET_CLASS - - * {{{https://jira.spring.io/browse/BATCH-1952}[BATCH-1952]}} - Missing Import in spring-batch-infrastructure.jar - - * {{{https://jira.spring.io/browse/BATCH-1757}[BATCH-1757]}} - MinMaxPartitioner sets incorrect max value - - * {{{https://jira.spring.io/browse/BATCH-1959}[BATCH-1959]}} - Problem with FlatFileItemWriter restart using multi-byte encoding - - * {{{https://jira.spring.io/browse/BATCH-1960}[BATCH-1960]}} - drop table not consistent across supported dbs - - * {{{https://jira.spring.io/browse/BATCH-1972}[BATCH-1972]}} - StaxEventItemReader fails when restarted at end of file - - * {{{https://jira.spring.io/browse/BATCH-1975}[BATCH-1975]}} - StaxEventItemWriter namespace added to elements after restart - -* Improvement - - * {{{https://jira.spring.io/browse/BATCH-1723}[BATCH-1723]}} - Change JobParameters to use wrapper types for getLong and getDouble - - * {{{https://jira.spring.io/browse/BATCH-1770}[BATCH-1770]}} - Checking for UNKNOWN step status could be performed before the JobExecution is launched - - * {{{https://jira.spring.io/browse/BATCH-1906}[BATCH-1906]}} - add support to access an item's line number - - * {{{https://jira.spring.io/browse/BATCH-1928}[BATCH-1928]}} - Convert deprecated classes from the org.springframework.jdbc.core.simple package in samples - - * {{{https://jira.spring.io/browse/BATCH-1955}[BATCH-1955]}} - Remove requirement to inject ItemSqlParameterSourceProvider into JdbcBatchItemWriter - - * {{{https://jira.spring.io/browse/BATCH-1957}[BATCH-1957]}} - Add StaxEventItemWriter deleteIfEmpty property - - * {{{https://jira.spring.io/browse/BATCH-1958}[BATCH-1958]}} - Fix typo in samples apt index - -* New Feature - - * {{{https://jira.spring.io/browse/BATCH-1412}[BATCH-1412]}} - Allow a Job to accept JobParameters that do not contribute to its identity - - * {{{https://jira.spring.io/browse/BATCH-1728}[BATCH-1728]}} - Add support for Spring Data (readers and writers) - - * {{{https://jira.spring.io/browse/BATCH-1934}[BATCH-1934]}} - Update spring-batch docs for AmqpItemReader / Writers and use of SQLFire as a db option - - * {{{https://jira.spring.io/browse/BATCH-1964}[BATCH-1964]}} - Optional Transaction in JpaPagingItemReader - -* Task - - * {{{https://jira.spring.io/browse/BATCH-1954}[BATCH-1954]}} - Update documentation for 2.2.0 - - * {{{https://jira.spring.io/browse/BATCH-1968}[BATCH-1968]}} - Upgrade to hsqldb 2.2.9 - - * {{{https://jira.spring.io/browse/BATCH-1977}[BATCH-1977]}} - Create a migration from old schema to new schema - -* Refactoring - - * {{{https://jira.spring.io/browse/BATCH-1939}[BATCH-1939]}} - Minor cleanups to AMQP sample - - * {{{https://jira.spring.io/browse/BATCH-1947}[BATCH-1947]}} - Replace org.easymock.classextension.EasyMock with org.easymock.EasyMock - - * {{{https://jira.spring.io/browse/BATCH-1966}[BATCH-1966]}} - Use abstract classes to inherit behaviors - \ No newline at end of file diff --git a/src/site/apt/migration/2.2.0.RC1-2.2.0.RC2.apt b/src/site/apt/migration/2.2.0.RC1-2.2.0.RC2.apt deleted file mode 100644 index 19457ea79..000000000 --- a/src/site/apt/migration/2.2.0.RC1-2.2.0.RC2.apt +++ /dev/null @@ -1,23 +0,0 @@ -Spring Batch 2.2.0.RC2 Release Notes - -* Bug - - * {{{https://jira.spring.io/browse/BATCH-1787}[BATCH-1787]}} - Don't import provided libs in your compile-configuration in ivy.xml - - * {{{https://jira.spring.io/browse/BATCH-1995}[BATCH-1995]}} - Line ending in multiline delimiter not being processed correctly - - * {{{https://jira.spring.io/browse/BATCH-1996}[BATCH-1996]}} - DelimitedLineTokenizer skips first token if it is empty. - - * {{{https://jira.spring.io/browse/BATCH-2017}[BATCH-2017]}} - Fix typo of the word delegate - - * {{{https://jira.spring.io/browse/BATCH-2019}[BATCH-2019]}} - Support PropertySourcesPlaceholderConfigurer delegation to job contexts - - * {{{https://jira.spring.io/browse/BATCH-2022}[BATCH-2022]}} - Drop script for Postgresql assumes that the tables are there when dropping constraints. - - * {{{https://jira.spring.io/browse/BATCH-2023}[BATCH-2023]}} - @StepScope should default to ScopedProxyMode.TARGET_CLASS - -* Improvement - - * {{{https://jira.spring.io/browse/BATCH-1982}[BATCH-1982]}} - JavaConfig for Spring Batch - Copy-Constructor for CommonStepProperties - - * {{{https://jira.spring.io/browse/BATCH-1993}[BATCH-1993]}} - Update reference manual copyright date diff --git a/src/site/apt/migration/2.2.0.RC2-2.2.0.apt b/src/site/apt/migration/2.2.0.RC2-2.2.0.apt deleted file mode 100755 index 731e34c9d..000000000 --- a/src/site/apt/migration/2.2.0.RC2-2.2.0.apt +++ /dev/null @@ -1,7 +0,0 @@ -Spring Batch 2.2.0 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-2031}[BATCH-2031]}} - Incorrect delimiter detection in DelimitedLineTokenizer - - * {{{http://jira.spring.io/browse/BATCH-2028}[BATCH-2028]}} - Update downloads documentation diff --git a/src/site/apt/migration/2.2.1-2.2.2.apt b/src/site/apt/migration/2.2.1-2.2.2.apt deleted file mode 100755 index 5241ce5f4..000000000 --- a/src/site/apt/migration/2.2.1-2.2.2.apt +++ /dev/null @@ -1,11 +0,0 @@ -Spring Batch 2.2.2 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-2040}[BATCH-2040]}} - Db2PagingQueryProvider creates erroneous Statement in generateJumpToItemQuery - - * {{{http://jira.spring.io/browse/BATCH-2076}[BATCH-2076]}} - FileUtils throws an exception when append is true - - * {{{http://jira.spring.io/browse/BATCH-2086}[BATCH-2086]}} - default writer implementations need public setter for name - - * {{{http://jira.spring.io/browse/BATCH-2096}[BATCH-2096]}} - 'chunk-completion-policy' or 'commit-interval' with '#{jobParameters[...]}' is ignored when 'retry-limit' exists. diff --git a/src/site/apt/migration/2.2.1-3.0.0.M1.apt b/src/site/apt/migration/2.2.1-3.0.0.M1.apt deleted file mode 100755 index c10251380..000000000 --- a/src/site/apt/migration/2.2.1-3.0.0.M1.apt +++ /dev/null @@ -1,60 +0,0 @@ -Spring Batch 3.0.0.M1 Release Notes - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1997}[BATCH-1997]}} - Implement JSR TCK SPI - - * {{{http://jira.spring.io/browse/BATCH-1999}[BATCH-1999]}} - JSR-352 Parsing - - * {{{http://jira.spring.io/browse/BATCH-2000}[BATCH-2000]}} - Parser batch.xml - - * {{{http://jira.spring.io/browse/BATCH-2007}[BATCH-2007]}} - Adapt JSR JobOperator to Spring Batch JobOperator - - * {{{http://jira.spring.io/browse/BATCH-2009}[BATCH-2009]}} - Implement Tasklet.stop() - - * {{{http://jira.spring.io/browse/BATCH-2037}[BATCH-2037]}} - Retry Reads - - * {{{http://jira.spring.io/browse/BATCH-2062}[BATCH-2062]}} - Implement the JSR's CheckpointAlgorithm interface - - * {{{http://jira.spring.io/browse/BATCH-2071}[BATCH-2071]}} - Add Thread Context Class Loading for batch artifacts (JSR-352 section 10.5) - - * {{{http://jira.spring.io/browse/BATCH-2072}[BATCH-2072]}} - Implement JSR's Decider interface - - * {{{http://jira.spring.io/browse/BATCH-2077}[BATCH-2077]}} - Java Config: Register listeners just once - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-2018}[BATCH-2018]}} - TransactionAwareBufferedWriter uses hashcode as TransactionSynchronizationManager key - - * {{{http://jira.spring.io/browse/BATCH-2034}[BATCH-2034]}} - 'Job cannot be null' exception when starting FlowStep remotely with org.springframework.batch.integration.partition.StepExecutionRequestHandler - - * {{{http://jira.spring.io/browse/BATCH-2035}[BATCH-2035]}} - Create parallel to simple-cli for pure Java configuration - - * {{{http://jira.spring.io/browse/BATCH-2067}[BATCH-2067]}} - Fix context management - - * {{{http://jira.spring.io/browse/BATCH-2073}[BATCH-2073]}} - allow-start-if-complete in JSR based job definition is not parsed correctly - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1343}[BATCH-1343]}} - Change JobLauncher.run() to "throws JobExecutionException" - - * {{{http://jira.spring.io/browse/BATCH-1664}[BATCH-1664]}} - MultiResourceItemReader.getCurrentResource() shouldn't be public - - * {{{http://jira.spring.io/browse/BATCH-1811}[BATCH-1811]}} - Javadoc for JdbcBatchItemWriter - - * {{{http://jira.spring.io/browse/BATCH-2043}[BATCH-2043]}} - Update DefaultJobParametersConvereterTests to specify English locale - - * {{{http://jira.spring.io/browse/BATCH-2044}[BATCH-2044]}} - Update SystemCommandTaskletIntegrationTests.java to use ping on windows instead of sleep - -* Task - - * {{{http://jira.spring.io/browse/BATCH-2004}[BATCH-2004]}} - Create wrapper/adapter classes for JSR interfaces - - * {{{http://jira.spring.io/browse/BATCH-2006}[BATCH-2006]}} - Create context implementations - - * {{{http://jira.spring.io/browse/BATCH-2008}[BATCH-2008]}} - Implement JSR's JobExecution, JobInstance and StepExecution interfaces - - - - - diff --git a/src/site/apt/migration/2.2.2-2.2.3.apt b/src/site/apt/migration/2.2.2-2.2.3.apt deleted file mode 100755 index 85ff6a064..000000000 --- a/src/site/apt/migration/2.2.2-2.2.3.apt +++ /dev/null @@ -1,11 +0,0 @@ -Spring Batch 2.2.3 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-2122}[BATCH-2122]}} - Offset not reset when skip limit is hit a chunk boundary - - * {{{http://jira.spring.io/browse/BATCH-2124}[BATCH-2124]}} - Running batch create scripts multiple times can lead to multiple rows being inserted in sequence tables - - * {{{http://jira.spring.io/browse/BATCH-2141}[BATCH-2141]}} - RepositoryItemReader reads the first page twice when used with partitions. - - * {{{http://jira.spring.io/browse/BATCH-2077}[BATCH-2077]}} - Java Config: Register listeners just once. diff --git a/src/site/apt/migration/2.2.3-2.2.4.apt b/src/site/apt/migration/2.2.3-2.2.4.apt deleted file mode 100755 index 9fe43c2bb..000000000 --- a/src/site/apt/migration/2.2.3-2.2.4.apt +++ /dev/null @@ -1,15 +0,0 @@ -Spring Batch 2.2.4 Release Notes - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-2140}[BATCH-2140]}} - Typo in second paragraph of section "4.2. Java Config" on the Reference Documentation - - * {{{http://jira.spring.io/browse/BATCH-2150}[BATCH-2150]}} - Add private constructor to the StepExecution class - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-2148}[BATCH-2148]}} - Cannot create db for MySQL - - * {{{http://jira.spring.io/browse/BATCH-2149}[BATCH-2149]}} - JavaConfig: Registering a ChunkListener twice will result in two ChunkListeners in fault-tolerant mode - - * {{{http://jira.spring.io/browse/BATCH-2151}[BATCH-2151]}} - Skip issues on restart diff --git a/src/site/apt/migration/2.2.4-2.2.5.apt b/src/site/apt/migration/2.2.4-2.2.5.apt deleted file mode 100755 index c3556e88f..000000000 --- a/src/site/apt/migration/2.2.4-2.2.5.apt +++ /dev/null @@ -1,19 +0,0 @@ -Spring Batch 2.2.5 Release Notes - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-1980}[BATCH-1980]}} - Transaction timeout results in step execution status UNKNOWN - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-2153}[BATCH-2153]}} - StepSynchronizationManager uses static HashMap - NullPointerException with multiple Threads - - * {{{http://jira.spring.io/browse/BATCH-2169}[BATCH-2169]}} - @BeforeStep doesn't work when using @StepScope - -* Task - - * {{{http://jira.spring.io/browse/BATCH-2173}[BATCH-2173]}} - Update POM files to reference new repository URLs - - * {{{http://jira.spring.io/browse/BATCH-2180}[BATCH-2180]}} - Clarify: CompositeItemWriter and the need to register streams - - * {{{http://jira.spring.io/browse/BATCH-2181}[BATCH-2181]}} - Backport BATCH-2175 to the 2.2.x branch diff --git a/src/site/apt/migration/2.2.5-2.2.6.apt b/src/site/apt/migration/2.2.5-2.2.6.apt deleted file mode 100755 index 4e238df2d..000000000 --- a/src/site/apt/migration/2.2.5-2.2.6.apt +++ /dev/null @@ -1,43 +0,0 @@ -Spring Batch 2.2.6 Release Notes - -* Improvement - - * {{{http://jira.springsource.org/browse/BATCH-1786}[BATCH-1786]}} - Add convenience method to AbstractJobExplorerFactoryBean - - * {{{http://jira.springsource.org/browse/BATCH-2042}[BATCH-2042]}} - Update docs and expand on role of ItemProcessor especially during a retry - - * {{{http://jira.springsource.org/browse/BATCH-2083}[BATCH-2083]}} - AbstractStep needs to give better exception message - - * {{{http://jira.springsource.org/browse/BATCH-2092}[BATCH-2092]}} - Get input line when by FlatFileFormatException - - * {{{http://jira.springsource.org/browse/BATCH-2185}[BATCH-2185]}} - Provide a way to register listeners in javaconfig that do not implement a listener interface - -* Bug - - * {{{http://jira.springsource.org/browse/BATCH-2011}[BATCH-2011]}} - ExitStatus.compareTo() delivers result out of given range [-1,1] - - * {{{http://jira.springsource.org/browse/BATCH-2059}[BATCH-2059]}} - OrderedComposite.add fails if one of the items is step scope - - * {{{http://jira.springsource.org/browse/BATCH-2060}[BATCH-2060]}} - Wrong Link to Source-Repository on Project Website - - * {{{http://jira.springsource.org/browse/BATCH-2061}[BATCH-2061]}} - State transition causes infinite loop - - * {{{http://jira.springsource.org/browse/BATCH-2085}[BATCH-2085]}} - Attribute 'flow' is not allowed to appear in element 'batch:step' - - * {{{http://jira.springsource.org/browse/BATCH-2106}[BATCH-2106]}} - batch_job_execution_params migration script incorrect value for 'identifying' column - - * {{{http://jira.springsource.org/browse/BATCH-2172}[BATCH-2172]}} - Spring batch fails to autodetect database type DB2ZOS - - * {{{http://jira.springsource.org/browse/BATCH-2186}[BATCH-2186]}} - Backport BATCH-2045 to 2.2.x branch - - * {{{http://jira.springsource.org/browse/BATCH-2189}[BATCH-2189]}} - DefaultBatchConfigurer violates PostConstruct rules - - * {{{http://jira.springsource.org/browse/BATCH-2204}[BATCH-2204]}} - transactional reader does not work since 2.2 - -* Task - - * {{{http://jira.springsource.org/browse/BATCH-2090}[BATCH-2090]}} - HibernateItemWriter: doWrite should not be deprecated - - - - diff --git a/src/site/apt/migration/3.0.0.M1-3.0.0.M2.apt b/src/site/apt/migration/3.0.0.M1-3.0.0.M2.apt deleted file mode 100755 index 8148d93bb..000000000 --- a/src/site/apt/migration/3.0.0.M1-3.0.0.M2.apt +++ /dev/null @@ -1,11 +0,0 @@ -Spring Batch 3.0.0.M2 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-2049}[BATCH-2049]}} - Support multiple fragmentRootElementNames in StaxEventItemReader - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-2077}[BATCH-2077]}} - Java Config: Register listeners just once - - * {{{http://jira.spring.io/browse/BATCH-2089}[BATCH-2089]}} - Add ability to remap exit status on transitions diff --git a/src/site/apt/migration/3.0.0.M2-3.0.0.M3.apt b/src/site/apt/migration/3.0.0.M2-3.0.0.M3.apt deleted file mode 100755 index 3f7b71bc6..000000000 --- a/src/site/apt/migration/3.0.0.M2-3.0.0.M3.apt +++ /dev/null @@ -1,45 +0,0 @@ -Spring Batch 3.0.0.M3 Release Notes - -* Bug - - * {{{http://jira.spring.io/browse/BATCH-2080}[BATCH-2080]}} - Clean up "Invalid JavaBean property 'itemWriter' being accessed" warnings - - * {{{http://jira.spring.io/browse/BATCH-2126}[BATCH-2126]}} - DefaultJobParametersConverter is not thread-safe and the SimpleJobOperator either - - * {{{http://jira.spring.io/browse/BATCH-2179}[BATCH-2179]}} - DefaultJobParametersConverter#getProperties ignores NON_IDENTIFYING_FLAG - -* Improvement - - * {{{http://jira.spring.io/browse/BATCH-2046}[BATCH-2046]}} - StaxEventItemWriter item grouping tag - - * {{{http://jira.spring.io/browse/BATCH-2175}[BATCH-2175]}} - Support DBMS not declared in DatabaseType enum. - -* Task - - * {{{http://jira.spring.io/browse/BATCH-2066}[BATCH-2066]}} - Bump Spring version to 3.2.7.RELEASE - - * {{{http://jira.spring.io/browse/BATCH-2110}[BATCH-2110]}} - Spring 4 - - * {{{http://jira.spring.io/browse/BATCH-2111}[BATCH-2111]}} - Java 8 / Upgrade to Spring 4 - - * {{{http://jira.spring.io/browse/BATCH-2112}[BATCH-2112]}} - Remove Spring Batch's SerializationUtils in favor of the core version. - - * {{{http://jira.spring.io/browse/BATCH-2129}[BATCH-2129]}} - Update iBatis support for Spring 4 - - * {{{http://jira.spring.io/browse/BATCH-2130}[BATCH-2130]}} - Fix XStream error when using Spring 4. - - * {{{http://jira.spring.io/browse/BATCH-2142}[BATCH-2142]}} - Refactor JsrJobOperator to stop/start/restart jobs asynchronously only - - * {{{http://jira.spring.io/browse/BATCH-2174}[BATCH-2174]}} - Execute JSR sigtest - -* New Feature - - * {{{http://jira.spring.io/browse/BATCH-1701}[BATCH-1701]}} - Introduce job scope - - * {{{http://jira.spring.io/browse/BATCH-2003}[BATCH-2003]}} - Tasklet Partitioning - - * {{{http://jira.spring.io/browse/BATCH-2014}[BATCH-2014]}} - Implement JSR Partition Model - - * {{{http://jira.spring.io/browse/BATCH-2063}[BATCH-2063]}} - Implement JSR-352 SkipListener interface - - * {{{http://jira.spring.io/browse/BATCH-2163}[BATCH-2163]}} - Add support for SQLite diff --git a/src/site/apt/migration/index.apt b/src/site/apt/migration/index.apt deleted file mode 100644 index e83304978..000000000 --- a/src/site/apt/migration/index.apt +++ /dev/null @@ -1,119 +0,0 @@ - ------ - Spring Batch Migration Guides - ------ - Dave Syer, Michael Minella - ------ - September 2009 - - See the changes report generated from {{{issue-tracking.html}JIRA}}. - - There is a pre-built {{{http://opensource.atlassian.com/projects/spring/secure/IssueNavigator.jspa?reset=true&mode=hide&pid=10090&status=5&status=6&updated:previous=-1w&sorter/field=updated&sorter/order=DESC}Resolved Recently}} query that might be useful. - - You can also browse the upcoming releases and look at the {{{http://opensource.atlassian.com/projects/spring/browse/BATCH?report=com.atlassian.jira.plugin.system.project:roadmap-panel}Road Map}} query. - - Links: - - * {{{./3.0.0.M2-3.0.0.M3.html}3.0.0.M2-3.0.0.M3}} - - * {{{./3.0.0.M1-3.0.0.M2.html}3.0.0.M1-3.0.0.M2}} - - * {{{./2.2.1-3.0.0.M1.html}2.2.1-3.0.0.M1}} - - * {{{./2.2.5-2.2.6.html}2.2.5-2.2.6}} - - * {{{./2.2.4-2.2.5.html}2.2.4-2.2.5}} - - * {{{./2.2.3-2.2.4.html}2.2.3-2.2.4}} - - * {{{./2.2.2-2.2.3.html}2.2.2-2.2.3}} - - * {{{./2.2.1-2.2.2.html}2.2.1-2.2.2}} - - * {{{./2.2.0-2.2.1.html}2.2.0-2.2.1}} - - * {{{./2.2.0.RC2-2.2.0.html}2.2.0.RC2-2.2.0}} - - * {{{./2.2.0.RC1-2.2.0.RC2.html}2.2.0.RC1-2.2.0.RC2}} - - * {{{./2.2.0.M1-2.2.0.RC1.html}2.2.0.M1-2.2.0.RC1}} - - * {{{./2.1.9-2.2.0.M1.html}2.1.9-2.2.0.M1}} - - * {{{./2.1.8-2.1.9.html}2.1.8 to 2.1.9}} - - * {{{./2.1.7-2.1.8.html}2.1.7 to 2.1.8}} - - * {{{./2.1.6-2.1.7.html}2.1.6 to 2.1.7}} - - * {{{./2.1.5-2.1.6.html}2.1.5 to 2.1.6}} - - * {{{./2.1.4-2.1.5.html}2.1.4 to 2.1.5}} - - * {{{./2.1.3-2.1.4.html}2.1.3 to 2.1.4}} - - * {{{./2.1.2-2.1.3.html}2.1.2 to 2.1.3}} - - * {{{./2.1.1-2.1.2.html}2.1.1 to 2.1.2}} - - * {{{./2.1.0-2.1.1.html}2.1.0 to 2.1.1}} - - * {{{./2.1.0.RC1-2.1.0.html}2.1.0.RC1 to 2.1.0}} - - * {{{./2.1.0.M4-2.1.0.RC1.html}2.1.0.M4 to 2.1.0.RC1}} - - * {{{./2.1.0.M3-2.1.0.M4.html}2.1.0.M3 to 2.1.0.M4}} - - * {{{./2.1.0.M2-2.1.0.M3.html}2.1.0.M2 to 2.1.0.M3}} - - * {{{./2.1.0.M1-2.1.0.M2.html}2.1.0.M1 to 2.1.0.M2}} - - * {{{./2.1.0.M1-2.1.0.M2.html}2.1.0.M1 to 2.1.0.M2}} - - * {{{./2.0.x-2.1.0.M1.html}2.0.x to 2.1.0.M1}} - - * {{{./2.0-highlights.html}Highlights of changes between 1.x and 2.0}} - - * {{{./2.0.3-2.0.4.html}2.0.3.RELEASE to 2.0.4.RELEASE}} - - * {{{./2.0.2-2.0.3.html}2.0.2.RELEASE to 2.0.3.RELEASE}} - - * {{{./2.0.1-2.0.2.html}2.0.1.RELEASE to 2.0.2.RELEASE}} - - * {{{./2.0.0-2.0.1.html}2.0.0.RELEASE to 2.0.1.RELEASE}} - - * {{{./2.0-rc3-release.html}2.0.0.RC3 to 2.0.0.RELEASE}} - - * {{{./2.0-rc2-rc3.html}2.0.0.RC2 to 2.0.0.RC3}} - - * {{{./2.0-rc1-rc2.html}2.0.0.RC1 to 2.0.0.RC2}} - - * {{{./2.0-m4-rc1.html}2.0.0.M4 to 2.0.0.RC1}} - - * {{{./2.0-m3-m4.html}2.0.0.M3 to 2.0.0.M4}} - - * {{{./2.0-m2-m3.html}2.0.0.M2 to 2.0.0.M3}} - - * {{{./2.0-m1-m2.html}2.0.0.M1 to 2.0.0.M2}} - - * {{{./1.1-2.0-m1.html}1.1 to 2.0.0.M1}} - - * {{{./1.1.2-1.1.3.html}1.1.2 to 1.1.3}} - - * {{{./1.1.1-1.1.2.html}1.1.1 to 1.1.2}} - - * {{{./1.1-1.1.1.html}1.1 to 1.1.1}} - - * {{{./1.0.1-1.1.html}1.0.1 to 1.1}} - - * {{{./1.0.0-1.0.1.html}1.0.0 to 1.0.1}} - - * {{{./1.0-rc1-final.html}1.0 rc1 to final}} - - * {{{./1.0-m5-rc1.html}1.0 m5 to rc1}} - - * {{{./1.0-m4-m5.html}1.0 m4 to m5}} - - * {{{./1.0-m3-m4.html}1.0 m3 to m4}} - - * {{{./1.0-m2-m3.html}1.0 m2 to m3}} - diff --git a/src/site/apt/reference/index.apt b/src/site/apt/reference/index.apt deleted file mode 100644 index e42f04ceb..000000000 --- a/src/site/apt/reference/index.apt +++ /dev/null @@ -1,20 +0,0 @@ - ----- - Spring Batch Documentation - ----- - Dave Syer - ----- - Aug 2007 - ----- - -Spring Batch Documentation - - This is the home of the Spring Batch Reference Guide. This is where you can find out how to use Spring Batch and how the pieces fit together. For detailed descriptions of the individual classes in Spring Batch please refer to the {{{../apidocs/index.html}Javadocs}}. There is also a separate section of this web site for the {{{../spring-batch-samples/index.html}Spring Batch Samples}}. If you want to get started quickly that might be a good place to start. - - Use the links below to navigate to the HTML and PDF versions of the guide: - - * {{{./html/index.html}HTML}} format - - * {{{./html-single/index.html}HTML Single Page}} - - * {{{./pdf/spring-batch-docs.pdf}PDF}} format - diff --git a/src/site/apt/scratch.apt b/src/site/apt/scratch.apt deleted file mode 100644 index 6e512936b..000000000 --- a/src/site/apt/scratch.apt +++ /dev/null @@ -1,58 +0,0 @@ - ------ - Spring Batch Scratch - ------ - Dave Syer - ------ - March 2007 - - -+--- - | restore; - | -1 | BATCH(repeat=until exhausted) { - | -2 | RETRY(outer) { - | -3 | TX(datasource=batch) { - | -4 | TX(datasource=business) { - | -5 | BATCH(repeat=5) { - | -6 | RETRY(inner) { -6.1 | input; -7 | } PROCESS { - | output; -8 | } RECOVER { - | recover; - | } - | - | } - | -4.1 | savepoint; - | - | } - | - | } - | - | } - | - | } -+--- - - * The order of the transaction nesting might be important, but only - if they are not XA, and only if there is a partial failure (inner - commits and the outer rolls back), and only if that happens on the - last attempt at RETRY(2). - - * Batch TX is outside business TX so the worse that can happen is - that we might restart from the same point twice (if the inner TX - commits and the outer rolls back). If they were the other way - round the batch savepoint(4.1) could commit and the business - processing (7) roll back - then we would miss the business - processing if the batch had to restart. - - * The savepoint(4.1) needs to be implemented so that the state it - saves is synchronized with the business TX(4). That way if TX(4) - rolls back the savepoint will always be the correct state to - restart if a partial failure is followed by a successful RETRY(2). diff --git a/src/site/apt/sitemap.apt b/src/site/apt/sitemap.apt deleted file mode 100644 index a7bf864a5..000000000 --- a/src/site/apt/sitemap.apt +++ /dev/null @@ -1,120 +0,0 @@ - ------ - Site Map - ------ - Dave Syer - ------ - April 2007 - -Spring Batch Site Map - -* Overview - - * Main Site - high-level information and links to sub-projects - (called "modules" in Maven speak): - - * Docs - reference documentation, user guides - - * Infrastructure - CI build and technical information - - * Integration Tests - reports on tests of infrastructure - - * Core - CI and technical information about core domain - - * Execution - CI and technical information about execution (implementation of core) - -* Main Site - - * Splash page - welcome, mission statement, download links - - * Whitepaper (JavaOne presentation translated to HTML) - - * Occasional Articles (e.g. transactions) - - * Use Cases - - * Project Information (standdard Maven stuff) - - * Developers - - * Source Repository - - * License - - * etc. - -* Documentation - - * Splash page - welcome, links to rest of reference docs. - - * User Guides (docbook, Spring branded reference guides - HTML, HTML - Single Page and PDF). Two choices: one big guide with parts as - listed below, or multiple mini-guides. The former is probably - better. - - Maybe we could also break each of these down a bit more... - - * Infrastructure - How to use the core API - - * Simple Execution Environment - - * Partitioning Execution Environment - - * Other Execution Environments? - - * Changelog - -* Infrastructure - - * Splash page explaining the role of infrastructure, and high level - API packaging. - - * Changelog - - * Project information (duplicated from Main Site - Maven "feature") - - * CI Reports - - * JUnit test report - - * Clover coverage - - * JDepend report - - * Javadocs - -* Integration Tests - - * Changelog - - * Project information (duplicated from Main Site - Maven "feature" - - TODO: find a way to switch them off in sub-projects) - - * CI Reports (same as for infrastructure). - -* Core - - * Changelog - - * Project information (duplicated from Main Site - Maven "feature" - - TODO: find a way to switch them off in sub-projects) - - * CI Reports (same as for infrastructure). - -* Execution - - * Changelog - - * Project information - - * CI Reports (same as for infrastructure). - -* Integration Tests - - * Changelog - - * Project information (duplicated from Main Site - Maven "feature" - - TODO: find a way to switch them off in sub-projects) - - * CI Reports (same as for infrastructure). - - diff --git a/src/site/apt/snapshots.apt b/src/site/apt/snapshots.apt deleted file mode 100644 index 586a26bdc..000000000 --- a/src/site/apt/snapshots.apt +++ /dev/null @@ -1,33 +0,0 @@ - --------- - Snapshots - --------- - Dave Syer, Michael Minella - ------ - August 2007, February 2009 - -Snapshot Builds - - These builds are provided for testing and development purposes only. They are built by a Bamboo process automatically using the latest snapshot from Subversion. - - Snapshots are deployed in Maven Central format every night to the {{{http://s3browse.com/explore/maven.springframework.org/snapshot/org/springframework/batch}SpringSource Maven Repository}}, so use this in your POM (inside a \ element): - -+--- - - spring-s3 - Spring Maven Snapshot Repository - http://s3.amazonaws.com/maven.springframework.org/snapshot - -+--- - - If you are downloading the jar files manually from there you can see the internal and external project dependencies in the <<>> files. You will probably need <<>> and <<>>. - - Individual dependencies can then by added like so (inside a \ element at the top level): - -+--------------- - - org.springframework.batch - spring-batch-core - 3.0.0.BUILD-SNAPSHOT - -+--------------- - diff --git a/src/site/apt/stateful.apt b/src/site/apt/stateful.apt deleted file mode 100644 index 3455085c4..000000000 --- a/src/site/apt/stateful.apt +++ /dev/null @@ -1,161 +0,0 @@ - ------ - Spring Batch - State and Thread Safety - ------ - Dave Syer - ------ - March 2009 - -State and Thread Safety in Spring Batch - - A stateless component is thread safe, but sometimes not practical (you need to store some state). A stateful component can be thread safe, if its contract is clearly explained to and met by its clients. Spring Batch has a lot of stateful components, which by and large are not capable of being used in a thread safe manner, but that doesn't have to be the case for ever. - - Components with private non-final fields are not necessarily stateful in practice - Spring components often have fields that are injected or initialized after the object is created. The working definition of "stateless" for the present purposes is a component with fields that do not change after initialization, which has the usual Spring lifecycle meaning (i.e. once "released into the wild" with <<>>, or the equivalent). - - Conversely, even components with only final fields are not necessarily stateless. They can have the appearance of statelessness (and thread safety), but if they mutate their final fields, then they are stateful by association. It is not always possible to tell from the implementation of a component whether it is stateful by association, since it depends entirely on the implementation of its fields, whose concrete type may not even be known at compile time. - -* Variants of State - - There are two reasons why a Batch component might need to be stateful: rollback and restart. - - * : to support rollback after a transaction, a component might need to detect the rollback (and potentially the start of the original transaction) and rewind to its former state. This is a single-process (JVM) pattern. Normally a transaction is managed on a single thread as well, but in principle there might be multiple threads using the same component, which inevitably leads to problems. - - * : to support restart of a failed job execution, a component needs to be able to re-hydrate its former state from a previour execution. This is often a multi-process (JVM) pattern, and needs to work between processes even if it isn't always invoked that way in practice. To support this requirement Spring Batch uses the <<>> calback methods and its <<>> to store state. The framework deals with the state storage and re-hydration, and components only need to provide snapshots of their state through the <<>> interface. - -* ItemReaders - - The most common case in Batch where stateful components are necessary are the item readers, whose job is to provide instances of business data for processing. At a high level there are three variants, driven by the needs of their client (usually the framework) for rollback and restart. - - * . A fully transactional reader has its rollback and restart state managed entirely by an external system (middleware) that is driven from a transaction in the batch system. After a rollback items are returned to the middleware, and represented in a subsequent transaction. There is no essential difference between rollback and retry: as far as the middleware is concerned they are just failed reads. The user has to tell Spring Batch explicitly if one of these readers is being used so it can take into account the expected re-presentation of items in a new transaction. Just about the only example of this is the <<>>. - - * . A stateless component doesn't need to do anything special to provide restartability, which is quite a valuable feature. It is also thread safe (by construction), which is at least equally valuable if not more. Stateless <<>> are rare in practice: in the Spring Batch source code the only one is the <<>> from the samples. - - * . Part of the contract for <<>> implementations in Batch 2.0 is that <<>> do not need to manage state for rollback because each item is only ever read once (and buffered for use on rollback internally). They do, however still need state if they want to provide restartability, which all the framework implementations do. A stateful component has to work hard to be thread safe, but it is not ruled out in principle. In fact none of the stateful <<>> implementations in Spring Batch is thread safe as of 2.0, but they are all restartable (which is more to the point). - - Because these different categories of <<>> behave differently with respect to rollback and restart, they have to be recognised and treated differently by the framework. If a simple fail fast <<>> is used, then any error leads to immediate failure, so rollback is not important in that case, but restart always is. If a fault tolerant <<>> is used, then rollback and restart have to be handled, and differently for each category of reader. To recognise a reader the framework needs a flag to be set by the user (see <<>>). To recognise a or reader the framework uses the <<>> interface (if present assume ). - -Rollback and Restart with Skips - -* Spring Batch 2.0.0.RC1 - -** Retry and Skip with a Transactional Reader - - Since the middleware will simply re-present failed items, there is nothing for the framework to do. We can use this example to establish some notation. Suppose five items are read in one transaction and there is a deterministic failure while writing the 3rd one. If skips are allowed, but not retries, the process looks like this: - -+--- -[1,2,3,4,5; (1,2,3,4,5)]* -[1,2,3,4,5; (1),(2),(3)]* -[1,2,3,4,5; (1,2,4,5)] -... -+--- - - where parentheses denote a write operation, brackets ([]) represent a transaction, and an asterisk (*) denotes a rollback. In words we have: - - * Read items 1 through 5, then write them as a chunk, encounter an error and rollback. - - * Read items 1 through 5 again and write them individually, scanning for errors. Encounter the error on item 3, then rollback having identified item 3 as skippable - - * Read the 5 items again and skip item 3 on writing the chunk. - - To achieve this, the items from a failed chunk need to be intrinsically identifiable, so that when they show up again the system can throttle back and scan for the error. In completely general terms this is not a well-defined problem - tere is no generic identifier for the items that can always be used. Spring Batch by default uses the items themselves as the identifier in this case, leading to possible problems if their identity (equals and hashCode) are not properly defined. We might be able to pick an identifier in some special cases, like in the JMS case the message ID will be unique, in which case we would need to provide a <<>> implementation. (This is uncommon enough that in Spring Batch 2.0.0 there is no way to do it using the XML namespace, but you can do it using <<>>.) - - There is also the issue of storing the identifiers, waiting for all the failed items to be seen again. There is no guarantee that the failed items will ever come back to this consumer, so we have to store the identifiers potentially indefinitely, possibly leading to memory leaks. To help alleviate this problem (at the risk of misidentifying a failed item as a new one) Spring Batch provides the <<>> which allows cached values to be garabage collected if memory is under pressure. - - With a retry limit of 1, the same execution would look like this - -+--- -[1,2,3,4,5; (1,2,3,4,5)]* -[1,2,3,4,5; (1,2,3,4,5)]* -[1,2,3,4,5; (1),(2),(3)]* -[1,2,3,4,5; (1,2,4,5)] -... -+--- - - (just an extra iteration where the chunk is given a chance to succeed before the error scan starts). - -** Retry and Skip with a Non-Transactional Reader - - In this case there is no middleware so the <<>> has to buffer the items between rollbacks, but otherwise the process looks like very similar. The internal name for the buffer is a <<>>. With no retry: - -+--- -[1,2,3,4,5; (1,2,3,4,5)]* -[; (1),(2),(3)]* -[; (1,2,4,5)] -... -+--- - - and with retry: - -+--- -[1,2,3,4,5; (1,2,3,4,5)]* -[; (1,2,3,4,5)]* -[; (1),(2),(3)]* -[; (1,2,4,5)] -... -+--- - - In the case of the non-Transactional reader there is no problem with item identifiers: the <<>> can be used to identify the failed items when they are re-processed. - -* A More Efficient Approach - - It would be more efficient if we didn't end up processing each item more than twice in the simple case of skip with no retry. - -** Skip with a Transactional Reader - -+--- -[1,2,3,4,5; (1,2,3,4,5)]* -[1; (1)] -[2; (2)] -[3; (3)]* -[4; (4)] -[5; (5)] -... -+--- - - This is difficult to achieve with the <<>> because it requires communication between the <<>> and <<>> about the failed items: the <<>> has to stop reading when it encounters an item from a previously failed chunk. This feature is not yet implemented in Spring Batch (as of 2.0.0.RC2). - -** Skip with a Stateful Reader - -+--- -[1,2,3,4,5; (1,2,3,4,5)]* -[; (1)] -[; (2)] -[; (3)]* -[; (4)] -[; (5)] -... -+--- - - This processing and rollback plan is not difficult to achieve with the <<>> but it hard to get the restart data properly aligned. The main issue is that the <<>> gets the <<>> callback before every commit. It is going to think that all 5 items have been committed after the first (and every) commit, which is wrong, so any subsequent non-skippable failure will lead to a restart on item 6 with all intermediate items lost. So after a fatal error on item 2 the restart would like this - -+--- -[1,2,3,4,5; (1,2,3,4,5)]* -[; (1)] -[; (2)]* - - - -[6,7,8,9,10; (6,7,8,9,10)] -... -+--- - - and items (2,3,4,5) are ommitted with no record of attempting to process them. - - To fix this we have to mask the <<>> callback in the <<>> and only pass it through if we know we have successfully finished a whole chunk. In the partial chunk transactions, we need to update the <<>> with some offset data that would prevent the intermediate values being processed on restart. - -+--- -[1,2,3,4,5; (1,2,3,4,5)]* -[; (1)] -[; (2)]* - - - -[2,3,4,5,6; (2,3,4,5,6)]* -[; (2)] -[; (3)]* -[; (4)] -[; (5)] -[; (6)] -... -+--- - - This can be implemented by storing the offset within a chunk separately from the read count. In the example above, the offset would be 2 when the fatal exception happened, and the read count would be 0 up to the point where the first chunk successfully commits. Caveat: only works if the <<>> is single-threaded (which it has to be for all the existing Stateful readers). The implementation via <<>> assumes that the step is single threaded if it finds that the <<>> is an <<>>, and the <<>> is a <<>>. If the <<>> is concurrent then warnings are logged, and the offset is not stored )the assumption is that the reader is not restartable so it won't care. diff --git a/src/site/docbook/reference/appendix.xml b/src/site/docbook/reference/appendix.xml deleted file mode 100644 index 40b8ff538..000000000 --- a/src/site/docbook/reference/appendix.xml +++ /dev/null @@ -1,314 +0,0 @@ - - - - List of ItemReaders and ItemWriters - -
- Item Readers - - - Available Item Readers - - - - - - - Item Reader - - Description - - - - - - AbstractItemCountingItemStreamItemReader - - Abstract base class that provides basic - restart capabilities by counting the number of items returned from - an ItemReader. - - - - AggregateItemReader - - An ItemReader that delivers a list as its - item, storing up objects from the injected ItemReader until they - are ready to be packed out as a collection. This ItemReader should - mark the beginning and end of records with the constant values in - FieldSetMapper AggregateItemReader#BEGIN_RECORD and - AggregateItemReader#END_RECORD - - - - AmqpItemReader - - Given a Spring AmqpTemplate it provides - synchronous receive methods. The receiveAndConvert() method - lets you receive POJO objects. - - - - FlatFileItemReader - - Reads from a flat file. Includes ItemStream - and Skippable functionality. See section on Read from a - File - - - - HibernateCursorItemReader - - Reads from a cursor based on an HQL query. See - section on Reading from a Database - - - - HibernatePagingItemReader - - Reads from a paginated HQL query - - - - ItemReaderAdapter - - Adapts any class to the - ItemReader interface. - - - - JdbcCursorItemReader - - Reads from a database cursor via JDBC. See - HOWTO - Read from a Database - - - - JdbcPagingItemReader - - Given a SQL statement, pages through the rows, - such that large datasets can be read without running out of - memory - - - - JmsItemReader - - Given a Spring JmsOperations object and a JMS - Destination or destination name to send errors, provides items - received through the injected JmsOperations receive() - method - - - - JpaPagingItemReader - - Given a JPQL statement, pages through the - rows, such that large datasets can be read without running out of - memory - - - - ListItemReader - - Provides the items from a list, one at a - time - - - - MongoItemReader - - Given a MongoOperations object and JSON based MongoDB - query, provides items received from the MongoOperations find method - - - - Neo4jItemReader - - Given a Neo4jOperations object and the components of a - Cyhper query, items are returned as the result of the Neo4jOperations.query - method - - - - RepositoryItemReader - - Given a Spring Data PagingAndSortingRepository object, - a Sort and the name of method to execute, returns items provided by the - Spring Data repository implementation - - - - StoredProcedureItemReader - - Reads from a database cursor resulting from the - execution of a database stored procedure. See HOWTO - Read from a - Database - - - - StaxEventItemReader - - Reads via StAX. See HOWTO - Read from a - File - - - -
-
- -
- Item Writers - - - Available Item Writers - - - - - - - Item Writer - - Description - - - - - - AbstractItemStreamItemWriter - - Abstract base class that combines the - ItemStream and - ItemWriter interfaces. - - - - AmqpItemWriter - - Given a Spring AmqpTemplate it provides - for synchronous send method. The convertAndSend(Object) - method lets you send POJO objects. - - - - CompositeItemWriter - - Passes an item to the process method of each - in an injected List of ItemWriter objects - - - - FlatFileItemWriter - - Writes to a flat file. Includes ItemStream and - Skippable functionality. See section on Writing to a File - - - - GemfireItemWriter - - Using a GemfireOperations object, items wre either written - or removed from the Gemfire instance based on the configuration of the delete - flag - - - - HibernateItemWriter - - This item writer is hibernate session aware - and handles some transaction-related work that a non-"hibernate - aware" item writer would not need to know about and then delegates - to another item writer to do the actual writing. - - - - ItemWriterAdapter - - Adapts any class to the - ItemWriter interface. - - - - JdbcBatchItemWriter - - Uses batching features from a - PreparedStatement, if available, and can - take rudimentary steps to locate a failure during a - flush. - - - - JmsItemWriter - - Using a JmsOperations object, items are written - to the default queue via the JmsOperations.convertAndSend() method - - - - JpaItemWriter - - This item writer is JPA EntityManager aware - and handles some transaction-related work that a non-"jpa aware" - ItemWriter would not need to know about and - then delegates to another writer to do the actual writing. - - - - MimeMessageItemWriter - - Using Spring's JavaMailSender, items of type MimeMessage - are sent as mail messages - - - - MongoItemWriter - - Given a MongoOperations object, items are written - via the MongoOperations.save(Object) method. The actual write is delayed - until the last possible moment before the transaction commits. - - - - Neo4jItemWriter - - Given a Neo4jOperations object, items are persisted via the - save(Object) method or deleted via the delete(Object) per the - ItemWriter's configuration - - - - PropertyExtractingDelegatingItemWriter - - Extends AbstractMethodInvokingDelegator - creating arguments on the fly. Arguments are created by retrieving - the values from the fields in the item to be processed (via a - SpringBeanWrapper) based on an injected array of field - name - - - - RepositoryItemWriter - - Given a Spring Data CrudRepository implementation, - items are saved via the method specified in the configuration. - - - - StaxEventItemWriter - - Uses an ObjectToXmlSerializer implementation to - convert each item to XML and then writes it to an XML file using - StAX. - - - -
-
-
diff --git a/src/site/docbook/reference/common-patterns.xml b/src/site/docbook/reference/common-patterns.xml deleted file mode 100644 index a65422bd7..000000000 --- a/src/site/docbook/reference/common-patterns.xml +++ /dev/null @@ -1,604 +0,0 @@ - - - - Common Batch Patterns - - Some batch jobs can be assembled purely from off-the-shelf components - in Spring Batch. For instance the ItemReader and - ItemWriter implementations can be configured to cover - a wide range of scenarios. However, for the majority of cases, custom code - will have to be written. The main API entry points for application - developers are the Tasklet, - ItemReader, ItemWriter and the - various listener interfaces. Most simple batch jobs will be able to use - off-the-shelf input from a Spring Batch ItemReader, - but it is often the case that there are custom concerns in the processing - and writing, which require developers to implement an - ItemWriter or - ItemProcessor. - - Here, we provide a few examples of common patterns in custom business - logic. These examples primarily feature the listener interfaces. It should - be noted that an ItemReader or - ItemWriter can implement a listener interface as - well, if appropriate. - -
- Logging Item Processing and Failures - - A common use case is the need for special handling of errors in a - step, item by item, perhaps logging to a special channel, or inserting a - record into a database. A chunk-oriented Step - (created from the step factory beans) allows users to implement this use - case with a simple ItemReadListener, for errors on - read, and an ItemWriteListener, for errors on - write. The below code snippets illustrate a listener that logs both read - and write failures: - - public class ItemFailureLoggerListener extends ItemListenerSupport { - - private static Log logger = LogFactory.getLog("item.error"); - - public void onReadError(Exception ex) { - logger.error("Encountered error on read", e); - } - - public void onWriteError(Exception ex, Object item) { - logger.error("Encountered error on write", ex); - } - -} - - Having implemented this listener it must be registered with the - step: - - <step id="simpleStep"> - ... - <listeners> - <listener> - <bean class="org.example...ItemFailureLoggerListener"/> - </listener> - </listeners> -</step> - - Remember that if your listener does anything in an - onError() method, it will be inside a transaction that is - going to be rolled back. If you need to use a transactional resource such - as a database inside an onError() method, consider adding a - declarative transaction to that method (see Spring Core Reference Guide - for details), and giving its propagation attribute the value - REQUIRES_NEW. -
- -
- Stopping a Job Manually for Business Reasons - - Spring Batch provides a stop() method - through the JobLauncher interface, but this is - really for use by the operator rather than the application programmer. - Sometimes it is more convenient or makes more sense to stop a job - execution from within the business logic. - - The simplest thing to do is to throw a - RuntimeException (one that isn't retried - indefinitely or skipped). For example, a custom exception type could be - used, as in the example below: - - public class PoisonPillItemWriter implements ItemWriter<T> { - - public void write(T item) throws Exception { - if (isPoisonPill(item)) { - throw new PoisonPillException("Posion pill detected: " + item); - } - } - -} - - Another simple way to stop a step from executing is to simply return - null from the ItemReader: - - public class EarlyCompletionItemReader implements ItemReader<T> { - - private ItemReader<T> delegate; - - public void setDelegate(ItemReader<T> delegate) { ... } - - public T read() throws Exception { - T item = delegate.read(); - if (isEndItem(item)) { - return null; // end the step here - } - return item; - } - -} - - The previous example actually relies on the fact that there is a - default implementation of the CompletionPolicy - strategy which signals a complete batch when the item to be processed is - null. A more sophisticated completion policy could be implemented and - injected into the Step through the - SimpleStepFactoryBean: - - <step id="simpleStep"> - <tasklet> - <chunk reader="reader" writer="writer" commit-interval="10" - chunk-completion-policy="completionPolicy"/> - </tasklet> -</step> - -<bean id="completionPolicy" class="org.example...SpecialCompletionPolicy"/> - - An alternative is to set a flag in the - StepExecution, which is checked by the - Step implementations in the framework in between - item processing. To implement this alternative, we need access to the - current StepExecution, and this can be achieved by - implementing a StepListener and registering it with - the Step. Here is an example of a listener that - sets the flag: - - public class CustomItemWriter extends ItemListenerSupport implements StepListener { - - private StepExecution stepExecution; - - public void beforeStep(StepExecution stepExecution) { - this.stepExecution = stepExecution; - } - - public void afterRead(Object item) { - if (isPoisonPill(item)) { - stepExecution.setTerminateOnly(true); - } - } - -} - - The default behavior here when the flag is set is for the step to - throw a JobInterruptedException. This can be - controlled through the StepInterruptionPolicy, but - the only choice is to throw or not throw an exception, so this is always - an abnormal ending to a job. -
- -
- Adding a Footer Record - - Often when writing to flat files, a "footer" record must be appended - to the end of the file, after all processing has be completed. This can - also be achieved using the FlatFileFooterCallback - interface provided by Spring Batch. The - FlatFileFooterCallback (and its counterpart, the - FlatFileHeaderCallback) are optional properties of - the FlatFileItemWriter: - - <bean id="itemWriter" class="org.spr...FlatFileItemWriter"> - <property name="resource" ref="outputResource" /> - <property name="lineAggregator" ref="lineAggregator"/> - <property name="headerCallback" ref="headerCallback" /> - <property name="footerCallback" ref="footerCallback" /> -</bean> - - The footer callback interface is very simple. It has just one method - that is called when the footer must be written: - - public interface FlatFileFooterCallback { - - void writeFooter(Writer writer) throws IOException; - -} - -
- Writing a Summary Footer - - A very common requirement involving footer records is to aggregate - information during the output process and to append this information to - the end of the file. This footer serves as a summarization of the file - or provides a checksum. - - For example, if a batch job is writing - Trade records to a flat file, and there is a - requirement that the total amount from all the - Trades is placed in a footer, then the following - ItemWriter implementation can be used: - - public class TradeItemWriter implements ItemWriter<Trade>, - FlatFileFooterCallback { - - private ItemWriter<Trade> delegate; - - private BigDecimal totalAmount = BigDecimal.ZERO; - - public void write(List<? extends Trade> items) { - BigDecimal chunkTotal = BigDecimal.ZERO; - for (Trade trade : items) { - chunkTotal = chunkTotal.add(trade.getAmount()); - } - - delegate.write(items); - - // After successfully writing all items - totalAmount = totalAmount.add(chunkTotal); - } - - public void writeFooter(Writer writer) throws IOException { - writer.write("Total Amount Processed: " + totalAmount); - } - - public void setDelegate(ItemWriter delegate) {...} -} - - This TradeItemWriter stores a - totalAmount value that is increased with the - amount from each Trade item written. - After the last Trade is processed, the framework - will call writeFooter, which will put that - totalAmount into the file. Note that the - write method makes use of a temporary variable, - chunkTotalAmount, that stores the total of the trades - in the chunk. This is done to ensure that if a skip occurs in the - write method, that the - totalAmount will be left unchanged. It is only at - the end of the write method, once we are - guaranteed that no exceptions will be thrown, that we update the - totalAmount. - - In order for the writeFooter method to be - called, the TradeItemWriter (which implements - FlatFileFooterCallback) must be wired into the - FlatFileItemWriter as the - footerCallback: - - <bean id="tradeItemWriter" class="..TradeItemWriter"> - <property name="delegate" ref="flatFileItemWriter" /> -</bean> - -<bean id="flatFileItemWriter" class="org.spr...FlatFileItemWriter"> - <property name="resource" ref="outputResource" /> - <property name="lineAggregator" ref="lineAggregator"/> - <property name="footerCallback" ref="tradeItemWriter" /> -</bean> - - The way that the TradeItemWriter has been - so far will only function correctly if the Step - is not restartable. This is because the class is stateful (since it - stores the totalAmount), but the totalAmount - is not persisted to the database, and therefore, it cannot be retrieved - in the event of a restart. In order to make this class restartable, the - ItemStream interface should be implemented along - with the methods open and - update: - - public void open(ExecutionContext executionContext) { - if (executionContext.containsKey("total.amount") { - totalAmount = (BigDecimal) executionContext.get("total.amount"); - } -} - -public void update(ExecutionContext executionContext) { - executionContext.put("total.amount", totalAmount); -} - - The update method will store the most - current version of totalAmount to the - ExecutionContext just before that object is - persisted to the database. The open method will - retrieve any existing totalAmount from the - ExecutionContext and use it as the starting point - for processing, allowing the TradeItemWriter to - pick up on restart where it left off the previous time the - Step was executed. -
-
- -
- Driving Query Based ItemReaders - - In the chapter on readers and writers, database input using paging - was discussed. Many database vendors, such as DB2, have extremely - pessimistic locking strategies that can cause issues if the table being - read also needs to be used by other portions of the online application. - Furthermore, opening cursors over extremely large datasets can cause - issues on certain vendors. Therefore, many projects prefer to use a - 'Driving Query' approach to reading in data. This approach works by - iterating over keys, rather than the entire object that needs to be - returned, as the following example illustrates: - - - - - - - - - - - - As you can see, this example uses the same 'FOO' table as was used - in the cursor based example. However, rather than selecting the entire - row, only the ID's were selected in the SQL statement. So, rather than a - FOO object being returned from read, an Integer - will be returned. This number can then be used to query for the 'details', - which is a complete Foo object: - - - - - - - - - - - - An ItemProcessor should be used to transform the key obtained from - the driving query into a full 'Foo' object. An existing DAO can be used to - query for the full object based on the key. -
- -
- Multi-Line Records - - While it is usually the case with flat files that one each record is - confined to a single line, it is common that a file might have records - spanning multiple lines with multiple formats. The following excerpt from - a file illustrates this: - - HEA;0013100345;2007-02-15 -NCU;Smith;Peter;;T;20014539;F -BAD;;Oak Street 31/A;;Small Town;00235;IL;US -FOT;2;2;267.34 - - Everything between the line starting with 'HEA' and the line - starting with 'FOT' is considered one record. There are a few - considerations that must be made in order to handle this situation - correctly: - - - - Instead of reading one record at a time, the - ItemReader must read every line of the - multi-line record as a group, so that it can be passed to the - ItemWriter intact. - - - - Each line type may need to be tokenized differently. - - - - Because a single record spans multiple lines, and we may not know - how many lines there are, the ItemReader must be - careful to always read an entire record. In order to do this, a custom - ItemReader should be implemented as a wrapper for - the FlatFileItemReader. - - <bean id="itemReader" class="org.spr...MultiLineTradeItemReader"> - <property name="delegate"> - <bean class="org.springframework.batch.item.file.FlatFileItemReader"> - <property name="resource" value="data/iosample/input/multiLine.txt" /> - <property name="lineMapper"> - <bean class="org.spr...DefaultLineMapper"> - <property name="lineTokenizer" ref="orderFileTokenizer"/> - <property name="fieldSetMapper"> - <bean class="org.spr...PassThroughFieldSetMapper" /> - </property> - </bean> - </property> - </bean> - </property> -</bean> - - To ensure that each line is tokenized properly, which is especially - important for fixed length input, the - PatternMatchingCompositeLineTokenizer can be used - on the delegate FlatFileItemReader. See for more details. The delegate - reader will then use a PassThroughFieldSetMapper to - deliver a FieldSet for each line back to the - wrapping ItemReader. - - <bean id="orderFileTokenizer" class="org.spr...PatternMatchingCompositeLineTokenizer"> - <property name="tokenizers"> - <map> - <entry key="HEA*" value-ref="headerRecordTokenizer" /> - <entry key="FOT*" value-ref="footerRecordTokenizer" /> - <entry key="NCU*" value-ref="customerLineTokenizer" /> - <entry key="BAD*" value-ref="billingAddressLineTokenizer" /> - </map> - </property> -</bean> - - This wrapper will have to be able recognize the end of a record so - that it can continually call read() on its - delegate until the end is reached. For each line that is read, the wrapper - should build up the item to be returned. Once the footer is reached, the - item can be returned for delivery to the - ItemProcessor and - ItemWriter. - - private FlatFileItemReader<FieldSet> delegate; - -public Trade read() throws Exception { - Trade t = null; - - for (FieldSet line = null; (line = this.delegate.read()) != null;) { - String prefix = line.readString(0); - if (prefix.equals("HEA")) { - t = new Trade(); // Record must start with header - } - else if (prefix.equals("NCU")) { - Assert.notNull(t, "No header was found."); - t.setLast(line.readString(1)); - t.setFirst(line.readString(2)); - ... - } - else if (prefix.equals("BAD")) { - Assert.notNull(t, "No header was found."); - t.setCity(line.readString(4)); - t.setState(line.readString(6)); - ... - } - else if (prefix.equals("FOT")) { - return t; // Record must end with footer - } - } - Assert.isNull(t, "No 'END' was found."); - return null; -} -
- -
- Executing System Commands - - Many batch jobs may require that an external command be called from - within the batch job. Such a process could be kicked off separately by the - scheduler, but the advantage of common meta-data about the run would be - lost. Furthermore, a multi-step job would also need to be split up into - multiple jobs as well. - - Because the need is so common, Spring Batch provides a - Tasklet implementation for calling system - commands: - - <bean class="org.springframework.batch.core.step.tasklet.SystemCommandTasklet"> - <property name="command" value="echo hello" /> - <!-- 5 second timeout for the command to complete --> - <property name="timeout" value="5000" /> -</bean> -
- -
- Handling Step Completion When No Input is Found - - In many batch scenarios, finding no rows in a database or file to - process is not exceptional. The Step is simply - considered to have found no work and completes with 0 items read. All of - the ItemReader implementations provided out of the - box in Spring Batch default to this approach. This can lead to some - confusion if nothing is written out even when input is present. (which - usually happens if a file was misnamed, etc) For this reason, the meta - data itself should be inspected to determine how much work the framework - found to be processed. However, what if finding no input is considered - exceptional? In this case, programmatically checking the meta data for no - items processed and causing failure is the best solution. Because this is - a common use case, a listener is provided with just this - functionality: - - public class NoWorkFoundStepExecutionListener extends StepExecutionListenerSupport { - - public ExitStatus afterStep(StepExecution stepExecution) { - if (stepExecution.getReadCount() == 0) { - return ExitStatus.FAILED; - } - return null; - } - -} - - The above StepExecutionListener inspects the - readCount property of the StepExecution during the - 'afterStep' phase to determine if no items were read. If that is the case, - an exit code of FAILED is returned, indicating that the - Step should fail. Otherwise, null is returned, - which will not affect the status of the - Step. -
- -
- Passing Data to Future Steps - - It is often useful to pass information from one step to another. - This can be done using the ExecutionContext. The - catch is that there are two ExecutionContexts: one - at the Step level and one at the - Job level. The Step - ExecutionContext lives only as long as the step - while the Job - ExecutionContext lives through the whole - Job. On the other hand, the - Step ExecutionContext is - updated every time the Step commits a chunk while - the Job ExecutionContext is - updated only at the end of each Step. - - The consequence of this separation is that all data must be placed - in the Step ExecutionContext - while the Step is executing. This will ensure that - the data will be stored properly while the Step is - on-going. If data is stored to the Job - ExecutionContext, then it will not be persisted - during Step execution and if the - Step fails, that data will be lost. - - public class SavingItemWriter implements ItemWriter<Object> { - private StepExecution stepExecution; - - public void write(List<? extends Object> items) throws Exception { - // ... - - ExecutionContext stepContext = this.stepExecution.getExecutionContext(); - stepContext.put("someKey", someObject); - } - - @BeforeStep - public void saveStepExecution(StepExecution stepExecution) { - this.stepExecution = stepExecution; - } -} - - To make the data available to future Steps, - it will have to be "promoted" to the Job - ExecutionContext after the step has finished. - Spring Batch provides the - ExecutionContextPromotionListener for this purpose. - The listener must be configured with the keys related to the data in the - ExecutionContext that must be promoted. It can - also, optionally, be configured with a list of exit code patterns for - which the promotion should occur ("COMPLETED" is the default). As with all - listeners, it must be registered on the - Step. - - <job id="job1"> - <step id="step1"> - <tasklet> - <chunk reader="reader" writer="savingWriter" commit-interval="10"/> - </tasklet> - <listeners> - <listener ref="promotionListener"/> - </listeners> - </step> - - <step id="step2"> - ... - </step> -</job> - -<beans:bean id="promotionListener" class="org.spr....ExecutionContextPromotionListener"> - <beans:property name="keys" value="someKey"/> -</beans:bean> - - Finally, the saved values must be retrieved from the - Job ExeuctionContext: - - public class RetrievingItemWriter implements ItemWriter<Object> { - private Object someObject; - - public void write(List<? extends Object> items) throws Exception { - // ... - } - - @BeforeStep - public void retrieveInterstepData(StepExecution stepExecution) { - JobExecution jobExecution = stepExecution.getJobExecution(); - ExecutionContext jobContext = jobExecution.getExecutionContext(); - this.someObject = jobContext.get("someKey"); - } -} -
-
diff --git a/src/site/docbook/reference/domain.xml b/src/site/docbook/reference/domain.xml deleted file mode 100644 index cab219b5d..000000000 --- a/src/site/docbook/reference/domain.xml +++ /dev/null @@ -1,1068 +0,0 @@ - - - The Domain Language of Batch - - To any experienced batch architect, the overall concepts of batch - processing used in Spring Batch should be familiar and comfortable. There - are "Jobs" and "Steps" and developer supplied processing units called - ItemReaders and ItemWriters. However, because of the Spring patterns, - operations, templates, callbacks, and idioms, there are opportunities for - the following: - - significant improvement in adherence to a clear separation of - concerns - - - - clearly delineated architectural layers and services provided as - interfaces - - - - simple and default implementations that allow for quick adoption - and ease of use out-of-the-box - - - - significantly enhanced extensibility - - - - The diagram below is simplified version of the batch reference - architecture that has been used for decades. It provides an overview of the - components that make up the domain language of batch processing. This - architecture framework is a blueprint that has been proven through decades - of implementations on the last several generations of platforms - (COBOL/Mainframe, C++/Unix, and now Java/anywhere). JCL and COBOL developers - are likely to be as comfortable with the concepts as C++, C# and Java - developers. Spring Batch provides a physical implementation of the layers, - components and technical services commonly found in robust, maintainable - systems used to address the creation of simple to complex batch - applications, with the infrastructure and extensions to address very complex - processing needs. - - - - - - - - - - - Figure 2.1: Batch Stereotypes - - - The diagram above highlights the key concepts that make up the domain - language of batch. A Job has one to many steps, which has exactly one - ItemReader, ItemProcessor, and ItemWriter. A job needs to be launched - (JobLauncher), and meta data about the currently running process needs to be - stored (JobRepository). - -
- Job - - This section describes stereotypes relating to the concept of a - batch job. A Job is an entity that encapsulates an - entire batch process. As is common with other Spring projects, a - Job will be wired together via an XML configuration - file or Java based configuration. This configuration may be referred to as - the "job configuration". However, Job is just the - top of an overall hierarchy: - - - - - - - - - - - - In Spring Batch, a Job is simply a container for Steps. It combines - multiple steps that belong logically together in a flow and allows for - configuration of properties global to all steps, such as restartability. - The job configuration contains: - - - - The simple name of the job - - - - Definition and ordering of Steps - - - - Whether or not the job is restartable - - - - A default simple implementation of the Job - interface is provided by Spring Batch in the form of the - SimpleJob class which creates some standard - functionality on top of Job, however the batch - namespace abstracts away the need to instantiate it directly. Instead, the - <job> tag can be used: - - <job id="footballJob"> - <step id="playerload" next="gameLoad"/> - <step id="gameLoad" next="playerSummarization"/> - <step id="playerSummarization"/> -</job> - -
- JobInstance - - A JobInstance refers to the concept of a - logical job run. Let's consider a batch job that should be run once at - the end of the day, such as the 'EndOfDay' job from the diagram above. - There is one 'EndOfDay' Job, but each individual - run of the Job must be tracked separately. In the - case of this job, there will be one logical - JobInstance per day. For example, there will be a - January 1st run, and a January 2nd run. If the January 1st run fails the - first time and is run again the next day, it is still the January 1st - run. (Usually this corresponds with the data it is processing as well, - meaning the January 1st run processes data for January 1st, etc). - Therefore, each JobInstance can have multiple - executions (JobExecution is discussed in more - detail below) and only one JobInstance - corresponding to a particular Job and - identifying JobParameters can be running at a given - time. - - The definition of a JobInstance has - absolutely no bearing on the data the will be loaded. It is entirely up - to the ItemReader implementation used to - determine how data will be loaded. For example, in the EndOfDay - scenario, there may be a column on the data that indicates the - 'effective date' or 'schedule date' to which the data belongs. So, the - January 1st run would only load data from the 1st, and the January 2nd - run would only use data from the 2nd. Because this determination will - likely be a business decision, it is left up to the - ItemReader to decide. What using the same - JobInstance will determine, however, is whether - or not the 'state' (i.e. the ExecutionContext, - which is discussed below) from previous executions will be used. Using a - new JobInstance will mean 'start from the - beginning' and using an existing instance will generally mean 'start - from where you left off'. -
- -
- JobParameters - - Having discussed JobInstance and how it - differs from Job, the natural question to ask is: - "how is one JobInstance distinguished from - another?" The answer is: JobParameters. - JobParameters is a set of parameters used to - start a batch job. They can be used for identification or even as - reference data during the run: - - - - - - - - - - - - In the example above, where there are two instances, one for - January 1st, and another for January 2nd, there is really only one Job, - one that was started with a job parameter of 01-01-2008 and another that - was started with a parameter of 01-02-2008. Thus, the contract can be - defined as: JobInstance = - Job + identifying JobParameters. This - allows a developer to effectively control how a - JobInstance is defined, since they control what - parameters are passed in. -
- - Not all job parameters are required to contribute to the identification - of a JobInstance. By default they do, however the framework - allows the submission of a Job with parameters that do - not contribute to the identity of a JobInstance as well. - - -
- JobExecution - - A JobExecution refers to the technical - concept of a single attempt to run a Job. An - execution may end in failure or success, but the - JobInstance corresponding to a given execution - will not be considered complete unless the execution completes - successfully. Using the EndOfDay Job described - above as an example, consider a JobInstance for - 01-01-2008 that failed the first time it was run. If it is run again - with the same identifying job parameters as the first run (01-01-2008), a new - JobExecution will be created. However, there will - still be only one JobInstance. - - A Job defines what a job is and how it is - to be executed, and JobInstance is a purely - organizational object to group executions together, primarily to enable - correct restart semantics. A JobExecution, - however, is the primary storage mechanism for what actually happened - during a run, and as such contains many more properties that must be - controlled and persisted: - - - JobExecution Properties - - - - - - - - - status - - A BatchStatus object that - indicates the status of the execution. While running, it's - BatchStatus.STARTED, if it fails, it's BatchStatus.FAILED, and - if it finishes successfully, it's BatchStatus.COMPLETED - - - - startTime - - A java.util.Date representing the - current system time when the execution was started. - - - - endTime - - A java.util.Date representing the - current system time when the execution finished, regardless of - whether or not it was successful. - - - - exitStatus - - The ExitStatus indicating the - result of the run. It is most important because it contains an - exit code that will be returned to the caller. See chapter 5 for - more details. - - - - createTime - - A java.util.Date representing the - current system time when the JobExecution - was first persisted. The job may not have been started yet (and - thus has no start time), but it will always have a createTime, - which is required by the framework for managing job level - ExecutionContexts. - - - - lastUpdated - - A java.util.Date representing the - last time a JobExecution was - persisted. - - - - executionContext - - The 'property bag' containing any user data that needs to - be persisted between executions. - - - - failureExceptions - - The list of exceptions encountered during the execution - of a Job. These can be useful if more - than one exception is encountered during the failure of a - Job. - - - -
- - These properties are important because they will be persisted and - can be used to completely determine the status of an execution. For - example, if the EndOfDay job for 01-01 is executed at 9:00 PM, and fails - at 9:30, the following entries will be made in the batch meta data - tables: - - - BATCH_JOB_INSTANCE - - - - - JOB_INST_ID - - JOB_NAME - - - - 1 - - EndOfDayJob - - - -
- - - BATCH_JOB_EXECUTION_PARAMS - - - - - JOB_EXECUTION_ID - - TYPE_CD - - KEY_NAME - - DATE_VAL - - IDENTIFYING - - - - 1 - - DATE - - schedule.Date - - 2008-01-01 - - TRUE - - - -
- - - BATCH_JOB_EXECUTION - - - - - JOB_EXEC_ID - - JOB_INST_ID - - START_TIME - - END_TIME - - STATUS - - - - 1 - - 1 - - 2008-01-01 21:00 - - 2008-01-01 21:30 - - FAILED - - - -
- - - column names may have been abbreviated or removed for clarity - and formatting - - - Now that the job has failed, let's assume that it took the entire - course of the night for the problem to be determined, so that the 'batch - window' is now closed. Assuming the window starts at 9:00 PM, the job - will be kicked off again for 01-01, starting where it left off and - completing successfully at 9:30. Because it's now the next day, the - 01-02 job must be run as well, which is kicked off just afterwards at - 9:31, and completes in its normal one hour time at 10:30. There is no - requirement that one JobInstance be kicked off - after another, unless there is potential for the two jobs to attempt to - access the same data, causing issues with locking at the database level. - It is entirely up to the scheduler to determine when a - Job should be run. Since they're separate - JobInstances, Spring Batch will make no attempt - to stop them from being run concurrently. (Attempting to run the same - JobInstance while another is already running will - result in a JobExecutionAlreadyRunningException - being thrown). There should now be an extra entry in both the - JobInstance and - JobParameters tables, and two extra entries in - the JobExecution table: - - - BATCH_JOB_INSTANCE - - - - - JOB_INST_ID - - JOB_NAME - - - - 1 - - EndOfDayJob - - - - 2 - - EndOfDayJob - - - -
- - - BATCH_JOB_EXECUTION_PARAMS - - - - - JOB_EXECUTION_ID - - TYPE_CD - - KEY_NAME - - DATE_VAL - - IDENTIFYING - - - - 1 - - DATE - - schedule.Date - - 2008-01-01 00:00:00 - - TRUE - - - - 2 - - DATE - - schedule.Date - - 2008-01-01 00:00:00 - - TRUE - - - - 3 - - DATE - - schedule.Date - - 2008-01-02 00:00:00 - - TRUE - - - -
- - - BATCH_JOB_EXECUTION - - - - - JOB_EXEC_ID - - JOB_INST_ID - - START_TIME - - END_TIME - - STATUS - - - - 1 - - 1 - - 2008-01-01 21:00 - - 2008-01-01 21:30 - - FAILED - - - - 2 - - 1 - - 2008-01-02 21:00 - - 2008-01-02 21:30 - - COMPLETED - - - - 3 - - 2 - - 2008-01-02 21:31 - - 2008-01-02 22:29 - - COMPLETED - - - -
- - - column names may have been abbreviated or removed for clarity - and formatting - -
-
- -
- Step - - A Step is a domain object that encapsulates - an independent, sequential phase of a batch job. Therefore, every - Job is composed entirely of one or more steps. A - Step contains all of the information necessary to - define and control the actual batch processing. This is a necessarily - vague description because the contents of any given - Step are at the discretion of the developer writing - a Job. A Step can be as simple or complex as the - developer desires. A simple Step might load data - from a file into the database, requiring little or no code. (depending - upon the implementations used) A more complex Step - may have complicated business rules that are applied as part of the - processing. As with Job, a - Step has an individual - StepExecution that corresponds with a unique - JobExecution: - - - - - - - - - - - -
- StepExecution - - A StepExecution represents a single attempt - to execute a Step. A new - StepExecution will be created each time a - Step is run, similar to - JobExecution. However, if a step fails to execute - because the step before it fails, there will be no execution persisted - for it. A StepExecution will only be created when - its Step is actually started. - - Step executions are represented by objects of the - StepExecution class. Each execution contains a - reference to its corresponding step and - JobExecution, and transaction related data such - as commit and rollback count and start and end times. Additionally, each - step execution will contain an ExecutionContext, - which contains any data a developer needs persisted across batch runs, - such as statistics or state information needed to restart. The following - is a listing of the properties for - StepExecution: - - - StepExecution Properties - - - - - - - - - status - - A BatchStatus object that - indicates the status of the execution. While it's running, the - status is BatchStatus.STARTED, if it fails, the status is - BatchStatus.FAILED, and if it finishes successfully, the status - is BatchStatus.COMPLETED - - - - startTime - - A java.util.Date representing the - current system time when the execution was started. - - - - endTime - - A java.util.Date representing the - current system time when the execution finished, regardless of - whether or not it was successful. - - - - exitStatus - - The ExitStatus indicating the - result of the execution. It is most important because it - contains an exit code that will be returned to the caller. See - chapter 5 for more details. - - - - executionContext - - The 'property bag' containing any user data that needs to - be persisted between executions. - - - - readCount - - The number of items that have been successfully - read - - - - writeCount - - The number of items that have been successfully - written - - - - commitCount - - The number transactions that have been committed for this - execution - - - - rollbackCount - - The number of times the business transaction controlled - by the Step has been rolled back. - - - - readSkipCount - - The number of times read has - failed, resulting in a skipped item. - - - - processSkipCount - - The number of times process has - failed, resulting in a skipped item. - - - - filterCount - - The number of items that have been 'filtered' by the - ItemProcessor. - - - - writeSkipCount - - The number of times write has - failed, resulting in a skipped item. - - - -
-
-
- -
- ExecutionContext - - An ExecutionContext represents a collection - of key/value pairs that are persisted and controlled by the framework in - order to allow developers a place to store persistent state that is scoped - to a StepExecution or - JobExecution. For those familiar with Quartz, it is - very similar to JobDataMap. The best usage example - is to facilitate restart. Using flat file input as an example, while - processing individual lines, the framework periodically persists the - ExecutionContext at commit points. This allows the - ItemReader to store its state in case a fatal error - occurs during the run, or even if the power goes out. All that is needed - is to put the current number of lines read into the context, and the - framework will do the rest: - - executionContext.putLong(getKey(LINES_READ_COUNT), reader.getPosition()); - - Using the EndOfDay example from the Job Stereotypes section as an - example, assume there's one step: 'loadData', that loads a file into the - database. After the first failed run, the meta data tables would look like - the following: - - - BATCH_JOB_INSTANCE - - - - - JOB_INST_ID - - JOB_NAME - - - - 1 - - EndOfDayJob - - - -
- BATCH_JOB_PARAMS - - - - - JOB_INST_ID - - TYPE_CD - - KEY_NAME - - DATE_VAL - - - - 1 - - DATE - - schedule.Date - - 2008-01-01 - - - -
- BATCH_JOB_EXECUTION - - - - - JOB_EXEC_ID - - JOB_INST_ID - - START_TIME - - END_TIME - - STATUS - - - - 1 - - 1 - - 2008-01-01 21:00 - - 2008-01-01 21:30 - - FAILED - - - -
- BATCH_STEP_EXECUTION - - - - - STEP_EXEC_ID - - JOB_EXEC_ID - - STEP_NAME - - START_TIME - - END_TIME - - STATUS - - - - 1 - - 1 - - loadData - - 2008-01-01 21:00 - - 2008-01-01 21:30 - - FAILED - - - -
- BATCH_STEP_EXECUTION_CONTEXT - - - - - STEP_EXEC_ID - - SHORT_CONTEXT - - - - 1 - - {piece.count=40321} - - - -
In this case, the Step ran for 30 minutes - and processed 40,321 'pieces', which would represent lines in a file in - this scenario. This value will be updated just before each commit by the - framework, and can contain multiple rows corresponding to entries within - the ExecutionContext. Being notified before a - commit requires one of the various StepListeners, - or an ItemStream, which are discussed in more - detail later in this guide. As with the previous example, it is assumed - that the Job is restarted the next day. When it is - restarted, the values from the ExecutionContext of - the last run are reconstituted from the database, and when the - ItemReader is opened, it can check to see if it has - any stored state in the context, and initialize itself from there:
- - if (executionContext.containsKey(getKey(LINES_READ_COUNT))) { - log.debug("Initializing for restart. Restart data is: " + executionContext); - - long lineCount = executionContext.getLong(getKey(LINES_READ_COUNT)); - - LineReader reader = getReader(); - - Object record = ""; - while (reader.getPosition() < lineCount && record != null) { - record = readLine(); - } -} - - In this case, after the above code is executed, the current line - will be 40,322, allowing the Step to start again - from where it left off. The ExecutionContext can - also be used for statistics that need to be persisted about the run - itself. For example, if a flat file contains orders for processing that - exist across multiple lines, it may be necessary to store how many orders - have been processed (which is much different from than the number of lines - read) so that an email can be sent at the end of the - Step with the total orders processed in the body. - The framework handles storing this for the developer, in order to - correctly scope it with an individual JobInstance. - It can be very difficult to know whether an existing - ExecutionContext should be used or not. For - example, using the 'EndOfDay' example from above, when the 01-01 run - starts again for the second time, the framework recognizes that it is the - same JobInstance and on an individual - Step basis, pulls the - ExecutionContext out of the database and hands it - as part of the StepExecution to the - Step itself. Conversely, for the 01-02 run the - framework recognizes that it is a different instance, so an empty context - must be handed to the Step. There are many of these - types of determinations that the framework makes for the developer to - ensure the state is given to them at the correct time. It is also - important to note that exactly one ExecutionContext - exists per StepExecution at any given time. Clients - of the ExecutionContext should be careful because - this creates a shared keyspace, so care should be taken when putting - values in to ensure no data is overwritten. However, the - Step stores absolutely no data in the context, so - there is no way to adversely affect the framework. - - It is also important to note that there is at least one - ExecutionContext per - JobExecution, and one for every - StepExecution. For example, consider the following - code snippet: - - ExecutionContext ecStep = stepExecution.getExecutionContext(); -ExecutionContext ecJob = jobExecution.getExecutionContext(); -//ecStep does not equal ecJob - - As noted in the comment, ecStep will not equal ecJob; they are two - different ExecutionContexts. The one scoped to the - Step will be saved at every commit point in the - Step, whereas the one scoped to the - Job will be saved in between every - Step execution. -
- -
- JobRepository - - JobRepository is the persistence mechanism - for all of the Stereotypes mentioned above. It provides CRUD operations - for JobLauncher, Job, and - Step implementations. When a - Job is first launched, a - JobExecution is obtained from the repository, and - during the course of execution StepExecution and - JobExecution implementations are persisted by - passing them to the repository: - - <job-repository id="jobRepository"/> -
- -
- JobLauncher - - JobLauncher represents a simple interface for - launching a Job with a given set of - JobParameters: - - public interface JobLauncher { - - public JobExecution run(Job job, JobParameters jobParameters) - throws JobExecutionAlreadyRunningException, JobRestartException; -} - - It is expected that implementations will obtain a valid - JobExecution from the - JobRepository and execute the - Job. -
- -
- Item Reader - - ItemReader is an abstraction that represents - the retrieval of input for a Step, one item at a - time. When the ItemReader has exhausted the items - it can provide, it will indicate this by returning null. More details - about the ItemReader interface and its various - implementations can be found in . -
- -
- Item Writer - - ItemWriter is an abstraction that - represents the output of a Step, one batch - or chunk of items at a time. Generally, an item writer has no - knowledge of the input it will receive next, only the item that - was passed in its current invocation. More details about the - ItemWriter interface and its various - implementations can be found in . -
- -
- Item Processor - - ItemProcessor is an abstraction that - represents the business processing of an item. While the - ItemReader reads one item, and the - ItemWriter writes them, the - ItemProcessor provides access to transform or apply - other business processing. If, while processing the item, it is determined - that the item is not valid, returning null indicates that the item should - not be written out. More details about the ItemProcessor interface can be - found in . -
- -
- Batch Namespace - - Many of the domain concepts listed above need to be configured in a - Spring ApplicationContext. While there are - implementations of the interfaces above that can be used in a standard - bean definition, a namespace has been provided for ease of - configuration: - - <beans:beans xmlns="http://www.springframework.org/schema/batch" - xmlns:beans="http://www.springframework.org/schema/beans" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation=" - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans.xsd - http://www.springframework.org/schema/batch - http://www.springframework.org/schema/batch/spring-batch-2.2.xsd"> - - <job id="ioSampleJob"> - <step id="step1"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter" commit-interval="2"/> - </tasklet> - </step> - </job> - -</beans:beans> - - As long as the batch namespace has been declared, any of its - elements can be used. More information on configuring a - Job can be found in . More information on configuring a Step can be - found in . -
-
diff --git a/src/site/docbook/reference/glossary.xml b/src/site/docbook/reference/glossary.xml deleted file mode 100644 index 9b4892e11..000000000 --- a/src/site/docbook/reference/glossary.xml +++ /dev/null @@ -1,216 +0,0 @@ - - - - - Spring Batch Glossary - - - Batch - - - An accumulation of business transactions over time. - - - - - Batch Application Style - - - Term used to designate batch as an application style in its own - right similar to online, Web or SOA. It has standard elements of - input, validation, transformation of information to business model, - business processing and output. In addition, it requires monitoring at - a macro level. - - - - - Batch Processing - - - The handling of a batch of many business transactions that have - accumulated over a period of time (e.g. an hour, day, week, month, or - year). It is the application of a process, or set of processes, to - many data entities or objects in a repetitive and predictable fashion - with either no manual element, or a separate manual element for error - processing. - - - - - Batch Window - - - The time frame within which a batch job must complete. This can - be constrained by other systems coming online, other dependent jobs - needing to execute or other factors specific to the batch - environment. - - - - - Step - - - It is the main batch task or unit of work controller. It - initializes the business logic, and controls the transaction - environment based on commit interval setting, etc. - - - - - Tasklet - - - A component created by application developer to process the - business logic for a Step. - - - - - Batch Job Type - - - Job Types describe application of jobs for particular type of - processing. Common areas are interface processing (typically flat - files), forms processing (either for online pdf generation or print - formats), report processing. - - - - - Driving Query - - - A driving query identifies the set of work for a job to do; the - job then breaks that work into individual units of work. For instance, - identify all financial transactions that have a status of "pending - transmission" and send them to our partner system. The driving query - returns a set of record IDs to process; each record ID then becomes a - unit of work. A driving query may involve a join (if the criteria for - selection falls across two or more tables) or it may work with a - single table. - - - - - Item - - - An item represents the smallest ammount of complete data for - processing. In the simplest terms, this might mean a line in a file, a - row in a database table, or a particular element in an XML - file. - - - - - Logicial Unit of Work (LUW) - - - A batch job iterates through a driving query (or another input - source such as a file) to perform the set of work that the job must - accomplish. Each iteration of work performed is a unit of work. - - - - - Commit Interval - - - A set of LUWs processed within a single transaction. - - - - - Partitioning - - - Splitting a job into multiple threads where each thread is - responsible for a subset of the overall data to be processed. The - threads of execution may be within the same JVM or they may span JVMs - in a clustered environment that supports workload balancing. - - - - - Staging Table - - - A table that holds temporary data while it is being - processed. - - - - - Restartable - - - A job that can be executed again and will assume the same - identity as when run initially. In othewords, it is has the same job - instance id. - - - - - Rerunnable - - - A job that is restartable and manages its own state in terms of - previous run's record processing. An example of a rerunnable step is - one based on a driving query. If the driving query can be formed so - that it will limit the processed rows when the job is restarted than - it is re-runnable. This is managed by the application logic. Often - times a condition is added to the where statement to limit the rows - returned by the driving query with something like "and processedFlag - != true". - - - - - Repeat - - - One of the most basic units of batch processing, that defines - repeatability calling a portion of code until it is finished, and - while there is no error. Typically a batch process would be repeatable - as long as there is input. - - - - - Retry - - - Simplifies the execution of operations with retry semantics most - frequently associated with handling transactional output exceptions. - Retry is slightly different from repeat, rather than continually - calling a block of code, retry is stateful, and continually calls the - same block of code with the same input, until it either succeeds, or - some type of retry limit has been exceeded. It is only generally - useful if a subsequent invocation of the operation might succeed - because something in the environment has improved. - - - - - Recover - - - Recover operations handle an exception in such a way that a - repeat process is able to continue. - - - - - Skip - - - Skip is a recovery strategy often used on file input sources as - the strategy for ignoring bad input records that failed - validation. - - - - diff --git a/src/site/docbook/reference/index.xml b/src/site/docbook/reference/index.xml deleted file mode 100644 index 9a35bfdcf..000000000 --- a/src/site/docbook/reference/index.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - - Spring Batch - Reference Documentation - Spring Batch - ${version} - - - - Lucas - Ward - - - Dave - Syer - - - - Thomas - Risberg - - - - Robert - Kasanicky - - - - Dan - Garrette - - - - Wayne - Lund - - - - Michael - Minella - - - - Chris - Schaefer - - - - Gunnar - Hillert - - - - 2009 - 2010 - 2011 - 2012 - 2013 - 2014 - 2015 - 2016 - 2017 - - Pivotal, Inc. All Rights Reserved. - - - - Copies of this document may be made for your own use and for - distribution to others, provided that you do not charge any fee for such - copies and further provided that each copy contains this Copyright - Notice, whether distributed in print or electronically. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/site/docbook/reference/job.xml b/src/site/docbook/reference/job.xml deleted file mode 100644 index dd7e354fe..000000000 --- a/src/site/docbook/reference/job.xml +++ /dev/null @@ -1,1152 +0,0 @@ - - - - Configuring and Running a Job - - In the domain section , the overall - architecture design was discussed, using the following diagram as a - guide: - - - - - - - - - - - - While the Job object may seem like a simple - container for steps, there are many configuration options of which a - developers must be aware . Furthermore, there are many considerations for - how a Job will be run and how its meta-data will be - stored during that run. This chapter will explain the various configuration - options and runtime concerns of a Job . - -
- Configuring a Job - - There are multiple implementations of the - Job interface, however, the namespace - abstracts away the differences in configuration. It has only three - required dependencies: a name, JobRepository , and - a list of Steps. - - - - - -]]> - - The examples here use a parent bean definition to create the steps; - see the section on step configuration - for more options declaring specific step details inline. The XML namespace - defaults to referencing a repository with an id of 'jobRepository', which - is a sensible default. However, this can be overridden explicitly: - - job-repository="specialRepository" - - - -]]> - - In addition to steps a job configuration can contain other elements - that help with parallelisation (<split/>), - declarative flow control (<decision/>) and - externalization of flow definitions - (<flow/>). - -
- Restartability - - One key issue when executing a batch job concerns the behavior of - a Job when it is restarted. The launching of a - Job is considered to be a 'restart' if a - JobExecution already exists for the particular - JobInstance. Ideally, all jobs should be able to - start up where they left off, but there are scenarios where this is not - possible. It is entirely up to the developer to - ensure that a new JobInstance is created in this - scenario. However, Spring Batch does provide some help. If a - Job should never be restarted, but should always - be run as part of a new JobInstance, then the - restartable property may be set to 'false': - - restartable="false" - ... -]]> - - To phrase it another way, setting restartable to false means "this - Job does not support being started again". Restarting a Job that is not - restartable will cause a JobRestartException to - be thrown: - - - - This snippet of JUnit code shows how attempting to create a - JobExecution the first time for a non restartable - job will cause no issues. However, the second - attempt will throw a JobRestartException. -
- -
- Intercepting Job Execution - - During the course of the execution of a - Job, it may be useful to be notified of various - events in its lifecycle so that custom code may be executed. The - SimpleJob allows for this by calling a - JobListener at the appropriate time: - - - - JobListeners can be added to a - SimpleJob via the listeners element on the - job: - - - - - -]]> <listeners> - <listener ref="sampleListener"/> - </listeners> -]]> - - It should be noted that afterJob will be - called regardless of the success or failure of the - Job. If success or failure needs to be determined - it can be obtained from the JobExecution: - - - - The annotations corresponding to this interface are: - - - - @BeforeJob - - - - @AfterJob - - -
- -
- Inheriting from a Parent Job - - If a group of Jobs share similar, but not - identical, configurations, then it may be helpful to define a "parent" - Job from which the concrete - Jobs may inherit properties. Similar to class - inheritance in Java, the "child" Job will combine - its elements and attributes with the parent's. - - In the following example, "baseJob" is an abstract - Job definition that defines only a list of - listeners. The Job "job1" is a concrete - definition that inherits the list of listeners from "baseJob" and merges - it with its own list of listeners to produce a - Job with two listeners and one - Step, "step1". - - - - - - - - - - - - - -]]> - - Please see the section on Inheriting from a Parent Step - for more detailed information. -
- -
- JobParametersValidator - - A job declared in the XML namespace or using any subclass of - AbstractJob can optionally declare a validator for the job parameters at - runtime. This is useful when for instance you need to assert that a job - is started with all its mandatory parameters. There is a - DefaultJobParametersValidator that can be used to constrain combinations - of simple mandatory and optional parameters, and for more complex - constraints you can implement the interface yourself. The configuration - of a validator is supported through the XML namespace through a child - element of the job, e.g: - - - - -]]> - - The validator can be specified as a reference (as above) or as a - nested bean definition in the beans namespace. -
-
- -
- Java Config - - Spring 3 brought the ability to configure applications via java instead - of XML. As of Spring Batch 2.2.0, batch jobs can be configured using the same - java config. There are two components for the java based configuration: - the @EnableBatchConfiguration annotation and two builders. - - The @EnableBatchProcessing works similarly to the other - @Enable* annotations in the Spring family. In this case, - @EnableBatchProcessing provides a base configuration for - building batch jobs. Within this base configuration, an instance of - StepScope is created in addition to a number of beans made - available to be autowired: - - - - - JobRepository - bean name "jobRepository" - - - JobLauncher - bean name "jobLauncher" - - - JobRegistry - bean name "jobRegistry" - - - PlatformTransactionManager - bean name "transactionManager" - - - JobBuilderFactory - bean name "jobBuilders" - - - StepBuilderFactory - bean name "stepBuilders" - - - - The core interface for this configuration is the BatchConfigurer. - The default implementation provides the beans mentioned above and requires a - DataSource as a bean within the context to be provided. This data - source will be used by the JobRepository. - - - - Only one configuration class needs to have the - @EnableBatchProcessing annotation. Once you have a class - annotated with it, you will have all of the above available. - - - With the base configuration in place, a user can use the provided builder factories - to configure a job. Below is an example of a two step job configured via the - JobBuilderFactory and the StepBuilderFactory. - - @Configuration -@EnableBatchProcessing -@Import(DataSourceConfiguration.class) -public class AppConfig { - - @Autowired - private JobBuilderFactory jobs; - - @Autowired - private StepBuilderFactory steps; - - @Bean - public Job job(@Qualifier("step1") Step step1, @Qualifier("step2") Step step2) { - return jobs.get("myJob").start(step1).next(step2).build(); - } - - @Bean - protected Step step1(ItemReader<Person> reader, ItemProcessor<Person, Person> processor, ItemWriter<Person> writer) { - return steps.get("step1") - .<Person, Person> chunk(10) - .reader(reader) - .processor(processor) - .writer(writer) - .build(); - } - - @Bean - protected Step step2(Tasklet tasklet) { - return steps.get("step2") - .tasklet(tasklet) - .build(); - } -} - -
- -
- - - Configuring a JobRepository - - - - As described in earlier, the - JobRepository - is used for basic CRUD operations of the various persisted - domain objects within Spring Batch, such as - JobExecution and - StepExecution. It is required by many of the major - framework features, such as the JobLauncher, - Job, and Step. The batch - namespace abstracts away many of the implementation details of the - JobRepository implementations and their - collaborators. However, there are still a few configuration options - available: - - ]]> - - None of the configuration options listed above are required except - the id. If they are not set, the defaults shown above will be used. They - are shown above for awareness purposes. The - max-varchar-length defaults to 2500, which is the - length of the long VARCHAR columns in the sample schema scripts - - used to store things like exit code descriptions. If you don't modify the schema and you don't use multi-byte characters you shouldn't need to change it. - -
- Transaction Configuration for the JobRepository - - If the namespace is used, transactional advice will be - automatically created around the repository. This is to ensure that the - batch meta data, including state that is necessary for restarts after a - failure, is persisted correctly. The behavior of the framework is not - well defined if the repository methods are not transactional. The - isolation level in the create* method attributes is - specified separately to ensure that when jobs are launched, if two - processes are trying to launch the same job at the same time, only one - will succeed. The default isolation level for that method is - SERIALIZABLE, which is quite aggressive: READ_COMMITTED would work just - as well; READ_UNCOMMITTED would be fine if two processes are not likely - to collide in this way. However, since a call to the - create* method is quite short, it is unlikely - that the SERIALIZED will cause problems, as long as the database - platform supports it. However, this can be overridden: - - - isolation-level-for-create="REPEATABLE_READ"]]> - - - If the namespace or factory beans aren't used then it is also - essential to configure the transactional behavior of the repository - using AOP: - - - - - - - - - - - -]]> - - - This fragment can be used as is, with almost no changes. Remember - also to include the appropriate namespace declarations and to make sure - spring-tx and spring-aop (or the whole of spring) are on the - classpath. -
- - - -
- Changing the Table Prefix - - Another modifiable property of the - JobRepository is the table prefix of the - meta-data tables. By default they are all prefaced with BATCH_. - BATCH_JOB_EXECUTION and BATCH_STEP_EXECUTION are two examples. However, - there are potential reasons to modify this prefix. If the schema names - needs to be prepended to the table names, or if more than one set of - meta data tables is needed within the same schema, then the table prefix - will need to be changed: - - table-prefix="SYSTEM.TEST_"]]> - - Given the above changes, every query to the meta data tables will - be prefixed with "SYSTEM.TEST_". BATCH_JOB_EXECUTION will be referred to - as SYSTEM.TEST_JOB_EXECUTION. - - - Only the table prefix is configurable. The table and column - names are not. - -
- - - -
- In-Memory Repository - - There are scenarios in which you may not want to persist your - domain objects to the database. One reason may be speed; storing domain - objects at each commit point takes extra time. Another reason may be - that you just don't need to persist status for a particular job. For - this reason, Spring batch provides an in-memory Map version of the job - repository: - - - -]]> - - Note that the in-memory repository is volatile and so does not - allow restart between JVM instances. It also cannot guarantee that two - job instances with the same parameters are launched simultaneously, and - is not suitable for use in a multi-threaded Job, or a locally - partitioned Step. So use the database version of the repository wherever - you need those features. - - However it does require a transaction manager to be defined - because there are rollback semantics within the repository, and because - the business logic might still be transactional (e.g. RDBMS access). For - testing purposes many people find the - ResourcelessTransactionManager useful. -
- - - -
- Non-standard Database Types in a Repository - - If you are using a database platform that is not in the list of - supported platforms, you may be able to use one of the supported types, - if the SQL variant is close enough. To do this you can use the raw - JobRepositoryFactoryBean instead of the namespace - shortcut and use it to set the database type to the closest - match: - - - - -]]> - - (The JobRepositoryFactoryBean tries to - auto-detect the database type from the DataSource - if it is not specified.) The major differences between platforms are - mainly accounted for by the strategy for incrementing primary keys, so - often it might be necessary to override the - incrementerFactory as well (using one of the standard - implementations from the Spring Framework). - - If even that doesn't work, or you are not using an RDBMS, then the - only option may be to implement the various Dao - interfaces that the SimpleJobRepository depends - on and wire one up manually in the normal Spring way. -
- - -
- -
- Configuring a JobLauncher - - The most basic implementation of the - JobLauncher interface is the - SimpleJobLauncher. Its only required dependency is - a JobRepository, in order to obtain an - execution: - - - -]]> - - Once a JobExecution is - obtained, it is passed to the execute method of - Job, ultimately returning the - JobExecution to the caller: - - - - - - - - - - - - The sequence is straightforward and works well when launched from a - scheduler. However, issues arise when trying to launch from an HTTP - request. In this scenario, the launching needs to be done asynchronously - so that the SimpleJobLauncher returns immediately - to its caller. This is because it is not good practice to keep an HTTP - request open for the amount of time needed by long running processes such - as batch. An example sequence is below: - - - - - - - - - - - - The SimpleJobLauncher can easily be - configured to allow for this scenario by configuring a - TaskExecutor: - - - - - - -]]> - - Any implementation of the spring TaskExecutor - interface can be used to control how jobs are asynchronously - executed. -
- -
- Running a Job - - At a minimum, launching a batch job requires two things: the - Job to be launched and a - JobLauncher. Both can be contained within the same - context or different contexts. For example, if launching a job from the - command line, a new JVM will be instantiated for each Job, and thus every - job will have its own JobLauncher. However, if - running from within a web container within the scope of an - HttpRequest, there will usually be one - JobLauncher, configured for asynchronous job - launching, that multiple requests will invoke to launch their jobs. - -
- Running Jobs from the Command Line - - For users that want to run their jobs from an enterprise - scheduler, the command line is the primary interface. This is because - most schedulers (with the exception of Quartz unless using the - NativeJob) work directly with operating system - processes, primarily kicked off with shell scripts. There are many ways - to launch a Java process besides a shell script, such as Perl, Ruby, or - even 'build tools' such as ant or maven. However, because most people - are familiar with shell scripts, this example will focus on them. - -
- The CommandLineJobRunner - - Because the script launching the job must kick off a Java - Virtual Machine, there needs to be a class with a main method to act - as the primary entry point. Spring Batch provides an implementation - that serves just this purpose: - CommandLineJobRunner. It's important to note - that this is just one way to bootstrap your application, but there are - many ways to launch a Java process, and this class should in no way be - viewed as definitive. The CommandLineJobRunner - performs four tasks: - - - - Load the appropriate - ApplicationContext - - - - Parse command line arguments into - JobParameters - - - - Locate the appropriate job based on arguments - - - - Use the JobLauncher provided in the - application context to launch the job. - - - - All of these tasks are accomplished using only the arguments - passed in. The following are required arguments: - - - CommandLineJobRunner arguments - - - - - jobPath - - The location of the XML file that will be used to - create an ApplicationContext. This file - should contain everything needed to run the complete - Job - - - - jobName - - The name of the job to be run. - - - -
- - These arguments must be passed in with the path first and the - name second. All arguments after these are considered to be - JobParameters and must be in the format of 'name=value': - - bash$ - - In most cases you would want to use a manifest to declare your - main class in a jar, but for simplicity, the class was used directly. - This example is using the same 'EndOfDay' example from the domain section. The first argument is - 'endOfDayJob.xml', which is the Spring - ApplicationContext containing the - Job. The second argument, 'endOfDay' represents - the job name. The final argument, 'schedule.date(date)=2007/05/05' - will be converted into JobParameters. An - example of the XML configuration is below: - - - - - - -]]> - - This example is overly simplistic, since there are many more - requirements to a run a batch job in Spring Batch in general, but it - serves to show the two main requirements of the - CommandLineJobRunner: - Job and - JobLauncher -
- -
- ExitCodes - - When launching a batch job from the command-line, an enterprise - scheduler is often used. Most schedulers are fairly dumb and work only - at the process level. This means that they only know about some - operating system process such as a shell script that they're invoking. - In this scenario, the only way to communicate back to the scheduler - about the success or failure of a job is through return codes. A - return code is a number that is returned to a scheduler by the process - that indicates the result of the run. In the simplest case: 0 is - success and 1 is failure. However, there may be more complex - scenarios: If job A returns 4 kick off job B, and if it returns 5 kick - off job C. This type of behavior is configured at the scheduler level, - but it is important that a processing framework such as Spring Batch - provide a way to return a numeric representation of the 'Exit Code' - for a particular batch job. In Spring Batch this is encapsulated - within an ExitStatus, which is covered in more - detail in Chapter 5. For the purposes of discussing exit codes, the - only important thing to know is that an - ExitStatus has an exit code property that is - set by the framework (or the developer) and is returned as part of the - JobExecution returned from the - JobLauncher. The - CommandLineJobRunner converts this string value - to a number using the ExitCodeMapper - interface: - - - - The essential contract of an - ExitCodeMapper is that, given a string exit - code, a number representation will be returned. The default - implementation used by the job runner is the SimpleJvmExitCodeMapper - that returns 0 for completion, 1 for generic errors, and 2 for any job - runner errors such as not being able to find a - Job in the provided context. If anything more - complex than the 3 values above is needed, then a custom - implementation of the ExitCodeMapper interface - must be supplied. Because the - CommandLineJobRunner is the class that creates - an ApplicationContext, and thus cannot be - 'wired together', any values that need to be overwritten must be - autowired. This means that if an implementation of - ExitCodeMapper is found within the BeanFactory, - it will be injected into the runner after the context is created. All - that needs to be done to provide your own - ExitCodeMapper is to declare the implementation - as a root level bean and ensure that it is part of the - ApplicationContext that is loaded by the - runner. -
-
- -
- Running Jobs from within a Web Container - - Historically, offline processing such as batch jobs have been - launched from the command-line, as described above. However, there are - many cases where launching from an HttpRequest is - a better option. Many such use cases include reporting, ad-hoc job - running, and web application support. Because a batch job by definition - is long running, the most important concern is ensuring to launch the - job asynchronously: - - - - - - - - - - The controller in this case is a Spring MVC controller. More - information on Spring MVC can be found here: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html. - The controller launches a Job using a - JobLauncher that has been configured to launch - asynchronously, which - immediately returns a JobExecution. The - Job will likely still be running, however, this - nonblocking behaviour allows the controller to return immediately, which - is required when handling an HttpRequest. An - example is below: - - -
-
- -
- Advanced Meta-Data Usage - - So far, both the JobLauncher and JobRepository interfaces have been - discussed. Together, they represent simple launching of a job, and basic - CRUD operations of batch domain objects: - - - - - - - - - - - - A JobLauncher uses the - JobRepository to create new - JobExecution objects and run them. - Job and Step implementations - later use the same JobRepository for basic updates - of the same executions during the running of a Job. - The basic operations suffice for simple scenarios, but in a large batch - environment with hundreds of batch jobs and complex scheduling - requirements, more advanced access of the meta data is required: - - - - - - - - - - - - The JobExplorer and - JobOperator interfaces, which will be discussed - below, add additional functionality for querying and controlling the meta - data. - -
- Querying the Repository - - The most basic need before any advanced features is the ability to - query the repository for existing executions. This functionality is - provided by the JobExplorer interface: - - getJobInstances(String jobName, int start, int count); - - JobExecution getJobExecution(Long executionId); - - StepExecution getStepExecution(Long jobExecutionId, Long stepExecutionId); - - JobInstance getJobInstance(Long instanceId); - - List getJobExecutions(JobInstance jobInstance); - - Set findRunningJobExecutions(String jobName); -}]]> - - As is evident from the method signatures above, - JobExplorer is a read-only version of the - JobRepository, and like the - JobRepository, it can be easily configured via a - factory bean: - - ]]> - - Earlier in this - chapter, it was mentioned that the table prefix of the - JobRepository can be modified to allow for - different versions or schemas. Because the - JobExplorer is working with the same tables, it - too needs the ability to set a prefix: - - p:tablePrefix="BATCH_" ]]> -
- -
- JobRegistry - - A JobRegistry (and its parent interface JobLocator) is not - mandatory, but it can be useful if you want to keep track of which jobs - are available in the context. It is also useful for collecting jobs - centrally in an application context when they have been created - elsewhere (e.g. in child contexts). Custom JobRegistry implementations - can also be used to manipulate the names and other properties of the - jobs that are registered. There is only one implementation provided by - the framework and this is based on a simple map from job name to job - instance. It is configured simply like this: - - ]]> - - There are two ways to populate a JobRegistry automatically: using - a bean post processor and using a registrar lifecycle component. These - two mechanisms are described in the following sections. - -
- JobRegistryBeanPostProcessor - - This is a bean post-processor that can register all jobs as they - are created: - - - -]]> - - Athough it is not strictly necessary the post-processor in the - example has been given an id so that it can be included in child - contexts (e.g. as a parent bean definition) and cause all jobs created - there to also be regsistered automatically. -
- -
- AutomaticJobRegistrar - - This is a lifecycle component that creates child contexts and - registers jobs from those contexts as they are created. One advantage - of doing this is that, while the job names in the child contexts still - have to be globally unique in the registry, their dependencies can - have "natural" names. So for example, you can create a set of XML - configuration files each having only one Job, - but all having different definitions of an - ItemReader with the same bean name, e.g. - "reader". If all those files were imported into the same context, the - reader definitions would clash and override one another, but with the - automatic regsistrar this is avoided. This makes it easier to - integrate jobs contributed from separate modules of an - application. - - - - - - - - - - - - -]]> - - The registrar has two mandatory properties, one is an array of - ApplicationContextFactory (here created from a - convenient factory bean), and the other is a - JobLoader. The JobLoader - is responsible for managing the lifecycle of the child contexts and - registering jobs in the JobRegistry. - - The ApplicationContextFactory is - responsible for creating the child context and the most common usage - would be as above using a - ClassPathXmlApplicationContextFactory. One of - the features of this factory is that by default it copies some of the - configuration down from the parent context to the child. So for - instance you don't have to re-define the - PropertyPlaceholderConfigurer or AOP - configuration in the child, if it should be the same as the - parent. - - The AutomaticJobRegistrar can be used in - conjunction with a JobRegistryBeanPostProcessor - if desired (as long as the DefaultJobLoader is - used as well). For instance this might be desirable if there are jobs - defined in the main parent context as well as in the child - locations. -
-
- -
- JobOperator - - As previously discussed, the JobRepository - provides CRUD operations on the meta-data, and the - JobExplorer provides read-only operations on the - meta-data. However, those operations are most useful when used together - to perform common monitoring tasks such as stopping, restarting, or - summarizing a Job, as is commonly done by batch operators. Spring Batch - provides for these types of operations via the - JobOperator interface: - - getExecutions(long instanceId) throws NoSuchJobInstanceException; - - List getJobInstances(String jobName, int start, int count) - throws NoSuchJobException; - - Set getRunningExecutions(String jobName) throws NoSuchJobException; - - String getParameters(long executionId) throws NoSuchJobExecutionException; - - Long start(String jobName, String parameters) - throws NoSuchJobException, JobInstanceAlreadyExistsException; - - Long restart(long executionId) - throws JobInstanceAlreadyCompleteException, NoSuchJobExecutionException, - NoSuchJobException, JobRestartException; - - Long startNextInstance(String jobName) - throws NoSuchJobException, JobParametersNotFoundException, JobRestartException, - JobExecutionAlreadyRunningException, JobInstanceAlreadyCompleteException; - - boolean stop(long executionId) - throws NoSuchJobExecutionException, JobExecutionNotRunningException; - - String getSummary(long executionId) throws NoSuchJobExecutionException; - - Map getStepExecutionSummaries(long executionId) - throws NoSuchJobExecutionException; - - Set getJobNames(); - -}]]> - - The above operations represent methods from many different - interfaces, such as JobLauncher, - JobRepository, - JobExplorer, and - JobRegistry. For this reason, the provided - implementation of JobOperator, - SimpleJobOperator, has many dependencies: - - - - - - - - - - -]]> - - - If you set the table prefix on the job repository, don't forget to set it on the job explorer as well. - -
- -
- JobParametersIncrementer - - Most of the methods on JobOperator are - self-explanatory, and more detailed explanations can be found on the - javadoc - of the interface. However, the - startNextInstance method is worth noting. This - method will always start a new instance of a Job. - This can be extremely useful if there are serious issues in a - JobExecution and the Job - needs to be started over again from the beginning. Unlike - JobLauncher though, which requires a new - JobParameters object that will trigger a new - JobInstance if the parameters are different from - any previous set of parameters, the - startNextInstance method will use the - JobParametersIncrementer tied to the - Job to force the Job to a - new instance: - - - - The contract of JobParametersIncrementer is - that, given a JobParameters - object, it will return the 'next' JobParameters - object by incrementing any necessary values it may contain. This - strategy is useful because the framework has no way of knowing what - changes to the JobParameters make it the 'next' - instance. For example, if the only value in - JobParameters is a date, and the next instance - should be created, should that value be incremented by one day? Or one - week (if the job is weekly for instance)? The same can be said for any - numerical values that help to identify the Job, - as shown below: - - - - In this example, the value with a key of 'run.id' is used to - discriminate between JobInstances. If the - JobParameters passed in is null, it can be - assumed that the Job has never been run before - and thus its initial state can be returned. However, if not, the old - value is obtained, incremented by one, and returned. An incrementer can - be associated with Job via the 'incrementer' - attribute in the namespace: - - incrementer="sampleIncrementer" - ... -]]> -
- -
- Stopping a Job - - One of the most common use cases of - JobOperator is gracefully stopping a - Job: - - executions = jobOperator.getRunningExecutions("sampleJob"); -jobOperator.stop(executions.iterator().next());]]> - - The shutdown is not immediate, since there is no way to force - immediate shutdown, especially if the execution is currently in - developer code that the framework has no control over, such as a - business service. However, as soon as control is returned back to the - framework, it will set the status of the current - StepExecution to - BatchStatus.STOPPED, save it, then do the same - for the JobExecution before finishing. -
- -
- Aborting a Job - - A job execution which is FAILED can be - restarted (if the Job is restartable). A job execution whose status is - ABANDONED will not be restarted by the framework. - The ABANDONED status is also used in step - executions to mark them as skippable in a restarted job execution: if a - job is executing and encounters a step that has been marked - ABANDONED in the previous failed job execution, it - will move on to the next step (as determined by the job flow definition - and the step execution exit status). - - If the process died ("kill -9" or server - failure) the job is, of course, not running, but the JobRepository has - no way of knowing because no-one told it before the process died. You - have to tell it manually that you know that the execution either failed - or should be considered aborted (change its status to - FAILED or ABANDONED) - it's - a business decision and there is no way to automate it. Only change the - status to FAILED if it is not restartable, or if - you know the restart data is valid. There is a utility in Spring Batch - Admin JobService to abort a job execution. -
-
-
diff --git a/src/site/docbook/reference/jsr-352.xml b/src/site/docbook/reference/jsr-352.xml deleted file mode 100644 index 8349c226f..000000000 --- a/src/site/docbook/reference/jsr-352.xml +++ /dev/null @@ -1,641 +0,0 @@ - - - - JSR-352 Support - - As of Spring Batch 3.0 support for JSR-352 has been fully implemented. This section is not a replacement for - the spec itself and instead, intends to explain how the JSR-352 specific concepts apply to Spring Batch. - Additional information on JSR-352 can be found via the - JCP here: https://jcp.org/en/jsr/detail?id=352 - -
- General Notes Spring Batch and JSR-352 - - Spring Batch and JSR-352 are structurally the same. They both have jobs that are made up of steps. They - both have readers, processors, writers, and listeners. However, their interactions are subtly different. - For example, the org.springframework.batch.core.SkipListener#onSkipInWrite(S item, Throwable t) - within Spring Batch receives two parameters: the item that was skipped and the Exception that caused the - skip. The JSR-352 version of the same method - (javax.batch.api.chunk.listener.SkipWriteListener#onSkipWriteItem(List<Object> items, Exception ex)) - also receives two parameters. However the first one is a List of all the items - within the current chunk with the second being the Exception that caused the skip. - Because of these differences, it is important to note that there are two paths to execute a job within - Spring Batch: either a traditional Spring Batch job or a JSR-352 based job. While the use of Spring Batch - artifacts (readers, writers, etc) will work within a job configured via JSR-352's JSL and executed via the - JsrJobOperator, they will behave according to the rules of JSR-352. It is also - important to note that batch artifacts that have been developed against the JSR-352 interfaces will not work - within a traditional Spring Batch job. -
- -
- Setup - -
- Application Contexts - - All JSR-352 based jobs within Spring Batch consist of two application contexts. A parent context, that - contains beans related to the infrastructure of Spring Batch such as the JobRepository, - PlatformTransactionManager, etc and a child context that consists of the configuration - of the job to be run. The parent context is defined via the baseContext.xml provided - by the framework. This context may be overridden via the JSR-352-BASE-CONTEXT system - property. - - The base context is not processed by the JSR-352 processors for things like property injection so - no components requiring that additional processing should be configured there. - -
- -
- Launching a JSR-352 based job - - JSR-352 requires a very simple path to executing a batch job. The following code is all that is needed to - execute your first batch job: - - - JobOperator operator = BatchRuntime.getJobOperator(); - jobOperator.start("myJob", new Properties()); - - While that is convenient for developers, the devil is in the details. Spring Batch bootstraps a bit of - infrastructure behind the scenes that a developer may want to override. The following is bootstrapped the - first time BatchRuntime.getJobOperator() is called: - - - - - - - - - Bean Name - - - Default Configuration - - - Notes - - - - - dataSource - - - Apache DBCP BasicDataSource with configured values. - - - By default, HSQLDB is bootstrapped. - - - - - transactionManager - - - org.springframework.jdbc.datasource.DataSourceTransactionManager - - - References the dataSource bean defined above. - - - - - A Datasource initializer - - - - - This is configured to execute the scripts configured via the - batch.drop.script and batch.schema.script properties. By - default, the schema scripts for HSQLDB are executed. This behavior can be disabled via - batch.data.source.init property. - - - - - jobRepository - - - A JDBC based SimpleJobRepository. - - - This JobRepository uses the previously mentioned data source and transaction - manager. The schema's table prefix is configurable (defaults to BATCH_) via the - batch.table.prefix property. - - - - - jobLauncher - - - org.springframework.batch.core.launch.support.SimpleJobLauncher - - - Used to launch jobs. - - - - - batchJobOperator - - - org.springframework.batch.core.launch.support.SimpleJobOperator - - - The JsrJobOperator wraps this to provide most of it's functionality. - - - - - jobExplorer - - - org.springframework.batch.core.explore.support.JobExplorerFactoryBean - - - Used to address lookup functionality provided by the JsrJobOperator. - - - - - jobParametersConverter - - - org.springframework.batch.core.jsr.JsrJobParametersConverter - - - JSR-352 specific implementation of the JobParametersConverter. - - - - - jobRegistry - - - org.springframework.batch.core.configuration.support.MapJobRegistry - - - Used by the SimpleJobOperator. - - - - - placeholderProperties - - - org.springframework.beans.factory.config.PropertyPlaceholderConfigure - - - Loads the properties file batch-${ENVIRONMENT:hsql}.properties to configure - the properties mentioned above. ENVIRONMENT is a System property (defaults to hsql) - that can be used to specify any of the supported databases Spring Batch currently - supports. - - - - - - - None of the above beans are optional for executing JSR-352 based jobs. All may be overriden to - provide customized functionality as needed. - -
- -
- -
- Dependency Injection - - JSR-352 is based heavily on the Spring Batch programming model. As such, while not explicitly requiring a - formal dependency injection implementation, DI of some kind implied. Spring Batch supports all three - methods for loading batch artifacts defined by JSR-352: - - - Implementation Specific Loader - Spring Batch is built upon Spring and so supports Spring - dependency injection within JSR-352 batch jobs. - - - Archive Loader - JSR-352 defines the existing of a batch.xml file that provides mappings between a - logical name and a class name. This file must be found within the /META-INF/ directory if it is - used. - - - Thread Context Class Loader - JSR-352 allows configurations to specify batch artifact - implementations in their JSL by providing the fully qualified class name inline. Spring Batch - supports this as well in JSR-352 configured jobs. - - - - To use Spring dependency injection within a JSR-352 based batch job consists of configuring batch - artifacts using a Spring application context as beans. Once the beans have been defined, a job can refer to - them as it would any bean defined within the batch.xml. - <?xml version="1.0" encoding="UTF-8"?> -<beans xmlns="http://www.springframework.org/schema/beans" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans.xsd - http://xmlns.jcp.org/xml/ns/javaee - http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd"> - - <!-- javax.batch.api.Batchlet implementation --> - <bean id="fooBatchlet" class="io.spring.FooBatchlet"> - <property name="prop" value="bar"/> - </bean> - - <!-- Job is defined using the JSL schema provided in JSR-352 --> - <job id="fooJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0"> - <step id="step1"> - <batchlet ref="fooBatchlet"/> - </step> - </job> -</beans> - - - The assembly of Spring contexts (imports, etc) works with JSR-352 jobs just as it would with any other - Spring based application. The only difference with a JSR-352 based job is that the entry point for the - context definition will be the job definition found in /META-INF/batch-jobs/. - - To use the thread context class loader approach, all you need to do is provide the fully qualified class - name as the ref. It is important to note that when using this approach or the batch.xml approach, the class - referenced requires a no argument constructor which will be used to create the bean. - <?xml version="1.0" encoding="UTF-8"?> -<job id="fooJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0"> - <step id="step1" > - <batchlet ref="io.spring.FooBatchlet" /> - </step> -</job> - - -
- -
- Batch Properties - -
- Property Support - - JSR-352 allows for properties to be defined at the Job, Step and batch artifact level by way of - configuration in the JSL. Batch properties are configured at each level in the following way: - - <properties> - <property name="propertyName1" value="propertyValue1"/> - <property name="propertyName2" value="propertyValue2"/> -</properties> - - Properties may be configured on any batch artifact. -
-
- <classname>@BatchProperty</classname> annotation - - Properties are referenced in batch artifacts by annotating class fields with the - @BatchProperty and @Inject annotations (both annotations - are required by the spec). As defined by JSR-352, fields for properties must be String typed. Any type - conversion is up to the implementing developer to perform. - - An javax.batch.api.chunk.ItemReader artifact could be configured with a - properties block such as the one described above and accessed as such: - public class MyItemReader extends AbstractItemReader { - @Inject - @BatchProperty - private String propertyName1; - - ... -} - - The value of the field "propertyName1" will be "propertyValue1" -
-
- Property Substitution - - Property substitution is provided by way of operators and simple conditional expressions. The general - usage is #{operator['key']}. - Supported operators: - - - - jobParameters - access job parameter values that the job was started/restarted with. - - - - jobProperties - access properties configured at the job level of the JSL. - - - systemProperties - access named system properties. - - - partitionPlan - access named property from the partition plan of a partitioned step. - - - - - #{jobParameters['unresolving.prop']}?:#{systemProperties['file.separator']} - - The left hand side of the assignment is the expected value, the right hand side is the default value. In - this example, the result will resolve to a value of the system property file.separator as - #{jobParameters['unresolving.prop']} is assumed to not be resolvable. If neither expressions can be - resolved, an empty String will be returned. Multiple conditions can be used, which are separated by a - ';'. - -
-
- -
- Processing Models - - JSR-352 provides the same two basic processing models that Spring Batch does: - - - - Item based processing - Using an javax.batch.api.chunk.ItemReader, an - optional javax.batch.api.chunk.ItemProcessor, and an - javax.batch.api.chunk.ItemWriter. - - - Task based processing - Using a javax.batch.api.Batchlet - implementation. This processing model is the same as the - org.springframework.batch.core.step.tasklet.Tasklet based processing - currently available. - - - - -
- Item based processing - Item based processing in this context is a chunk size being set by the number of items read by an - ItemReader. To configure a step this way, specify the - item-count (which defaults to 10) and optionally configure the - checkpoint-policy as item (this is the default). - - ... -<step id="step1"> - <chunk checkpoint-policy="item" item-count="3"> - <reader ref="fooReader"/> - <processor ref="fooProcessor"/> - <writer ref="fooWriter"/> - </chunk> -</step> -... - - If item based checkpointing is chosen, an additional attribute time-limit is - supported. This sets a time limit for how long the number of items specified has to be processed. If - the timeout is reached, the chunk will complete with however many items have been read by then - regardless of what the item-count is configured to be. - -
- -
- Custom checkpointing - JSR-352 calls the process around the commit interval within a step "checkpointing". Item based - checkpointing is one approach as mentioned above. However, this will not be robust enough in many - cases. Because of this, the spec allows for the implementation of a custom checkpointing algorithm by - implementing the javax.batch.api.chunk.CheckpointAlgorithm interface. This - functionality is functionally the same as Spring Batch's custom completion policy. To use an - implementation of CheckpointAlgorithm, configure your step with the custom - checkpoint-policy as shown below where fooCheckpointer refers to an - implementation of CheckpointAlgorithm. - - ... -<step id="step1"> - <chunk checkpoint-policy="custom"> - <checkpoint-algorithm ref="fooCheckpointer"/> - <reader ref="fooReader"/> - <processor ref="fooProcessor"/> - <writer ref="fooWriter"/> - </chunk> -</step> -... -
-
- -
- Running a job - - The entrance to executing a JSR-352 based job is through the - javax.batch.operations.JobOperator. Spring Batch provides our own implementation to - this interface (org.springframework.batch.core.jsr.launch.JsrJobOperator). This - implementation is loaded via the javax.batch.runtime.BatchRuntime. Launching a - JSR-352 based batch job is implemented as follows: - - -JobOperator jobOperator = BatchRuntime.getJobOperator(); -long jobExecutionId = jobOperator.start("fooJob", new Properties()); - - - The above code does the following: - - - - - Bootstraps a base ApplicationContext - In order to provide batch functionality, the framework - needs some infrastructure bootstrapped. This occurs once per JVM. The components that are - bootstrapped are similar to those provided by @EnableBatchProcessing. - Specific details can be found in the javadoc for the JsrJobOperator. - - - - Loads an ApplicationContext for the job requested - In the example - above, the framework will look in /META-INF/batch-jobs for a file named fooJob.xml and load a - context that is a child of the shared context mentioned previously. - - - Launch the job - The job defined within the context will be executed asynchronously. The - JobExecution's id will be returned. - - - - - All JSR-352 based batch jobs are executed asynchronously. - - When JobOperator#start is called using SimpleJobOperator, - Spring Batch determines if the call is an initial run or a retry of a previously executed run. Using the - JSR-352 based JobOpeator#start(String jobXMLName, Properties jobParameters), the - framework will always create a new JobInstance (JSR-352 job parameters are - non-identifying). In order to restart a job, a call to - JobOperator#restart(long executionId, Properties restartParameters) is required. - -
- -
- Contexts - - JSR-352 defines two context objects that are used to interact with the meta-data of a job or step from - within a batch artifact: javax.batch.runtime.context.JobContext and - javax.batch.runtime.context.StepContext. Both of these are available in any step - level artifact (Batchlet, ItemReader, etc) with the - JobContext being available to job level artifacts as well - (JobListener for example). - - To obtain a reference to the JobContext or StepContext - within the current scope, simply use the @Inject annotation: - - @Inject -JobContext jobContext; - - - - @Autowire for JSR-352 contexts - Using Spring's @Autowire is not supported for the injection of these contexts. - - - In Spring Batch, the JobContext and StepContext wrap their - corresponding execution objects (JobExecution and - StepExecution respectively). Data stored via - StepContext#persistent#setPersistentUserData(Serializable data) is stored in the - Spring Batch StepExecution#executionContext. -
- -
- Step Flow - Within a JSR-352 based job, the flow of steps works similarly as it does within Spring Batch. - However, there are a few subtle differences: - - - - Decision's are steps - In a regular Spring Batch job, a decision is a state that does not - have an independent StepExecution or any of the rights and - responsibilities that go along with being a full step.. However, with JSR-352, a decision - is a step just like any other and will behave just as any other steps (transactionality, - it gets a StepExecution, etc). This means that they are treated the - same as any other step on restarts as well. - - - next attribute and step transitions - In a regular job, these are - allowed to appear together in the same step. JSR-352 allows them to both be used in the - same step with the next attribute taking precedence in evaluation. - - - Transition element ordering - In a standard Spring Batch job, transition elements are - sorted from most specific to least specific and evaluated in that order. JSR-352 jobs - evaluate transition elements in the order they are specified in the XML. - - - -
- -
- Scaling a JSR-352 batch job - - Traditional Spring Batch jobs have four ways of scaling (the last two capable of being executed across - multiple JVMs): - - - Split - Running multiple steps in parallel. - - - Multiple threads - Executing a single step via multiple threads. - - - Partitioning - Dividing the data up for parallel processing (master/slave). - - - Remote Chunking - Executing the processor piece of logic remotely. - - - - - JSR-352 provides two options for scaling batch jobs. Both options support only a single JVM: - - - Split - Same as Spring Batch - - - Partitioning - Conceptually the same as Spring Batch however implemented slightly different. - - - - - -
- Partitioning - Conceptually, partitioning in JSR-352 is the same as it is in Spring Batch. Meta-data is provided - to each slave to identify the input to be processed with the slaves reporting back to the master the - results upon completion. However, there are some important differences: - - - Partitioned Batchlet - This will run multiple instances of the - configured Batchlet on multiple threads. Each instance will have - it's own set of properties as provided by the JSL or the - PartitionPlan - - - PartitionPlan - With Spring Batch's partitioning, an - ExecutionContext is provided for each partition. With JSR-352, a - single javax.batch.api.partition.PartitionPlan is provided with an - array of Properties providing the meta-data for each partition. - - - - PartitionMapper - JSR-352 provides two ways to generate partition - meta-data. One is via the JSL (partition properties). The second is via an implementation - of the javax.batch.api.partition.PartitionMapper interface. - Functionally, this interface is similar to the - org.springframework.batch.core.partition.support.Partitioner - interface provided by Spring Batch in that it provides a way to programmaticaly generate - meta-data for partitioning. - - - StepExecutions - In Spring Batch, partitioned steps are run as - master/slave. Within JSR-352, the same configuration occurs. However, the slave steps do - not get official StepExecutions. Because of that, calls to - JsrJobOperator#getStepExecutions(long jobExecutionId) will only - return the StepExecution for the master. The child - StepExecutions still exist in the job repository and are available - via the JobExplorer and Spring Batch Admin. - - - - Compensating logic - Since Spring Batch implements the master/slave logic of - partitioning using steps, StepExecutionListeners can be used to - handle compensating logic if something goes wrong. However, since the slaves JSR-352 - provides a collection of other components for the ability to provide compensating logic when - errors occur and to dynamically set the exit status. These components include the following: - - - - - - - - Artifact Interface - - - Description - - - - javax.batch.api.partition.PartitionCollector - Provides a way for slave steps to send information back to the - master. There is one instance per slave thread. - - - javax.batch.api.partition.PartitionAnalyzer - End point that receives the information collected by the - PartitionCollector as well as the resulting - statuses from a completed partition. - - - javax.batch.api.partition.PartitionReducer - Provides the ability to provide compensating logic for a partitioned - step. - - - - - - - - -
-
- -
- Testing - - Since all JSR-352 based jobs are executed asynchronously, it can be difficult to determine when a job has - completed. To help with testing, Spring Batch provides the - org.springframework.batch.core.jsr.JsrTestUtils. This utility class provides the - ability to start a job and restart a job and wait for it to complete. Once the job completes, the - associated JobExecution is returned. -
- -
diff --git a/src/site/docbook/reference/readersAndWriters.xml b/src/site/docbook/reference/readersAndWriters.xml deleted file mode 100644 index 8f5fa9dfa..000000000 --- a/src/site/docbook/reference/readersAndWriters.xml +++ /dev/null @@ -1,2711 +0,0 @@ - - - - ItemReaders and ItemWriters - - All batch processing can be described in its most simple form as - reading in large amounts of data, performing some type of calculation or - transformation, and writing the result out. Spring Batch provides three key - interfaces to help perform bulk reading and writing: - ItemReader, ItemProcessor and - ItemWriter. - -
- ItemReader - - Although a simple concept, an ItemReader is - the means for providing data from many different types of input. The most - general examples include: - - Flat File- Flat File Item Readers read lines of data from a - flat file that typically describe records with fields of data - defined by fixed positions in the file or delimited by some special - character (e.g. Comma). - - - - XML - XML ItemReaders process XML independently of - technologies used for parsing, mapping and validating objects. Input - data allows for the validation of an XML file against an XSD - schema. - - - - Database - A database resource is accessed to return - resultsets which can be mapped to objects for processing. The - default SQL ItemReaders invoke a RowMapper to - return objects, keep track of the current row if restart is - required, store basic statistics, and provide some transaction - enhancements that will be explained later. - - There are many more possibilities, but we'll focus on the - basic ones for this chapter. A complete list of all available ItemReaders - can be found in Appendix A. - - ItemReader is a basic interface for generic - input operations: - - public interface ItemReader<T> { - - T read() throws Exception, UnexpectedInputException, ParseException; - -} - - The read method defines the most essential - contract of the ItemReader; calling it returns one - Item or null if no more items are left. An item might represent a line in - a file, a row in a database, or an element in an XML file. It is generally - expected that these will be mapped to a usable domain object (i.e. Trade, - Foo, etc) but there is no requirement in the contract to do so. - - It is expected that implementations of the - ItemReader interface will be forward only. However, - if the underlying resource is transactional (such as a JMS queue) then - calling read may return the same logical item on subsequent calls in a - rollback scenario. It is also worth noting that a lack of items to process - by an ItemReader will not cause an exception to be - thrown. For example, a database ItemReader that is - configured with a query that returns 0 results will simply return null on - the first invocation of read. -
- -
- ItemWriter - - ItemWriter is similar in functionality to an - ItemReader, but with inverse operations. Resources - still need to be located, opened and closed but they differ in that an - ItemWriter writes out, rather than reading in. In - the case of databases or queues these may be inserts, updates, or sends. - The format of the serialization of the output is specific to each batch - job. - - As with ItemReader, - ItemWriter is a fairly generic interface: - - public interface ItemWriter<T> { - - void write(List<? extends T> items) throws Exception; - -} - - As with read on - ItemReader, write provides - the basic contract of ItemWriter; it will attempt - to write out the list of items passed in as long as it is open. Because it - is generally expected that items will be 'batched' together into a chunk - and then output, the interface accepts a list of items, rather than an - item by itself. After writing out the list, any flushing that may be - necessary can be performed before returning from the write method. For - example, if writing to a Hibernate DAO, multiple calls to write can be - made, one for each item. The writer can then call close on the hibernate - Session before returning. -
- -
- ItemProcessor - - The ItemReader and - ItemWriter interfaces are both very useful for - their specific tasks, but what if you want to insert business logic before - writing? One option for both reading and writing is to use the composite - pattern: create an ItemWriter that contains another - ItemWriter, or an ItemReader - that contains another ItemReader. For - example: - - public class CompositeItemWriter<T> implements ItemWriter<T> { - - ItemWriter<T> itemWriter; - - public CompositeItemWriter(ItemWriter<T> itemWriter) { - this.itemWriter = itemWriter; - } - - public void write(List<? extends T> items) throws Exception { - //Add business logic here - itemWriter.write(item); - } - - public void setDelegate(ItemWriter<T> itemWriter){ - this.itemWriter = itemWriter; - } -} - - The class above contains another ItemWriter - to which it delegates after having provided some business logic. This - pattern could easily be used for an ItemReader as - well, perhaps to obtain more reference data based upon the input that was - provided by the main ItemReader. It is also useful - if you need to control the call to write yourself. - However, if you only want to 'transform' the item passed in for writing - before it is actually written, there isn't much need to call - write yourself: you just want to modify the item. - For this scenario, Spring Batch provides the - ItemProcessor interface: - - public interface ItemProcessor<I, O> { - - O process(I item) throws Exception; -} - - An ItemProcessor is very simple; given one - object, transform it and return another. The provided object may or may - not be of the same type. The point is that business logic may be applied - within process, and is completely up to the developer to create. An - ItemProcessor can be wired directly into a step, - For example, assuming an ItemReader provides a - class of type Foo, and it needs to be converted to type Bar before being - written out. An ItemProcessor can be written that - performs the conversion: - - public class Foo {} - -public class Bar { - public Bar(Foo foo) {} -} - -public class FooProcessor implements ItemProcessor<Foo,Bar>{ - public Bar process(Foo foo) throws Exception { - //Perform simple transformation, convert a Foo to a Bar - return new Bar(foo); - } -} - -public class BarWriter implements ItemWriter<Bar>{ - public void write(List<? extends Bar> bars) throws Exception { - //write bars - } -} - - In the very simple example above, there is a class - Foo, a class Bar, and a - class FooProcessor that adheres to the - ItemProcessor interface. The transformation is - simple, but any type of transformation could be done here. The - BarWriter will be used to write out - Bar objects, throwing an exception if any other - type is provided. Similarly, the FooProcessor will - throw an exception if anything but a Foo is - provided. The FooProcessor can then be injected - into a Step: - - <job id="ioSampleJob"> - <step name="step1"> - <tasklet> - <chunk reader="fooReader" processor="fooProcessor" writer="barWriter" - commit-interval="2"/> - </tasklet> - </step> -</job> - -
- Chaining ItemProcessors - - Performing a single transformation is useful in many scenarios, - but what if you want to 'chain' together multiple - ItemProcessors? This can be accomplished using - the composite pattern mentioned previously. To update the previous, - single transformation, example, Foo will be - transformed to Bar, which will be transformed to - Foobar and written out: - - public class Foo {} - -public class Bar { - public Bar(Foo foo) {} -} - -public class Foobar{ - public Foobar(Bar bar) {} -} - -public class FooProcessor implements ItemProcessor<Foo,Bar>{ - public Bar process(Foo foo) throws Exception { - //Perform simple transformation, convert a Foo to a Bar - return new Bar(foo); - } -} - -public class BarProcessor implements ItemProcessor<Bar,FooBar>{ - public FooBar process(Bar bar) throws Exception { - return new Foobar(bar); - } -} - -public class FoobarWriter implements ItemWriter<FooBar>{ - public void write(List<? extends FooBar> items) throws Exception { - //write items - } -} - - A FooProcessor and - BarProcessor can be 'chained' together to give - the resultant Foobar: - - CompositeItemProcessor<Foo,Foobar> compositeProcessor = - new CompositeItemProcessor<Foo,Foobar>(); -List itemProcessors = new ArrayList(); -itemProcessors.add(new FooTransformer()); -itemProcessors.add(new BarTransformer()); -compositeProcessor.setDelegates(itemProcessors); - - Just as with the previous example, the composite processor can be - configured into the Step: - - <job id="ioSampleJob"> - <step name="step1"> - <tasklet> - <chunk reader="fooReader" processor="compositeProcessor" writer="foobarWriter" - commit-interval="2"/> - </tasklet> - </step> -</job> - -<bean id="compositeItemProcessor" - class="org.springframework.batch.item.support.CompositeItemProcessor"> - <property name="delegates"> - <list> - <bean class="..FooProcessor" /> - <bean class="..BarProcessor" /> - </list> - </property> -</bean> -
- -
- Filtering Records - - One typical use for an item processor is to filter out records - before they are passed to the ItemWriter. Filtering is an action - distinct from skipping; skipping indicates that a record is invalid - whereas filtering simply indicates that a record should not be - written. - - For example, consider a batch job that reads a file containing - three different types of records: records to insert, records to update, - and records to delete. If record deletion is not supported by the - system, then we would not want to send any "delete" records to the - ItemWriter. But, since these records are not - actually bad records, we would want to filter them out, rather than - skip. As a result, the ItemWriter would receive only "insert" and - "update" records. - - To filter a record, one simply returns "null" from the - ItemProcessor. The framework will detect that the - result is "null" and avoid adding that item to the list of records - delivered to the ItemWriter. As usual, an - exception thrown from the ItemProcessor will - result in a skip. -
- -
- Fault Tolerance - - When a chunk is rolled back, items that have been cached - during reading may be reprocessed. If a step is configured to - be fault tolerant (uses skip or retry processing typically), - any ItemProcessor used should be implemented in a way that is - idempotent. Typically that would consist of performing no changes - on the input item for the ItemProcessor and only updating the - instance that is the result. -
-
- -
- ItemStream - - Both ItemReaders and - ItemWriters serve their individual purposes well, - but there is a common concern among both of them that necessitates another - interface. In general, as part of the scope of a batch job, readers and - writers need to be opened, closed, and require a mechanism for persisting - state: - - public interface ItemStream { - - void open(ExecutionContext executionContext) throws ItemStreamException; - - void update(ExecutionContext executionContext) throws ItemStreamException; - - void close() throws ItemStreamException; -} - - Before describing each method, we should mention the - ExecutionContext. Clients of an - ItemReader that also implement - ItemStream should call - open before any calls to - read in order to open any resources such as files - or to obtain connections. A similar restriction applies to an - ItemWriter that implements - ItemStream. As mentioned in Chapter 2, if expected - data is found in the ExecutionContext, it may be - used to start the ItemReader or - ItemWriter at a location other than its initial - state. Conversely, close will be called to ensure - that any resources allocated during open will be - released safely. update is called primarily to - ensure that any state currently being held is loaded into the provided - ExecutionContext. This method will be called before - committing, to ensure that the current state is persisted in the database - before commit. - - In the special case where the client of an - ItemStream is a Step (from - the Spring Batch Core), an ExecutionContext is - created for each StepExecution to allow users to - store the state of a particular execution, with the expectation that it - will be returned if the same JobInstance is started - again. For those familiar with Quartz, the semantics are very similar to a - Quartz JobDataMap. -
- -
- The Delegate Pattern and Registering with the Step - - Note that the CompositeItemWriter is an - example of the delegation pattern, which is common in Spring Batch. The - delegates themselves might implement callback interfaces StepListener. - If they do, and they are being used in conjunction with Spring Batch Core - as part of a Step in a Job, - then they almost certainly need to be registered manually with the - Step. A reader, writer, or processor that is - directly wired into the Step will be registered automatically if it - implements ItemStream or a - StepListener interface. But because the delegates - are not known to the Step, they need to be injected - as listeners or streams (or both if appropriate): - - <job id="ioSampleJob"> - <step name="step1"> - <tasklet> - <chunk reader="fooReader" processor="fooProcessor" writer="compositeItemWriter" - commit-interval="2"> - <streams> - <stream ref="barWriter" /> - </streams> - </chunk> - </tasklet> - </step> -</job> - -<bean id="compositeItemWriter" class="...CustomCompositeItemWriter"> - <property name="delegate" ref="barWriter" /> -</bean> - -<bean id="barWriter" class="...BarWriter" /> -
- -
- Flat Files - - One of the most common mechanisms for interchanging bulk data has - always been the flat file. Unlike XML, which has an agreed upon standard - for defining how it is structured (XSD), anyone reading a flat file must - understand ahead of time exactly how the file is structured. In general, - all flat files fall into two types: Delimited and Fixed Length. Delimited - files are those in which fields are separated by a delimiter, such as a - comma. Fixed Length files have fields that are a set length. - -
- The FieldSet - - When working with flat files in Spring Batch, regardless of - whether it is for input or output, one of the most important classes is - the FieldSet. Many architectures and libraries - contain abstractions for helping you read in from a file, but they - usually return a String or an array of Strings. This really only gets - you halfway there. A FieldSet is Spring Batch’s - abstraction for enabling the binding of fields from a file resource. It - allows developers to work with file input in much the same way as they - would work with database input. A FieldSet is - conceptually very similar to a Jdbc ResultSet. - FieldSets only require one argument, a String - array of tokens. Optionally, you can also configure in the names of the - fields so that the fields may be accessed either by index or name as - patterned after ResultSet: - - String[] tokens = new String[]{"foo", "1", "true"}; -FieldSet fs = new DefaultFieldSet(tokens); -String name = fs.readString(0); -int value = fs.readInt(1); -boolean booleanValue = fs.readBoolean(2); - - There are many more options on the FieldSet - interface, such as Date, long, - BigDecimal, etc. The biggest advantage of the - FieldSet is that it provides consistent parsing - of flat file input. Rather than each batch job parsing differently in - potentially unexpected ways, it can be consistent, both when handling - errors caused by a format exception, or when doing simple data - conversions. -
- -
- FlatFileItemReader - - A flat file is any type of file that contains at most - two-dimensional (tabular) data. Reading flat files in the Spring Batch - framework is facilitated by the class - FlatFileItemReader, which provides basic - functionality for reading and parsing flat files. The two most important - required dependencies of FlatFileItemReader are - Resource and LineMapper. - The LineMapper interface will be - explored more in the next sections. The resource property represents a - Spring Core Resource. Documentation explaining - how to create beans of this type can be found in Spring - Framework, Chapter 5.Resources. Therefore, this - guide will not go into the details of creating - Resource objects. However, a simple example of a - file system resource can be found below: - - Resource resource = new FileSystemResource("resources/trades.csv"); - - In complex batch environments the directory structures are often - managed by the EAI infrastructure where drop zones for external - interfaces are established for moving files from ftp locations to batch - processing locations and vice versa. File moving utilities are beyond - the scope of the spring batch architecture but it is not unusual for - batch job streams to include file moving utilities as steps in the job - stream. It is sufficient that the batch architecture only needs to know - how to locate the files to be processed. Spring Batch begins the process - of feeding the data into the pipe from this starting point. However, - Spring - Integration provides many of these types of - services. - - The other properties in FlatFileItemReader - allow you to further specify how your data will be interpreted: - FlatFileItemReader Properties - - - - - - - Property - - Type - - Description - - - - - - comments - - String[] - - Specifies line prefixes that indicate - comment rows - - - - encoding - - String - - Specifies what text encoding to use - - default is "ISO-8859-1" - - - - lineMapper - - LineMapper - - Converts a String - to an Object representing the - item. - - - - linesToSkip - - int - - Number of lines to ignore at the top of - the file - - - - recordSeparatorPolicy - - RecordSeparatorPolicy - - Used to determine where the line endings - are and do things like continue over a line ending if inside a - quoted string. - - - - resource - - Resource - - The resource from which to read. - - - - skippedLinesCallback - - LineCallbackHandler - - Interface which passes the raw line - content of the lines in the file to be skipped. If linesToSkip - is set to 2, then this interface will be called twice. - - - - strict - - boolean - - In strict mode, the reader will throw an - exception on ExecutionContext if the input resource does not - exist. - - - -
- -
- LineMapper - - As with RowMapper, which takes a low - level construct such as ResultSet and returns - an Object, flat file processing requires the - same construct to convert a String line into an - Object: - - public interface LineMapper<T> { - - T mapLine(String line, int lineNumber) throws Exception; - -} - - The basic contract is that, given the current line and the line - number with which it is associated, the mapper should return a - resulting domain object. This is similar to - RowMapper in that each line is associated with - its line number, just as each row in a - ResultSet is tied to its row number. This - allows the line number to be tied to the resulting domain object for - identity comparison or for more informative logging. However, unlike - RowMapper, the - LineMapper is given a raw line which, as - discussed above, only gets you halfway there. The line must be - tokenized into a FieldSet, which can then be - mapped to an object, as described below. -
- -
- LineTokenizer - - An abstraction for turning a line of input into a line into a - FieldSet is necessary because there can be many - formats of flat file data that need to be converted to a - FieldSet. In Spring Batch, this interface is - the LineTokenizer: - - public interface LineTokenizer { - - FieldSet tokenize(String line); - -} - - The contract of a LineTokenizer is such - that, given a line of input (in theory the - String could encompass more than one line), a - FieldSet representing the line will be - returned. This FieldSet can then be passed to a - FieldSetMapper. Spring Batch contains the - following LineTokenizer implementations: - - - - DelmitedLineTokenizer - Used for - files where fields in a record are separated by a delimiter. The - most common delimiter is a comma, but pipes or semicolons are - often used as well. - - - - FixedLengthTokenizer - Used for files - where fields in a record are each a 'fixed width'. The width of - each field must be defined for each record type. - - - - PatternMatchingCompositeLineTokenizer - - Determines which among a list of - LineTokenizers should be used on a - particular line by checking against a pattern. - - -
- -
- FieldSetMapper - - The FieldSetMapper interface defines a - single method, mapFieldSet, which takes a - FieldSet object and maps its contents to an - object. This object may be a custom DTO, a domain object, or a simple - array, depending on the needs of the job. The - FieldSetMapper is used in conjunction with the - LineTokenizer to translate a line of data from - a resource into an object of the desired type: - - public interface FieldSetMapper<T> { - - T mapFieldSet(FieldSet fieldSet); - -} - - The pattern used is the same as the - RowMapper used by - JdbcTemplate. -
- -
- DefaultLineMapper - - Now that the basic interfaces for reading in flat files have - been defined, it becomes clear that three basic steps are - required: - - Read one line from the file. - - - - Pass the string line into the - LineTokenizer#tokenize() method, in - order to retrieve a FieldSet. - - - - Pass the FieldSet returned from - tokenizing to a FieldSetMapper, returning - the result from the ItemReader#read() - method. - - - - The two interfaces described above represent two separate tasks: - converting a line into a FieldSet, and mapping - a FieldSet to a domain object. Because the - input of a LineTokenizer matches the input of - the LineMapper (a line), and the output of a - FieldSetMapper matches the output of the - LineMapper, a default implementation that uses - both a LineTokenizer and - FieldSetMapper is provided. The - DefaultLineMapper represents the behavior most - users will need: - - public class DefaultLineMapper<T> implements LineMapper<T>, InitializingBean { - - private LineTokenizer tokenizer; - - private FieldSetMapper<T> fieldSetMapper; - - public T mapLine(String line, int lineNumber) throws Exception { - return fieldSetMapper.mapFieldSet(tokenizer.tokenize(line)); - } - - public void setLineTokenizer(LineTokenizer tokenizer) { - this.tokenizer = tokenizer; - } - - public void setFieldSetMapper(FieldSetMapper<T> fieldSetMapper) { - this.fieldSetMapper = fieldSetMapper; - } -} - - The above functionality is provided in a default implementation, - rather than being built into the reader itself (as was done in - previous versions of the framework) in order to allow users greater - flexibility in controlling the parsing process, especially if access - to the raw line is needed. -
- -
- Simple Delimited File Reading Example - - The following example will be used to illustrate this using an - actual domain scenario. This particular batch job reads in football - players from the following file: - - ID,lastName,firstName,position,birthYear,debutYear -"AbduKa00,Abdul-Jabbar,Karim,rb,1974,1996", -"AbduRa00,Abdullah,Rabih,rb,1975,1999", -"AberWa00,Abercrombie,Walter,rb,1959,1982", -"AbraDa00,Abramowicz,Danny,wr,1945,1967", -"AdamBo00,Adams,Bob,te,1946,1969", -"AdamCh00,Adams,Charlie,wr,1979,2003" - - The contents of this file will be mapped to the following - Player domain object: - - public class Player implements Serializable { - - private String ID; - private String lastName; - private String firstName; - private String position; - private int birthYear; - private int debutYear; - - public String toString() { - return "PLAYER:ID=" + ID + ",Last Name=" + lastName + - ",First Name=" + firstName + ",Position=" + position + - ",Birth Year=" + birthYear + ",DebutYear=" + - debutYear; - } - - // setters and getters... -} - - In order to map a FieldSet into a - Player object, a - FieldSetMapper that returns players needs to be - defined: - - protected static class PlayerFieldSetMapper implements FieldSetMapper<Player> { - public Player mapFieldSet(FieldSet fieldSet) { - Player player = new Player(); - - player.setID(fieldSet.readString(0)); - player.setLastName(fieldSet.readString(1)); - player.setFirstName(fieldSet.readString(2)); - player.setPosition(fieldSet.readString(3)); - player.setBirthYear(fieldSet.readInt(4)); - player.setDebutYear(fieldSet.readInt(5)); - - return player; - } -} - - The file can then be read by correctly constructing a - FlatFileItemReader and calling - read: - - FlatFileItemReader<Player> itemReader = new FlatFileItemReader<Player>(); -itemReader.setResource(new FileSystemResource("resources/players.csv")); -//DelimitedLineTokenizer defaults to comma as its delimiter -DefaultLineMapper<Player> lineMapper = new DefaultLineMapper<Player>(); -lineMapper.setLineTokenizer(new DelimitedLineTokenizer()); -lineMapper.setFieldSetMapper(new PlayerFieldSetMapper()); -itemReader.setLineMapper(lineMapper); -itemReader.open(new ExecutionContext()); -Player player = itemReader.read(); - - Each call to read will return a new - Player object from each line in the file. When the end of the file is - reached, null will be returned. -
- -
- Mapping Fields by Name - - There is one additional piece of functionality that is allowed - by both DelimitedLineTokenizer and - FixedLengthTokenizer that is similar in - function to a Jdbc ResultSet. The names of the - fields can be injected into either of these - LineTokenizer implementations to increase the - readability of the mapping function. First, the column names of all - fields in the flat file are injected into the tokenizer: - - tokenizer.setNames(new String[] {"ID", "lastName","firstName","position","birthYear","debutYear"}); - - A FieldSetMapper can use this information - as follows: - - public class PlayerMapper implements FieldSetMapper<Player> { - public Player mapFieldSet(FieldSet fs) { - - if(fs == null){ - return null; - } - - Player player = new Player(); - player.setID(fs.readString("ID")); - player.setLastName(fs.readString("lastName")); - player.setFirstName(fs.readString("firstName")); - player.setPosition(fs.readString("position")); - player.setDebutYear(fs.readInt("debutYear")); - player.setBirthYear(fs.readInt("birthYear")); - - return player; - } -} -
- -
- Automapping FieldSets to Domain Objects - - For many, having to write a specific - FieldSetMapper is equally as cumbersome as - writing a specific RowMapper for a - JdbcTemplate. Spring Batch makes this easier by - providing a FieldSetMapper that automatically - maps fields by matching a field name with a setter on the object using - the JavaBean specification. Again using the football example, the - BeanWrapperFieldSetMapper configuration looks - like the following: - - <bean id="fieldSetMapper" - class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper"> - <property name="prototypeBeanName" value="player" /> -</bean> - -<bean id="player" - class="org.springframework.batch.sample.domain.Player" - scope="prototype" /> - - For each entry in the FieldSet, the - mapper will look for a corresponding setter on a new instance of the - Player object (for this reason, prototype scope - is required) in the same way the Spring container will look for - setters matching a property name. Each available field in the - FieldSet will be mapped, and the resultant - Player object will be returned, with no code - required. -
- -
- Fixed Length File Formats - - So far only delimited files have been discussed in much detail, - however, they represent only half of the file reading picture. Many - organizations that use flat files use fixed length formats. An example - fixed length file is below: - - UK21341EAH4121131.11customer1 -UK21341EAH4221232.11customer2 -UK21341EAH4321333.11customer3 -UK21341EAH4421434.11customer4 -UK21341EAH4521535.11customer5 - - While this looks like one large field, it actually represent 4 - distinct fields: - - - - ISIN: Unique identifier for the item being order - 12 - characters long. - - - - Quantity: Number of this item being ordered - 3 characters - long. - - - - Price: Price of the item - 5 characters long. - - - - Customer: Id of the customer ordering the item - 9 - characters long. - - - - When configuring the - FixedLengthLineTokenizer, each of these lengths - must be provided in the form of ranges: - - <bean id="fixedLengthLineTokenizer" - class="org.springframework.batch.io.file.transform.FixedLengthTokenizer"> - <property name="names" value="ISIN,Quantity,Price,Customer" /> - <property name="columns" value="1-12, 13-15, 16-20, 21-29" /> -</bean> - - Because the FixedLengthLineTokenizer uses - the same LineTokenizer interface as discussed - above, it will return the same FieldSet as if a - delimiter had been used. This allows the same approaches to be used in - handling its output, such as using the - BeanWrapperFieldSetMapper. - - - Supporting the above syntax for ranges requires that a - specialized property editor, - RangeArrayPropertyEditor, be configured in - the ApplicationContext. However, this bean - is automatically declared in an - ApplicationContext where the batch - namespace is used. - -
- -
- Multiple Record Types within a Single File - - All of the file reading examples up to this point have all made - a key assumption for simplicity's sake: all of the records in a file - have the same format. However, this may not always be the case. It is - very common that a file might have records with different formats that - need to be tokenized differently and mapped to different objects. The - following excerpt from a file illustrates this: - - USER;Smith;Peter;;T;20014539;F -LINEA;1044391041ABC037.49G201XX1383.12H -LINEB;2134776319DEF422.99M005LI - - In this file we have three types of records, "USER", "LINEA", - and "LINEB". A "USER" line corresponds to a User object. "LINEA" and - "LINEB" both correspond to Line objects, though a "LINEA" has more - information than a "LINEB". - - The ItemReader will read each line - individually, but we must specify different - LineTokenizer and - FieldSetMapper objects so that the - ItemWriter will receive the correct items. The - PatternMatchingCompositeLineMapper makes this - easy by allowing maps of patterns to - LineTokenizers and patterns to - FieldSetMappers to be configured: - - <bean id="orderFileLineMapper" - class="org.spr...PatternMatchingCompositeLineMapper"> - <property name="tokenizers"> - <map> - <entry key="USER*" value-ref="userTokenizer" /> - <entry key="LINEA*" value-ref="lineATokenizer" /> - <entry key="LINEB*" value-ref="lineBTokenizer" /> - </map> - </property> - <property name="fieldSetMappers"> - <map> - <entry key="USER*" value-ref="userFieldSetMapper" /> - <entry key="LINE*" value-ref="lineFieldSetMapper" /> - </map> - </property> -</bean> - - In this example, "LINEA" and "LINEB" have separate - LineTokenizers but they both use the same - FieldSetMapper. - - The PatternMatchingCompositeLineMapper - makes use of the PatternMatcher's - match method in order to select the correct - delegate for each line. The PatternMatcher - allows for two wildcard characters with special meaning: the question - mark ("?") will match exactly one character, while the asterisk ("*") - will match zero or more characters. Note that in the configuration - above, all patterns end with an asterisk, making them effectively - prefixes to lines. The PatternMatcher will - always match the most specific pattern possible, regardless of the - order in the configuration. So if "LINE*" and "LINEA*" were both - listed as patterns, "LINEA" would match pattern "LINEA*", while - "LINEB" would match pattern "LINE*". Additionally, a single asterisk - ("*") can serve as a default by matching any line not matched by any - other pattern. - - <entry key="*" value-ref="defaultLineTokenizer" /> - - There is also a - PatternMatchingCompositeLineTokenizer that can - be used for tokenization alone. - - It is also common for a flat file to contain records that each - span multiple lines. To handle this situation, a more complex strategy - is required. A demonstration of this common pattern can be found in - . -
- -
- Exception Handling in Flat Files - - There are many scenarios when tokenizing a line may cause - exceptions to be thrown. Many flat files are imperfect and contain - records that aren't formatted correctly. Many users choose to skip - these erroneous lines, logging out the issue, original line, and line - number. These logs can later be inspected manually or by another batch - job. For this reason, Spring Batch provides a hierarchy of exceptions - for handling parse exceptions: - FlatFileParseException and - FlatFileFormatException. - FlatFileParseException is thrown by the - FlatFileItemReader when any errors are - encountered while trying to read a file. - FlatFileFormatException is thrown by - implementations of the LineTokenizer interface, - and indicates a more specific error encountered while - tokenizing. - -
- IncorrectTokenCountException - - Both DelimitedLineTokenizer and - FixedLengthLineTokenizer have the ability to - specify column names that can be used for creating a - FieldSet. However, if the number of column - names doesn't match the number of columns found while tokenizing a - line the FieldSet can't be created, and a - IncorrectTokenCountException is thrown, which - contains the number of tokens encountered, and the number - expected: - - tokenizer.setNames(new String[] {"A", "B", "C", "D"}); - -try { - tokenizer.tokenize("a,b,c"); -} -catch(IncorrectTokenCountException e){ - assertEquals(4, e.getExpectedCount()); - assertEquals(3, e.getActualCount()); -} - - Because the tokenizer was configured with 4 column names, but - only 3 tokens were found in the file, an - IncorrectTokenCountException was - thrown. -
- -
- IncorrectLineLengthException - - Files formatted in a fixed length format have additional - requirements when parsing because, unlike a delimited format, each - column must strictly adhere to its predefined width. If the total - line length doesn't add up to the widest value of this column, an - exception is thrown: - - tokenizer.setColumns(new Range[] { new Range(1, 5), - new Range(6, 10), - new Range(11, 15) }); -try { - tokenizer.tokenize("12345"); - fail("Expected IncorrectLineLengthException"); -} -catch (IncorrectLineLengthException ex) { - assertEquals(15, ex.getExpectedLength()); - assertEquals(5, ex.getActualLength()); -} - - The configured ranges for the tokenizer above are: 1-5, 6-10, - and 11-15, thus the total length of the line expected is 15. - However, in this case a line of length 5 was passed in, causing an - IncorrectLineLengthException to be thrown. - Throwing an exception here rather than only mapping the first column - allows the processing of the line to fail earlier, and with more - information than it would if it failed while trying to read in - column 2 in a FieldSetMapper. However, there - are scenarios where the length of the line isn't always constant. - For this reason, validation of line length can be turned off via the - 'strict' property: - - tokenizer.setColumns(new Range[] { new Range(1, 5), new Range(6, 10) }); -tokenizer.setStrict(false); -FieldSet tokens = tokenizer.tokenize("12345"); -assertEquals("12345", tokens.readString(0)); -assertEquals("", tokens.readString(1)); - - The above example is almost identical to the one before it, - except that tokenizer.setStrict(false) was called. This setting - tells the tokenizer to not enforce line lengths when tokenizing the - line. A FieldSet is now correctly created and - returned. However, it will only contain empty tokens for the - remaining values. -
-
-
- -
- FlatFileItemWriter - - Writing out to flat files has the same problems and issues that - reading in from a file must overcome. A step must be able to write out - in either delimited or fixed length formats in a transactional - manner. - -
- LineAggregator - - Just as the LineTokenizer interface is - necessary to take an item and turn it into a - String, file writing must have a way to - aggregate multiple fields into a single string for writing to a file. - In Spring Batch this is the - LineAggregator: - - public interface LineAggregator<T> { - - public String aggregate(T item); - -} - - The LineAggregator is the opposite of a - LineTokenizer. - LineTokenizer takes a - String and returns a - FieldSet, whereas - LineAggregator takes an - item and returns a - String. - -
- PassThroughLineAggregator - - The most basic implementation of the LineAggregator interface - is the PassThroughLineAggregator, which - simply assumes that the object is already a string, or that its - string representation is acceptable for writing: - - public class PassThroughLineAggregator<T> implements LineAggregator<T> { - - public String aggregate(T item) { - return item.toString(); - } -} - - The above implementation is useful if direct control of - creating the string is required, but the advantages of a - FlatFileItemWriter, such as transaction and - restart support, are necessary. -
-
- -
- Simplified File Writing Example - - Now that the LineAggregator interface and - its most basic implementation, - PassThroughLineAggregator, have been defined, - the basic flow of writing can be explained: - - - - The object to be written is passed to the - LineAggregator in order to obtain a - String. - - - - The returned String is written to the - configured file. - - - - The following excerpt from the - FlatFileItemWriter expresses this in - code: - - public void write(T item) throws Exception { - write(lineAggregator.aggregate(item) + LINE_SEPARATOR); -} - - A simple configuration would look like the following: - - <bean id="itemWriter" class="org.spr...FlatFileItemWriter"> - <property name="resource" value="file:target/test-outputs/output.txt" /> - <property name="lineAggregator"> - <bean class="org.spr...PassThroughLineAggregator"/> - </property> -</bean> -
- -
- FieldExtractor - - The above example may be useful for the most basic uses of a - writing to a file. However, most users of the - FlatFileItemWriter will have a domain object - that needs to be written out, and thus must be converted into a line. - In file reading, the following was required: - - Read one line from the file. - - - - Pass the string line into the - LineTokenizer#tokenize() method, in - order to retrieve a FieldSet - - - - Pass the FieldSet returned from - tokenizing to a FieldSetMapper, returning - the result from the ItemReader#read() - method - - - - File writing has similar, but inverse steps: - - - - Pass the item to be written to the writer - - - - convert the fields on the item into an array - - - - aggregate the resulting array into a line - - - - Because there is no way for the framework to know which fields - from the object need to be written out, a - FieldExtractor must be written to accomplish - the task of turning the item into an array: - - public interface FieldExtractor<T> { - - Object[] extract(T item); - -} - - Implementations of the FieldExtractor - interface should create an array from the fields of the provided - object, which can then be written out with a delimiter between the - elements, or as part of a field-width line. - -
- PassThroughFieldExtractor - - There are many cases where a collection, such as an array, - Collection, or - FieldSet, needs to be written out. - "Extracting" an array from a one of these collection types is very - straightforward: simply convert the collection to an array. - Therefore, the PassThroughFieldExtractor - should be used in this scenario. It should be noted, that if the - object passed in is not a type of collection, then the - PassThroughFieldExtractor will return an - array containing solely the item to be extracted. -
- -
- BeanWrapperFieldExtractor - - As with the BeanWrapperFieldSetMapper - described in the file reading section, it is often preferable to - configure how to convert a domain object to an object array, rather - than writing the conversion yourself. The - BeanWrapperFieldExtractor provides just this - type of functionality: - - BeanWrapperFieldExtractor<Name> extractor = new BeanWrapperFieldExtractor<Name>(); -extractor.setNames(new String[] { "first", "last", "born" }); - -String first = "Alan"; -String last = "Turing"; -int born = 1912; - -Name n = new Name(first, last, born); -Object[] values = extractor.extract(n); - -assertEquals(first, values[0]); -assertEquals(last, values[1]); -assertEquals(born, values[2]); - - This extractor implementation has only one required property, - the names of the fields to map. Just as the - BeanWrapperFieldSetMapper needs field names - to map fields on the FieldSet to setters on - the provided object, the - BeanWrapperFieldExtractor needs names to map - to getters for creating an object array. It is worth noting that the - order of the names determines the order of the fields within the - array. -
-
- -
- Delimited File Writing Example - - The most basic flat file format is one in which all fields are - separated by a delimiter. This can be accomplished using a - DelimitedLineAggregator. The example below - writes out a simple domain object that represents a credit to a - customer account: - - public class CustomerCredit { - - private int id; - private String name; - private BigDecimal credit; - - //getters and setters removed for clarity -} - - Because a domain object is being used, an implementation of the - FieldExtractor interface must be provided, along with the delimiter to - use: - - <bean id="itemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter"> - <property name="resource" ref="outputResource" /> - <property name="lineAggregator"> - <bean class="org.spr...DelimitedLineAggregator"> - <property name="delimiter" value=","/> - <property name="fieldExtractor"> - <bean class="org.spr...BeanWrapperFieldExtractor"> - <property name="names" value="name,credit"/> - </bean> - </property> - </bean> - </property> -</bean> - - In this case, the - BeanWrapperFieldExtractor described earlier in - this chapter is used to turn the name and credit fields within - CustomerCredit into an object array, which is - then written out with commas between each field. -
- -
- Fixed Width File Writing Example - - Delimited is not the only type of flat file format. Many prefer - to use a set width for each column to delineate between fields, which - is usually referred to as 'fixed width'. Spring Batch supports this in - file writing via the FormatterLineAggregator. - Using the same CustomerCredit domain object - described above, it can be configured as follows: - - <bean id="itemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter"> - <property name="resource" ref="outputResource" /> - <property name="lineAggregator"> - <bean class="org.spr...FormatterLineAggregator"> - <property name="fieldExtractor"> - <bean class="org.spr...BeanWrapperFieldExtractor"> - <property name="names" value="name,credit" /> - </bean> - </property> - <property name="format" value="%-9s%-2.0f" /> - </bean> - </property> -</bean> - - Most of the above example should look familiar. However, the - value of the format property is new: - - <property name="format" value="%-9s%-2.0f" /> - - The underlying implementation is built using the same - Formatter added as part of Java 5. The Java - Formatter is based on the - printf functionality of the C programming - language. Most details on how to configure a formatter can be found in - the javadoc of Formatter. -
- -
- Handling File Creation - - FlatFileItemReader has a very simple - relationship with file resources. When the reader is initialized, it - opens the file if it exists, and throws an exception if it does not. - File writing isn't quite so simple. At first glance it seems like a - similar straight forward contract should exist for - FlatFileItemWriter: if the file already exists, - throw an exception, and if it does not, create it and start writing. - However, potentially restarting a Job can cause - issues. In normal restart scenarios, the contract is reversed: if the - file exists, start writing to it from the last known good position, - and if it does not, throw an exception. However, what happens if the - file name for this job is always the same? In this case, you would - want to delete the file if it exists, unless it's a restart. Because - of this possibility, the FlatFileItemWriter - contains the property, shouldDeleteIfExists. - Setting this property to true will cause an existing file with the - same name to be deleted when the writer is opened. -
-
-
- -
- XML Item Readers and Writers - - Spring Batch provides transactional infrastructure for both reading - XML records and mapping them to Java objects as well as writing Java - objects as XML records. - - - Constraints on streaming XML - - The StAX API is used for I/O as other standard XML parsing APIs do - not fit batch processing requirements (DOM loads the whole input into - memory at once and SAX controls the parsing process allowing the user - only to provide callbacks). - - - Lets take a closer look how XML input and output works in Spring - Batch. First, there are a few concepts that vary from file reading and - writing but are common across Spring Batch XML processing. With XML - processing, instead of lines of records (FieldSets) that need to be - tokenized, it is assumed an XML resource is a collection of 'fragments' - corresponding to individual records: - - - - - - - - - - - Figure 3.1: XML Input - - - The 'trade' tag is defined as the 'root element' in the scenario - above. Everything between '<trade>' and '</trade>' is - considered one 'fragment'. Spring Batch uses Object/XML Mapping (OXM) to - bind fragments to objects. However, Spring Batch is not tied to any - particular XML binding technology. Typical use is to delegate to Spring - OXM, which provides uniform abstraction for the most - popular OXM technologies. The dependency on Spring OXM is optional and you - can choose to implement Spring Batch specific interfaces if desired. The - relationship to the technologies that OXM supports can be shown as the - following: - - - - - - - - - - - Figure 3.2: OXM Binding - - - Now with an introduction to OXM and how one can use XML fragments to - represent records, let's take a closer look at readers and writers. - -
- StaxEventItemReader - - The StaxEventItemReader configuration - provides a typical setup for the processing of records from an XML input - stream. First, lets examine a set of XML records that the - StaxEventItemReader can process. - - <?xml version="1.0" encoding="UTF-8"?> -<records> - <trade xmlns="http://springframework.org/batch/sample/io/oxm/domain"> - <isin>XYZ0001</isin> - <quantity>5</quantity> - <price>11.39</price> - <customer>Customer1</customer> - </trade> - <trade xmlns="http://springframework.org/batch/sample/io/oxm/domain"> - <isin>XYZ0002</isin> - <quantity>2</quantity> - <price>72.99</price> - <customer>Customer2c</customer> - </trade> - <trade xmlns="http://springframework.org/batch/sample/io/oxm/domain"> - <isin>XYZ0003</isin> - <quantity>9</quantity> - <price>99.99</price> - <customer>Customer3</customer> - </trade> -</records> - - To be able to process the XML records the following is needed: - - - Root Element Name - Name of the root element of the fragment - that constitutes the object to be mapped. The example - configuration demonstrates this with the value of trade. - - - - Resource - Spring Resource that represents the file to be - read. - - - - Unmarshaller - Unmarshalling - facility provided by Spring OXM for mapping the XML fragment to an - object. - - - - <bean id="itemReader" class="org.springframework.batch.item.xml.StaxEventItemReader"> - <property name="fragmentRootElementName" value="trade" /> - <property name="resource" value="data/iosample/input/input.xml" /> - <property name="unmarshaller" ref="tradeMarshaller" /> -</bean> - - Notice that in this example we have chosen to use an - XStreamMarshaller which accepts an alias passed - in as a map with the first key and value being the name of the fragment - (i.e. root element) and the object type to bind. Then, similar to a - FieldSet, the names of the other elements that - map to fields within the object type are described as key/value pairs in - the map. In the configuration file we can use a Spring configuration - utility to describe the required alias as follows: - - <bean id="tradeMarshaller" - class="org.springframework.oxm.xstream.XStreamMarshaller"> - <property name="aliases"> - <util:map id="aliases"> - <entry key="trade" - value="org.springframework.batch.sample.domain.Trade" /> - <entry key="price" value="java.math.BigDecimal" /> - <entry key="name" value="java.lang.String" /> - </util:map> - </property> -</bean> - - On input the reader reads the XML resource until it recognizes - that a new fragment is about to start (by matching the tag name by - default). The reader creates a standalone XML document from the fragment - (or at least makes it appear so) and passes the document to a - deserializer (typically a wrapper around a Spring OXM - Unmarshaller) to map the XML to a Java - object. - - In summary, this procedure is analogous to the following scripted - Java code which uses the injection provided by the Spring - configuration: - - StaxEventItemReader xmlStaxEventItemReader = new StaxEventItemReader() -Resource resource = new ByteArrayResource(xmlResource.getBytes()) - -Map aliases = new HashMap(); -aliases.put("trade","org.springframework.batch.sample.domain.Trade"); -aliases.put("price","java.math.BigDecimal"); -aliases.put("customer","java.lang.String"); -XStreamMarshaller unmarshaller = new XStreamMarshaller(); -unmarshaller.setAliases(aliases); -xmlStaxEventItemReader.setUnmarshaller(unmarshaller); -xmlStaxEventItemReader.setResource(resource); -xmlStaxEventItemReader.setFragmentRootElementName("trade"); -xmlStaxEventItemReader.open(new ExecutionContext()); - -boolean hasNext = true - -CustomerCredit credit = null; - -while (hasNext) { - credit = xmlStaxEventItemReader.read(); - if (credit == null) { - hasNext = false; - } - else { - System.out.println(credit); - } -} -
- -
- StaxEventItemWriter - - Output works symmetrically to input. The - StaxEventItemWriter needs a - Resource, a marshaller, and a rootTagName. A Java - object is passed to a marshaller (typically a standard Spring OXM - Marshaller) which writes to a - Resource using a custom event writer that filters - the StartDocument and - EndDocument events produced for each fragment by - the OXM tools. We'll show this in an example using the - MarshallingEventWriterSerializer. The Spring - configuration for this setup looks as follows: - - <bean id="itemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter"> - <property name="resource" ref="outputResource" /> - <property name="marshaller" ref="customerCreditMarshaller" /> - <property name="rootTagName" value="customers" /> - <property name="overwriteOutput" value="true" /> -</bean> - - The configuration sets up the three required properties and - optionally sets the overwriteOutput=true, mentioned earlier in the - chapter for specifying whether an existing file can be overwritten. It - should be noted the marshaller used for the writer is the exact same as - the one used in the reading example from earlier in the chapter: - - <bean id="customerCreditMarshaller" - class="org.springframework.oxm.xstream.XStreamMarshaller"> - <property name="aliases"> - <util:map id="aliases"> - <entry key="customer" - value="org.springframework.batch.sample.domain.CustomerCredit" /> - <entry key="credit" value="java.math.BigDecimal" /> - <entry key="name" value="java.lang.String" /> - </util:map> - </property> -</bean> - - To summarize with a Java example, the following code illustrates - all of the points discussed, demonstrating the programmatic setup of the - required properties: - - StaxEventItemWriter staxItemWriter = new StaxEventItemWriter() -FileSystemResource resource = new FileSystemResource("data/outputFile.xml") - -Map aliases = new HashMap(); -aliases.put("customer","org.springframework.batch.sample.domain.CustomerCredit"); -aliases.put("credit","java.math.BigDecimal"); -aliases.put("name","java.lang.String"); -Marshaller marshaller = new XStreamMarshaller(); -marshaller.setAliases(aliases); - -staxItemWriter.setResource(resource); -staxItemWriter.setMarshaller(marshaller); -staxItemWriter.setRootTagName("trades"); -staxItemWriter.setOverwriteOutput(true); - -ExecutionContext executionContext = new ExecutionContext(); -staxItemWriter.open(executionContext); -CustomerCredit Credit = new CustomerCredit(); -trade.setPrice(11.39); -credit.setName("Customer1"); -staxItemWriter.write(trade); -
-
- -
- Multi-File Input - - It is a common requirement to process multiple files within a single - Step. Assuming the files all have the same - formatting, the MultiResourceItemReader supports - this type of input for both XML and flat file processing. Consider the - following files in a directory: - - file-1.txt file-2.txt ignored.txt - - file-1.txt and file-2.txt are formatted the same and for business - reasons should be processed together. The - MuliResourceItemReader can be used to read in both - files by using wildcards: - - <bean id="multiResourceReader" class="org.spr...MultiResourceItemReader"> - <property name="resources" value="classpath:data/input/file-*.txt" /> - <property name="delegate" ref="flatFileItemReader" /> -</bean> - - The referenced delegate is a simple - FlatFileItemReader. The above configuration will - read input from both files, handling rollback and restart scenarios. It - should be noted that, as with any ItemReader, - adding extra input (in this case a file) could cause potential issues when - restarting. It is recommended that batch jobs work with their own - individual directories until completed successfully. -
- -
- Database - - Like most enterprise application styles, a database is the central - storage mechanism for batch. However, batch differs from other application - styles due to the sheer size of the datasets with which the system must - work. If a SQL statement returns 1 million rows, the result set probably - holds all returned results in memory until all rows have been read. Spring - Batch provides two types of solutions for this problem: Cursor and Paging - database ItemReaders. - -
- Cursor Based ItemReaders - - Using a database cursor is generally the default approach of most - batch developers, because it is the database's solution to the problem - of 'streaming' relational data. The Java - ResultSet class is essentially an object - orientated mechanism for manipulating a cursor. A - ResultSet maintains a cursor to the current row - of data. Calling next on a - ResultSet moves this cursor to the next row. - Spring Batch cursor based ItemReaders open the a cursor on - initialization, and move the cursor forward one row for every call to - read, returning a mapped object that can be - used for processing. The close method will then - be called to ensure all resources are freed up. The Spring core - JdbcTemplate gets around this problem by using - the callback pattern to completely map all rows in a - ResultSet and close before returning control back - to the method caller. However, in batch this must wait until the step is - complete. Below is a generic diagram of how a cursor based - ItemReader works, and while a SQL statement is - used as an example since it is so widely known, any technology could - implement the basic approach: - - - - - - - - - - - - This example illustrates the basic pattern. Given a 'FOO' table, - which has three columns: ID, NAME, and BAR, select all rows with an ID - greater than 1 but less than 7. This puts the beginning of the cursor - (row 1) on ID 2. The result of this row should be a completely mapped - Foo object. Calling read() again moves the - cursor to the next row, which is the Foo with an ID of 3. The results of - these reads will be written out after each - read, thus allowing the objects to be garbage - collected (assuming no instance variables are maintaining references to - them). - -
- JdbcCursorItemReader - - JdbcCursorItemReader is the Jdbc - implementation of the cursor based technique. It works directly with a - ResultSet and requires a SQL statement to run - against a connection obtained from a - DataSource. The following database schema will - be used as an example: - - CREATE TABLE CUSTOMER ( - ID BIGINT IDENTITY PRIMARY KEY, - NAME VARCHAR(45), - CREDIT FLOAT -); - - Many people prefer to use a domain object for each row, so we'll - use an implementation of the RowMapper - interface to map a CustomerCredit - object: - - public class CustomerCreditRowMapper implements RowMapper { - - public static final String ID_COLUMN = "id"; - public static final String NAME_COLUMN = "name"; - public static final String CREDIT_COLUMN = "credit"; - - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - CustomerCredit customerCredit = new CustomerCredit(); - - customerCredit.setId(rs.getInt(ID_COLUMN)); - customerCredit.setName(rs.getString(NAME_COLUMN)); - customerCredit.setCredit(rs.getBigDecimal(CREDIT_COLUMN)); - - return customerCredit; - } -} - - Because JdbcTemplate is so familiar to - users of Spring, and the JdbcCursorItemReader - shares key interfaces with it, it is useful to see an example of how - to read in this data with JdbcTemplate, in - order to contrast it with the ItemReader. For - the purposes of this example, let's assume there are 1,000 rows in the - CUSTOMER database. The first example will be using - JdbcTemplate: - - //For simplicity sake, assume a dataSource has already been obtained -JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); -List customerCredits = jdbcTemplate.query("SELECT ID, NAME, CREDIT from CUSTOMER", - new CustomerCreditRowMapper()); - - After running this code snippet the customerCredits list will - contain 1,000 CustomerCredit objects. In the - query method, a connection will be obtained from the - DataSource, the provided SQL will be run - against it, and the mapRow method will be - called for each row in the ResultSet. Let's - contrast this with the approach of the - JdbcCursorItemReader: - - JdbcCursorItemReader itemReader = new JdbcCursorItemReader(); -itemReader.setDataSource(dataSource); -itemReader.setSql("SELECT ID, NAME, CREDIT from CUSTOMER"); -itemReader.setRowMapper(new CustomerCreditRowMapper()); -int counter = 0; -ExecutionContext executionContext = new ExecutionContext(); -itemReader.open(executionContext); -Object customerCredit = new Object(); -while(customerCredit != null){ - customerCredit = itemReader.read(); - counter++; -} -itemReader.close(executionContext); - - After running this code snippet the counter will equal 1,000. If - the code above had put the returned customerCredit into a list, the - result would have been exactly the same as with the - JdbcTemplate example. However, the big - advantage of the ItemReader is that it allows - items to be 'streamed'. The read method can - be called once, and the item written out via an - ItemWriter, and then the next item obtained via - read. This allows item reading and writing to - be done in 'chunks' and committed periodically, which is the essence - of high performance batch processing. Furthermore, it is very easily - configured for injection into a Spring Batch - Step: - - <bean id="itemReader" class="org.spr...JdbcCursorItemReader"> - <property name="dataSource" ref="dataSource"/> - <property name="sql" value="select ID, NAME, CREDIT from CUSTOMER"/> - <property name="rowMapper"> - <bean class="org.springframework.batch.sample.domain.CustomerCreditRowMapper"/> - </property> -</bean> - -
- Additional Properties - - Because there are so many varying options for opening a cursor - in Java, there are many properties on the - JdbcCustorItemReader that can be set: - - - JdbcCursorItemReader Properties - - - - - ignoreWarnings - - Determines whether or not SQLWarnings are logged or - cause an exception - default is true - - - - fetchSize - - Gives the Jdbc driver a hint as to the number of rows - that should be fetched from the database when more rows are - needed by the ResultSet object used - by the ItemReader. By default, no - hint is given. - - - - maxRows - - Sets the limit for the maximum number of rows the - underlying ResultSet can hold at any - one time. - - - - queryTimeout - - Sets the number of seconds the driver will wait for a - Statement object to execute to the - given number of seconds. If the limit is exceeded, a - DataAccessEception is thrown. - (Consult your driver vendor documentation for - details). - - - - verifyCursorPosition - - Because the same ResultSet - held by the ItemReader is passed to - the RowMapper, it is possible for - users to call ResultSet.next() - themselves, which could cause issues with the reader's - internal count. Setting this value to true will cause an - exception to be thrown if the cursor position is not the - same after the RowMapper call as it - was before. - - - - saveState - - Indicates whether or not the reader's state should be - saved in the ExecutionContext - provided by - ItemStream#update(ExecutionContext) - The default value is true. - - - - driverSupportsAbsolute - - Defaults to false. Indicates whether the Jdbc driver - supports setting the absolute row on a - ResultSet. It is recommended that - this is set to true for Jdbc drivers that supports - ResultSet.absolute() as it may - improve performance, especially if a step fails while - working with a large data set. - - - - setUseSharedExtendedConnection - - Defaults to false. Indicates whether the connection - used for the cursor should be used by all other processing - thus sharing the same transaction. If this is set to false, - which is the default, then the cursor will be opened using - its own connection and will not participate in any - transactions started for the rest of the step processing. If - you set this flag to true then you must wrap the - DataSource in an - ExtendedConnectionDataSourceProxy to - prevent the connection from being closed and released after - each commit. When you set this option to true then the - statement used to open the cursor will be created with both - 'READ_ONLY' and 'HOLD_CUSORS_OVER_COMMIT' options. This - allows holding the cursor open over transaction start and - commits performed in the step processing. To use this - feature you need a database that supports this and a Jdbc - driver supporting Jdbc 3.0 or later. - - - -
-
-
- -
- HibernateCursorItemReader - - Just as normal Spring users make important decisions about - whether or not to use ORM solutions, which affect whether or not they - use a JdbcTemplate or a - HibernateTemplate, Spring Batch users have the - same options. HibernateCursorItemReader is the - Hibernate implementation of the cursor technique. Hibernate's usage in - batch has been fairly controversial. This has largely been because - Hibernate was originally developed to support online application - styles. However, that doesn't mean it can't be used for batch - processing. The easiest approach for solving this problem is to use a - StatelessSession rather than a standard - session. This removes all of the caching and dirty checking hibernate - employs that can cause issues in a batch scenario. For more - information on the differences between stateless and normal hibernate - sessions, refer to the documentation of your specific hibernate - release. The HibernateCursorItemReader allows - you to declare an HQL statement and pass in a - SessionFactory, which will pass back one item - per call to read in the same basic fashion as - the JdbcCursorItemReader. Below is an example - configuration using the same 'customer credit' example as the JDBC - reader: - - HibernateCursorItemReader itemReader = new HibernateCursorItemReader(); -itemReader.setQueryString("from CustomerCredit"); -//For simplicity sake, assume sessionFactory already obtained. -itemReader.setSessionFactory(sessionFactory); -itemReader.setUseStatelessSession(true); -int counter = 0; -ExecutionContext executionContext = new ExecutionContext(); -itemReader.open(executionContext); -Object customerCredit = new Object(); -while(customerCredit != null){ - customerCredit = itemReader.read(); - counter++; -} -itemReader.close(executionContext); - - This configured ItemReader will return - CustomerCredit objects in the exact same manner - as described by the JdbcCursorItemReader, - assuming hibernate mapping files have been created correctly for the - Customer table. The 'useStatelessSession' property defaults to true, - but has been added here to draw attention to the ability to switch it - on or off. It is also worth noting that the fetchSize of the - underlying cursor can be set via the setFetchSize property. As with - JdbcCursorItemReader, configuration is - straightforward: - - <bean id="itemReader" - class="org.springframework.batch.item.database.HibernateCursorItemReader"> - <property name="sessionFactory" ref="sessionFactory" /> - <property name="queryString" value="from CustomerCredit" /> -</bean> -
- -
- StoredProcedureItemReader - - Sometimes it is necessary to obtain the cursor data using a - stored procedure. The StoredProcedureItemReader - works like the JdbcCursorItemReader except that - instead of executing a query to obtain a cursor we execute a stored - procedure that returns a cursor. The stored procedure can return the - cursor in three different ways: - - - - as a returned ResultSet (used by SQL Server, Sybase, DB2, - Derby and MySQL) - - - - as a ref-cursor returned as an out parameter (used by Oracle - and PostgreSQL) - - - - as the return value of a stored function call - - - - Below is a basic example configuration using the same 'customer - credit' example as earlier: - - <bean id="reader" class="o.s.batch.item.database.StoredProcedureItemReader"> - <property name="dataSource" ref="dataSource"/> - <property name="procedureName" value="sp_customer_credit"/> - <property name="rowMapper"> - <bean class="org.springframework.batch.sample.domain.CustomerCreditRowMapper"/> - </property> -</bean> - - - This example relies on the stored procedure to provide a - ResultSet as a returned result (option 1 above). - - If the stored procedure returned a ref-cursor (option 2) then we - would need to provide the position of the out parameter that is the - returned ref-cursor. Here is an example where the first parameter is - the returned ref-cursor: - - <bean id="reader" class="o.s.batch.item.database.StoredProcedureItemReader"> - <property name="dataSource" ref="dataSource"/> - <property name="procedureName" value="sp_customer_credit"/> - <property name="refCursorPosition" value="1"/> - <property name="rowMapper"> - <bean class="org.springframework.batch.sample.domain.CustomerCreditRowMapper"/> - </property> -</bean> - - - If the cursor was returned from a stored function (option 3) we - would need to set the property "function" to - true. It defaults to false. Here - is what that would look like: - - <bean id="reader" class="o.s.batch.item.database.StoredProcedureItemReader"> - <property name="dataSource" ref="dataSource"/> - <property name="procedureName" value="sp_customer_credit"/> - <property name="function" value="true"/> - <property name="rowMapper"> - <bean class="org.springframework.batch.sample.domain.CustomerCreditRowMapper"/> - </property> -</bean> - - - In all of these cases we need to define a - RowMapper as well as a - DataSource and the actual procedure - name. - - If the stored procedure or function takes in parameter then they - must be declared and set via the parameters property. Here is an - example for Oracle that declares three parameters. The first one is - the out parameter that returns the ref-cursor, the second and third - are in parameters that takes a value of type INTEGER: - - <bean id="reader" class="o.s.batch.item.database.StoredProcedureItemReader"> - <property name="dataSource" ref="dataSource"/> - <property name="procedureName" value="spring.cursor_func"/> - <property name="parameters"> - <list> - <bean class="org.springframework.jdbc.core.SqlOutParameter"> - <constructor-arg index="0" value="newid"/> - <constructor-arg index="1"> - <util:constant static-field="oracle.jdbc.OracleTypes.CURSOR"/> - </constructor-arg> - </bean> - <bean class="org.springframework.jdbc.core.SqlParameter"> - <constructor-arg index="0" value="amount"/> - <constructor-arg index="1"> - <util:constant static-field="java.sql.Types.INTEGER"/> - </constructor-arg> - </bean> - <bean class="org.springframework.jdbc.core.SqlParameter"> - <constructor-arg index="0" value="custid"/> - <constructor-arg index="1"> - <util:constant static-field="java.sql.Types.INTEGER"/> - </constructor-arg> - </bean> - </list> - </property> - <property name="refCursorPosition" value="1"/> - <property name="rowMapper" ref="rowMapper"/> - <property name="preparedStatementSetter" ref="parameterSetter"/> -</bean> - - In addition to the parameter declarations we need to specify a - PreparedStatementSetter implementation that - sets the parameter values for the call. This works the same as for the - JdbcCursorItemReader above. All the additional - properties listed in - apply to the StoredProcedureItemReader as well. - -
-
- -
- Paging ItemReaders - - An alternative to using a database cursor is executing multiple - queries where each query is bringing back a portion of the results. We - refer to this portion as a page. Each query that is executed must - specify the starting row number and the number of rows that we want - returned for the page. - -
- JdbcPagingItemReader - - One implementation of a paging ItemReader - is the JdbcPagingItemReader. The - JdbcPagingItemReader needs a - PagingQueryProvider responsible for providing - the SQL queries used to retrieve the rows making up a page. Since each - database has its own strategy for providing paging support, we need to - use a different PagingQueryProvider for each - supported database type. There is also the - SqlPagingQueryProviderFactoryBean that will - auto-detect the database that is being used and determine the - appropriate PagingQueryProvider implementation. - This simplifies the configuration and is the recommended best - practice. - - The SqlPagingQueryProviderFactoryBean - requires that you specify a select clause and a from clause. You can - also provide an optional where clause. These clauses will be used to - build an SQL statement combined with the required sortKey. - - After the reader has been opened, it will pass back one item per - call to read in the same basic fashion as any - other ItemReader. The paging happens behind the - scenes when additional rows are needed. - - Below is an example configuration using a similar 'customer - credit' example as the cursor based ItemReaders above: - - <bean id="itemReader" class="org.spr...JdbcPagingItemReader"> - <property name="dataSource" ref="dataSource"/> - <property name="queryProvider"> - <bean class="org.spr...SqlPagingQueryProviderFactoryBean"> - <property name="selectClause" value="select id, name, credit"/> - <property name="fromClause" value="from customer"/> - <property name="whereClause" value="where status=:status"/> - <property name="sortKey" value="id"/> - </bean> - </property> - <property name="parameterValues"> - <map> - <entry key="status" value="NEW"/> - </map> - </property> - <property name="pageSize" value="1000"/> - <property name="rowMapper" ref="customerMapper"/> -</bean> - - This configured ItemReader will return - CustomerCredit objects using the - RowMapper that must be specified. The - 'pageSize' property determines the number of entities read from the - database for each query execution. - - The 'parameterValues' property can be used to specify a Map of - parameter values for the query. If you use named parameters in the - where clause the key for each entry should match the name of the named - parameter. If you use a traditional '?' placeholder then the key for - each entry should be the number of the placeholder, starting with - 1. -
- -
- JpaPagingItemReader - - Another implementation of a paging - ItemReader is the - JpaPagingItemReader. JPA doesn't have a concept - similar to the Hibernate StatelessSession so we - have to use other features provided by the JPA specification. Since - JPA supports paging, this is a natural choice when it comes to using - JPA for batch processing. After each page is read, the entities will - become detached and the persistence context will be cleared in order - to allow the entities to be garbage collected once the page is - processed. - - The JpaPagingItemReader allows you to - declare a JPQL statement and pass in a - EntityManagerFactory. It will then pass back - one item per call to read in the same basic - fashion as any other ItemReader. The paging - happens behind the scenes when additional entities are needed. Below - is an example configuration using the same 'customer credit' example - as the JDBC reader above: - - <bean id="itemReader" class="org.spr...JpaPagingItemReader"> - <property name="entityManagerFactory" ref="entityManagerFactory"/> - <property name="queryString" value="select c from CustomerCredit c"/> - <property name="pageSize" value="1000"/> -</bean> - - This configured ItemReader will return - CustomerCredit objects in the exact same manner - as described by the JdbcPagingItemReader above, - assuming the Customer object has the correct JPA annotations or ORM - mapping file. The 'pageSize' property determines the number of - entities read from the database for each query execution. -
- -
- -
- Database ItemWriters - - While both Flat Files and XML have specific ItemWriters, there is - no exact equivalent in the database world. This is because transactions - provide all the functionality that is needed. ItemWriters are necessary - for files because they must act as if they're transactional, keeping - track of written items and flushing or clearing at the appropriate - times. Databases have no need for this functionality, since the write is - already contained in a transaction. Users can create their own DAOs that - implement the ItemWriter interface or use one - from a custom ItemWriter that's written for - generic processing concerns, either way, they should work without any - issues. One thing to look out for is the performance and error handling - capabilities that are provided by batching the outputs. This is most - common when using hibernate as an ItemWriter, but - could have the same issues when using Jdbc batch mode. Batching database - output doesn't have any inherent flaws, assuming we are careful to flush - and there are no errors in the data. However, any errors while writing - out can cause confusion because there is no way to know which individual - item caused an exception, or even if any individual item was - responsible, as illustrated below: - - - - - - - - - - If items are buffered before being written out, any - errors encountered will not be thrown until the buffer is flushed just - before a commit. For example, let's assume that 20 items will be written - per chunk, and the 15th item throws a DataIntegrityViolationException. - As far as the Step is concerned, all 20 item will be written out - successfully, since there's no way to know that an error will occur - until they are actually written out. Once - Session#flush() is - called, the buffer will be emptied and the exception will be hit. At - this point, there's nothing the Step can do, the - transaction must be rolled back. Normally, this exception might cause - the Item to be skipped (depending upon the skip/retry policies), and - then it won't be written out again. However, in the batched scenario, - there's no way for it to know which item caused the issue, the whole - buffer was being written out when the failure happened. The only way to - solve this issue is to flush after each item: - - - - - - - - - - - - This is a common use case, especially when using Hibernate, and - the simple guideline for implementations of - ItemWriter, is to flush on each call to - write(). Doing so allows for items to be - skipped reliably, with Spring Batch taking care internally of the - granularity of the calls to ItemWriter after an - error. -
-
- -
- Reusing Existing Services - - Batch systems are often used in conjunction with other application - styles. The most common is an online system, but it may also support - integration or even a thick client application by moving necessary bulk - data that each application style uses. For this reason, it is common that - many users want to reuse existing DAOs or other services within their - batch jobs. The Spring container itself makes this fairly easy by allowing - any necessary class to be injected. However, there may be cases where the - existing service needs to act as an ItemReader or - ItemWriter, either to satisfy the dependency of - another Spring Batch class, or because it truly is the main - ItemReader for a step. It is fairly trivial to - write an adaptor class for each service that needs wrapping, but because - it is such a common concern, Spring Batch provides implementations: - ItemReaderAdapter and - ItemWriterAdapter. Both classes implement the - standard Spring method invoking the delegate pattern and are fairly simple - to set up. Below is an example of the reader: - - <bean id="itemReader" class="org.springframework.batch.item.adapter.ItemReaderAdapter"> - <property name="targetObject" ref="fooService" /> - <property name="targetMethod" value="generateFoo" /> -</bean> - -<bean id="fooService" class="org.springframework.batch.item.sample.FooService" /> - - One important point to note is that the contract of the targetMethod - must be the same as the contract for read: when - exhausted it will return null, otherwise an Object. - Anything else will prevent the framework from knowing when processing - should end, either causing an infinite loop or incorrect failure, - depending upon the implementation of the - ItemWriter. The ItemWriter - implementation is equally as simple: - - <bean id="itemWriter" class="org.springframework.batch.item.adapter.ItemWriterAdapter"> - <property name="targetObject" ref="fooService" /> - <property name="targetMethod" value="processFoo" /> -</bean> - -<bean id="fooService" class="org.springframework.batch.item.sample.FooService" /> - -
- -
- Validating Input - - During the course of this chapter, multiple approaches to parsing - input have been discussed. Each major implementation will throw an - exception if it is not 'well-formed'. The - FixedLengthTokenizer will throw an exception if a - range of data is missing. Similarly, attempting to access an index in a - RowMapper of FieldSetMapper - that doesn't exist or is in a different format than the one expected will - cause an exception to be thrown. All of these types of exceptions will be - thrown before read returns. However, they don't - address the issue of whether or not the returned item is valid. For - example, if one of the fields is an age, it obviously cannot be negative. - It will parse correctly, because it existed and is a number, but it won't - cause an exception. Since there are already a plethora of Validation - frameworks, Spring Batch does not attempt to provide yet another, but - rather provides a very simple interface that can be implemented by any - number of frameworks: - - public interface Validator { - - void validate(Object value) throws ValidationException; - -} - - The contract is that the validate method - will throw an exception if the object is invalid, and return normally if - it is valid. Spring Batch provides an out of the box - ItemProcessor: - - <bean class="org.springframework.batch.item.validator.ValidatingItemProcessor"> - <property name="validator" ref="validator" /> -</bean> - -<bean id="validator" - class="org.springframework.batch.item.validator.SpringValidator"> - <property name="validator"> - <bean id="orderValidator" - class="org.springmodules.validation.valang.ValangValidator"> - <property name="valang"> - <value> - <![CDATA[ - { orderId : ? > 0 AND ? <= 9999999999 : 'Incorrect order ID' : 'error.order.id' } - { totalLines : ? = size(lineItems) : 'Bad count of order lines' - : 'error.order.lines.badcount'} - { customer.registered : customer.businessCustomer = FALSE OR ? = TRUE - : 'Business customer must be registered' - : 'error.customer.registration'} - { customer.companyName : customer.businessCustomer = FALSE OR ? HAS TEXT - : 'Company name for business customer is mandatory' - :'error.customer.companyname'} - ]]> - </value> - </property> - </bean> - </property> -</bean> - - This simple example shows a simple - ValangValidator that is used to validate an order - object. The intent is not to show Valang functionality as much as to show - how a validator could be added. -
- -
- Preventing State Persistence - - By default, all of the ItemReader and - ItemWriter implementations store their current - state in the ExecutionContext before it is - committed. However, this may not always be the desired behavior. For - example, many developers choose to make their database readers - 'rerunnable' by using a process indicator. An extra column is added to the - input data to indicate whether or not it has been processed. When a - particular record is being read (or written out) the processed flag is - flipped from false to true. The SQL statement can then contain an extra - statement in the where clause, such as "where PROCESSED_IND = false", - thereby ensuring that only unprocessed records will be returned in the - case of a restart. In this scenario, it is preferable to not store any - state, such as the current row number, since it will be irrelevant upon - restart. For this reason, all readers and writers include the 'saveState' - property: - - <bean id="playerSummarizationSource" class="org.spr...JdbcCursorItemReader"> - <property name="dataSource" ref="dataSource" /> - <property name="rowMapper"> - <bean class="org.springframework.batch.sample.PlayerSummaryMapper" /> - </property> - <property name="saveState" value="false" /> - <property name="sql"> - <value> - SELECT games.player_id, games.year_no, SUM(COMPLETES), - SUM(ATTEMPTS), SUM(PASSING_YARDS), SUM(PASSING_TD), - SUM(INTERCEPTIONS), SUM(RUSHES), SUM(RUSH_YARDS), - SUM(RECEPTIONS), SUM(RECEPTIONS_YARDS), SUM(TOTAL_TD) - from games, players where players.player_id = - games.player_id group by games.player_id, games.year_no - </value> - </property> -</bean> - - The ItemReader configured above will not make - any entries in the ExecutionContext for any - executions in which it participates. -
- -
- Creating Custom ItemReaders and - ItemWriters - - So far in this chapter the basic contracts that exist for reading - and writing in Spring Batch and some common implementations have been - discussed. However, these are all fairly generic, and there are many - potential scenarios that may not be covered by out of the box - implementations. This section will show, using a simple example, how to - create a custom ItemReader and - ItemWriter implementation and implement their - contracts correctly. The ItemReader will also - implement ItemStream, in order to illustrate how to - make a reader or writer restartable. - -
- Custom ItemReader Example - - For the purpose of this example, a simple - ItemReader implementation that reads from a - provided list will be created. We'll start out by implementing the most - basic contract of ItemReader, - read: - - public class CustomItemReader<T> implements ItemReader<T>{ - - List<T> items; - - public CustomItemReader(List<T> items) { - this.items = items; - } - - public T read() throws Exception, UnexpectedInputException, - NoWorkFoundException, ParseException { - - if (!items.isEmpty()) { - return items.remove(0); - } - return null; - } -} - - This very simple class takes a list of items, and returns them one - at a time, removing each from the list. When the list is empty, it - returns null, thus satisfying the most basic requirements of an - ItemReader, as illustrated below: - - List<String> items = new ArrayList<String>(); -items.add("1"); -items.add("2"); -items.add("3"); - -ItemReader itemReader = new CustomItemReader<String>(items); -assertEquals("1", itemReader.read()); -assertEquals("2", itemReader.read()); -assertEquals("3", itemReader.read()); -assertNull(itemReader.read()); - -
- Making the <classname>ItemReader</classname> - Restartable - - The final challenge now is to make the - ItemReader restartable. Currently, if the power - goes out, and processing begins again, the - ItemReader must start at the beginning. This is - actually valid in many scenarios, but it is sometimes preferable that - a batch job starts where it left off. The key discriminant is often - whether the reader is stateful or stateless. A stateless reader does - not need to worry about restartability, but a stateful one has to try - and reconstitute its last known state on restart. For this reason, we - recommend that you keep custom readers stateless if possible, so you - don't have to worry about restartability. - - If you do need to store state, then the - ItemStream interface should be used: - - public class CustomItemReader<T> implements ItemReader<T>, ItemStream { - - List<T> items; - int currentIndex = 0; - private static final String CURRENT_INDEX = "current.index"; - - public CustomItemReader(List<T> items) { - this.items = items; - } - - public T read() throws Exception, UnexpectedInputException, - ParseException { - - if (currentIndex < items.size()) { - return items.get(currentIndex++); - } - - return null; - } - - public void open(ExecutionContext executionContext) throws ItemStreamException { - if(executionContext.containsKey(CURRENT_INDEX)){ - currentIndex = new Long(executionContext.getLong(CURRENT_INDEX)).intValue(); - } - else{ - currentIndex = 0; - } - } - - public void update(ExecutionContext executionContext) throws ItemStreamException { - executionContext.putLong(CURRENT_INDEX, new Long(currentIndex).longValue()); - } - - public void close() throws ItemStreamException {} -} - - On each call to the ItemStream - update method, the current index of the - ItemReader will be stored in the provided - ExecutionContext with a key of 'current.index'. - When the ItemStream open - method is called, the ExecutionContext is - checked to see if it contains an entry with that key. If the key is - found, then the current index is moved to that location. This is a - fairly trivial example, but it still meets the general - contract: - - ExecutionContext executionContext = new ExecutionContext(); -((ItemStream)itemReader).open(executionContext); -assertEquals("1", itemReader.read()); -((ItemStream)itemReader).update(executionContext); - -List<String> items = new ArrayList<String>(); -items.add("1"); -items.add("2"); -items.add("3"); -itemReader = new CustomItemReader<String>(items); - -((ItemStream)itemReader).open(executionContext); -assertEquals("2", itemReader.read()); - - Most ItemReaders have much more sophisticated restart logic. The - JdbcCursorItemReader, for example, stores the - row id of the last processed row in the Cursor. - - It is also worth noting that the key used within the - ExecutionContext should not be trivial. That is - because the same ExecutionContext is used for - all ItemStreams within a - Step. In most cases, simply prepending the key - with the class name should be enough to guarantee uniqueness. However, - in the rare cases where two of the same type of - ItemStream are used in the same step (which can - happen if two files are need for output) then a more unique name will - be needed. For this reason, many of the Spring Batch - ItemReader and - ItemWriter implementations have a - setName() property that allows this key name - to be overridden. -
-
- -
- Custom ItemWriter Example - - Implementing a Custom ItemWriter is similar - in many ways to the ItemReader example above, but - differs in enough ways as to warrant its own example. However, adding - restartability is essentially the same, so it won't be covered in this - example. As with the ItemReader example, a - List will be used in order to keep the example as - simple as possible: - - public class CustomItemWriter<T> implements ItemWriter<T> { - - List<T> output = TransactionAwareProxyFactory.createTransactionalList(); - - public void write(List<? extends T> items) throws Exception { - output.addAll(items); - } - - public List<T> getOutput() { - return output; - } -} - -
- Making the <classname>ItemWriter</classname> - Restartable - - To make the ItemWriter restartable we would follow the same - process as for the ItemReader, adding and - implementing the ItemStream interface to - synchronize the execution context. In the example we might have to - count the number of items processed and add that as a footer record. - If we needed to do that, we could implement - ItemStream in our - ItemWriter so that the counter was - reconstituted from the execution context if the stream was - re-opened. - - In many realistic cases, custom ItemWriters also delegate to - another writer that itself is restartable (e.g. when writing to a - file), or else it writes to a transactional resource so doesn't need - to be restartable because it is stateless. When you have a stateful - writer you should probably also be sure to implement - ItemStream as well as - ItemWriter. Remember also that the client of - the writer needs to be aware of the ItemStream, - so you may need to register it as a stream in the configuration - xml. -
-
-
-
diff --git a/src/site/docbook/reference/repeat.xml b/src/site/docbook/reference/repeat.xml deleted file mode 100644 index 1aff2ffd1..000000000 --- a/src/site/docbook/reference/repeat.xml +++ /dev/null @@ -1,287 +0,0 @@ - - - - Repeat - -
- RepeatTemplate - - Batch processing is about repetitive actions - either as a simple - optimization, or as part of a job. To strategize and generalize the - repetition as well as to provide what amounts to an iterator framework, - Spring Batch has the RepeatOperations interface. - The RepeatOperations interface looks like - this: - - public interface RepeatOperations { - - RepeatStatus iterate(RepeatCallback callback) throws RepeatException; - -} - The callback is a simple interface that allows you to insert - some business logic to be repeated: - - public interface RepeatCallback { - - RepeatStatus doInIteration(RepeatContext context) throws Exception; - -} - The callback is executed repeatedly until the implementation - decides that the iteration should end. The return value in these - interfaces is an enumeration that can either be - RepeatStatus.CONTINUABLE or - RepeatStatus.FINISHED. A RepeatStatus - conveys information to the caller of the repeat operations about whether - there is any more work to do. Generally speaking, implementations of - RepeatOperations should inspect the - RepeatStatus and use it as part of the decision to - end the iteration. Any callback that wishes to signal to the caller that - there is no more work to do can return - RepeatStatus.FINISHED. - - The simplest general purpose implementation of - RepeatOperations is - RepeatTemplate. It could be used like this: - - RepeatTemplate template = new RepeatTemplate(); - -template.setCompletionPolicy(new FixedChunkSizeCompletionPolicy(2)); - -template.iterate(new RepeatCallback() { - - public ExitStatus doInIteration(RepeatContext context) { - // Do stuff in batch... - return ExitStatus.CONTINUABLE; - } - -}); - - In the example we return RepeatStatus.CONTINUABLE to - show that there is more work to do. The callback can also return - ExitStatus.FINISHED if it wants to signal to the caller that - there is no more work to do. Some iterations can be terminated by - considerations intrinsic to the work being done in the callback, others - are effectively infinite loops as far as the callback is concerned and the - completion decision is delegated to an external policy as in the case - above. - -
- RepeatContext - - The method parameter for the RepeatCallback - is a RepeatContext. Many callbacks will simply - ignore the context, but if necessary it can be used as an attribute bag - to store transient data for the duration of the iteration. After the - iterate method returns, the context will no - longer exist. - - A RepeatContext will have a parent context - if there is a nested iteration in progress. The parent context is - occasionally useful for storing data that need to be shared between - calls to iterate. This is the case for instance - if you want to count the number of occurrences of an event in the - iteration and remember it across subsequent calls. -
- -
- RepeatStatus - - RepeatStatus is an enumeration used by - Spring Batch to indicate whether processing has finished. These are - possible RepeatStatus values: - - - ExitStatus Properties - - - - - Value - - Description - - - - CONTINUABLE - - There is more work to do. - - - - FINISHED - - No more repetitions should take place. - - - -
- - RepeatStatus values can also be combined - with a logical AND operation using the and() - method in RepeatStatus. The effect of this is to - do a logical AND on the continuable flag. In other words, if either - status is FINISHED, then the result will be - FINISHED. -
-
- -
- Completion Policies - - Inside a RepeatTemplate the termination of - the loop in the iterate method is determined by a - CompletionPolicy which is also a factory for the - RepeatContext. The - RepeatTemplate has the responsibility to use the - current policy to create a RepeatContext and pass - that in to the RepeatCallback at every stage in the - iteration. After a callback completes its - doInIteration, the - RepeatTemplate has to make a call to the - CompletionPolicy to ask it to update its state - (which will be stored in the RepeatContext). Then - it asks the policy if the iteration is complete. - - Spring Batch provides some simple general purpose implementations of - CompletionPolicy. The - SimpleCompletionPolicy just allows an execution up - to a fixed number of times (with RepeatStatus.FINISHED - forcing early completion at any time). - - Users might need to implement their own completion policies for more - complicated decisions. For example, a batch processing window that - prevents batch jobs from executing once the online systems are in use - would require a custom policy. -
- -
- Exception Handling - - If there is an exception thrown inside a - RepeatCallback, the - RepeatTemplate consults an - ExceptionHandler which can decide whether or not to - re-throw the exception. - - public interface ExceptionHandler { - - void handleException(RepeatContext context, Throwable throwable) - throws RuntimeException; - -} - A common use case is to count the number of exceptions of a - given type, and fail when a limit is reached. For this purpose Spring - Batch provides the SimpleLimitExceptionHandler and - slightly more flexible - RethrowOnThresholdExceptionHandler. The - SimpleLimitExceptionHandler has a limit property - and an exception type that should be compared with the current exception - - all subclasses of the provided type are also counted. Exceptions of the - given type are ignored until the limit is reached, and then rethrown. - Those of other types are always rethrown. - - An important optional property of the - SimpleLimitExceptionHandler is the boolean flag - useParent. It is false by default, so the limit is only - accounted for in the current RepeatContext. When - set to true, the limit is kept across sibling contexts in a nested - iteration (e.g. a set of chunks inside a step). -
- -
- Listeners - - Often it is useful to be able to receive additional callbacks for - cross cutting concerns across a number of different iterations. For this - purpose Spring Batch provides the RepeatListener - interface. The RepeatTemplate allows users to - register RepeatListeners, and they will be given - callbacks with the RepeatContext and - RepeatStatus where available during the - iteration. - - The interface looks like this: - - public interface RepeatListener { - void before(RepeatContext context); - void after(RepeatContext context, RepeatStatus result); - void open(RepeatContext context); - void onError(RepeatContext context, Throwable e); - void close(RepeatContext context); -} - The open and - close callbacks come before and after the entire - iteration. before, after - and onError apply to the individual - RepeatCallback calls. - - Note that when there is more than one listener, they are in a list, - so there is an order. In this case open and - before are called in the same order while - after, onError and - close are called in reverse order. -
- -
- Parallel Processing - - Implementations of RepeatOperations are not - restricted to executing the callback sequentially. It is quite important - that some implementations are able to execute their callbacks in parallel. - To this end, Spring Batch provides the - TaskExecutorRepeatTemplate, which uses the Spring - TaskExecutor strategy to run the - RepeatCallback. The default is to use a - SynchronousTaskExecutor, which has the effect of - executing the whole iteration in the same thread (the same as a normal - RepeatTemplate). -
- -
- Declarative Iteration - - Sometimes there is some business processing that you know you want - to repeat every time it happens. The classic example of this is the - optimization of a message pipeline - it is more efficient to process a - batch of messages, if they are arriving frequently, than to bear the cost - of a separate transaction for every message. Spring Batch provides an AOP - interceptor that wraps a method call in a - RepeatOperations for just this purpose. The - RepeatOperationsInterceptor executes the - intercepted method and repeats according to the - CompletionPolicy in the provided - RepeatTemplate. - - Here is an example of declarative iteration using the Spring AOP - namespace to repeat a service call to a method called - processMessage (for more detail on how to - configure AOP interceptors see the Spring User Guide): - - <aop:config> - <aop:pointcut id="transactional" - expression="execution(* com..*Service.processMessage(..))" /> - <aop:advisor pointcut-ref="transactional" - advice-ref="retryAdvice" order="-1"/> -</aop:config> - -<bean id="retryAdvice" class="org.spr...RepeatOperationsInterceptor"/> - - The example above uses a default - RepeatTemplate inside the interceptor. To change - the policies, listeners etc. you only need to inject an instance of - RepeatTemplate into the interceptor. - - If the intercepted method returns void then the - interceptor always returns ExitStatus.CONTINUABLE (so there is a danger of - an infinite loop if the CompletionPolicy does not - have a finite end point). Otherwise it returns - ExitStatus.CONTINUABLE until the return value from the - intercepted method is null, at which point it returns - ExitStatus.FINISHED. So the business logic inside the target - method can signal that there is no more work to do by returning - null, or by throwing an exception that is re-thrown by the - ExceptionHandler in the provided - RepeatTemplate. -
-
diff --git a/src/site/docbook/reference/retry.xml b/src/site/docbook/reference/retry.xml deleted file mode 100644 index 64f6c3f4e..000000000 --- a/src/site/docbook/reference/retry.xml +++ /dev/null @@ -1,368 +0,0 @@ - - - - Retry - -
- RetryTemplate - - - The retry functionality was pulled out of Spring Batch as of 2.2.0. - It is now part of a new library, Spring Retry. - - - To make processing more robust and less prone to failure, sometimes - it helps to automatically retry a failed operation in case it might - succeed on a subsequent attempt. Errors that are susceptible to this kind - of treatment are transient in nature. For example a remote call to a web - service or RMI service that fails because of a network glitch or a - DeadLockLoserException in a database update may - resolve themselves after a short wait. To automate the retry of such - operations Spring Batch has the RetryOperations - strategy. The RetryOperations interface looks like - this: - - public interface RetryOperations { - - <T> T execute(RetryCallback<T> retryCallback) throws Exception; - - <T> T execute(RetryCallback<T> retryCallback, RecoveryCallback<T> recoveryCallback) - throws Exception; - - <T> T execute(RetryCallback<T> retryCallback, RetryState retryState) - throws Exception, ExhaustedRetryException; - - <T> T execute(RetryCallback<T> retryCallback, RecoveryCallback<T> recoveryCallback, - RetryState retryState) throws Exception; - -} - The basic callback is a simple interface that allows you to - insert some business logic to be retried: - - public interface RetryCallback<T> { - - T doWithRetry(RetryContext context) throws Throwable; - -} - The callback is executed and if it fails (by throwing an - Exception), it will be retried until either it is - successful, or the implementation decides to abort. There are a number of - overloaded execute methods in the - RetryOperations interface dealing with various use - cases for recovery when all retry attempts are exhausted, and also with - retry state, which allows clients and implementations to store information - between calls (more on this later). - - The simplest general purpose implementation of - RetryOperations is - RetryTemplate. It could be used like this - - RetryTemplate template = new RetryTemplate(); - -TimeoutRetryPolicy policy = new TimeoutRetryPolicy(); -policy.setTimeout(30000L); - -template.setRetryPolicy(policy); - -Foo result = template.execute(new RetryCallback<Foo>() { - - public Foo doWithRetry(RetryContext context) { - // Do stuff that might fail, e.g. webservice operation - return result; - } - -}); - - In the example we execute a web service call and return the result - to the user. If that call fails then it is retried until a timeout is - reached. - -
- RetryContext - - The method parameter for the RetryCallback - is a RetryContext. Many callbacks will simply - ignore the context, but if necessary it can be used as an attribute bag - to store data for the duration of the iteration. - - A RetryContext will have a parent context - if there is a nested retry in progress in the same thread. The parent - context is occasionally useful for storing data that need to be shared - between calls to execute. -
- -
- RecoveryCallback - - When a retry is exhausted the - RetryOperations can pass control to a different - callback, the RecoveryCallback. To use this - feature clients just pass in the callbacks together to the same method, - for example: - - Foo foo = template.execute(new RetryCallback<Foo>() { - public Foo doWithRetry(RetryContext context) { - // business logic here - }, - new RecoveryCallback<Foo>() { - Foo recover(RetryContext context) throws Exception { - // recover logic here - } -}); - If the business logic does not succeed before the template - decides to abort, then the client is given the chance to do some - alternate processing through the recovery callback. -
- -
- Stateless Retry - - In the simplest case, a retry is just a while loop: the - RetryTemplate can just keep trying until it - either succeeds or fails. The RetryContext - contains some state to determine whether to retry or abort, but this - state is on the stack and there is no need to store it anywhere - globally, so we call this stateless retry. The distinction between - stateless and stateful retry is contained in the implementation of the - RetryPolicy (the - RetryTemplate can handle both). In a stateless - retry, the callback is always executed in the same thread on retry as - when it failed. -
- -
- Stateful Retry - - Where the failure has caused a transactional resource to become - invalid, there are some special considerations. This does not apply to a - simple remote call because there is no transactional resource (usually), - but it does sometimes apply to a database update, especially when using - Hibernate. In this case it only makes sense to rethrow the exception - that called the failure immediately so that the transaction can roll - back and we can start a new valid one. - - In these cases a stateless retry is not good enough because the - re-throw and roll back necessarily involve leaving the - RetryOperations.execute() method and potentially losing the - context that was on the stack. To avoid losing it we have to introduce a - storage strategy to lift it off the stack and put it (at a minimum) in - heap storage. For this purpose Spring Batch provides a storage strategy - RetryContextCache which can be injected into the - RetryTemplate. The default implementation of the - RetryContextCache is in memory, using a simple - Map. Advanced usage with multiple processes in a - clustered environment might also consider implementing the - RetryContextCache with a cluster cache of some - sort (though, even in a clustered environment this might be - overkill). - - Part of the responsibility of the - RetryOperations is to recognize the failed - operations when they come back in a new execution (and usually wrapped - in a new transaction). To facilitate this, Spring Batch provides the - RetryState abstraction. This works in conjunction - with a special execute methods in the - RetryOperations. - - The way the failed operations are recognized is by identifying the - state across multiple invocations of the retry. To identify the state, - the user can provide an RetryState object that is - responsible for returning a unique key identifying the item. The - identifier is used as a key in the - RetryContextCache. - - - Be very careful with the implementation of - Object.equals() and Object.hashCode() in the - key returned by RetryState. The best advice is - to use a business key to identify the items. In the case of a JMS - message the message ID can be used. - - - When the retry is exhausted there is also the option to handle the - failed item in a different way, instead of calling the - RetryCallback (which is presumed now to be likely - to fail). Just like in the stateless case, this option is provided by - the RecoveryCallback, which can be provided by - passing it in to the execute method of - RetryOperations. - - The decision to retry or not is actually delegated to a regular - RetryPolicy, so the usual concerns about limits - and timeouts can be injected there (see below). -
-
- -
- Retry Policies - - Inside a RetryTemplate the decision to retry - or fail in the execute method is determined by a - RetryPolicy which is also a factory for the - RetryContext. The - RetryTemplate has the responsibility to use the - current policy to create a RetryContext and pass - that in to the RetryCallback at every attempt. - After a callback fails the RetryTemplate has to - make a call to the RetryPolicy to ask it to update - its state (which will be stored in the - RetryContext), and then it asks the policy if - another attempt can be made. If another attempt cannot be made (e.g. a - limit is reached or a timeout is detected) then the policy is also - responsible for handling the exhausted state. Simple implementations will - just throw RetryExhaustedException which will cause - any enclosing transaction to be rolled back. More sophisticated - implementations might attempt to take some recovery action, in which case - the transaction can remain intact. - - - Failures are inherently either retryable or not - if the same - exception is always going to be thrown from the business logic, it - doesn't help to retry it. So don't retry on all exception types - try to - focus on only those exceptions that you expect to be retryable. It's not - usually harmful to the business logic to retry more aggressively, but - it's wasteful because if a failure is deterministic there will be time - spent retrying something that you know in advance is fatal. - - - Spring Batch provides some simple general purpose implementations of - stateless RetryPolicy, for example a - SimpleRetryPolicy, and the - TimeoutRetryPolicy used in the example - above. - - The SimpleRetryPolicy just allows a retry on - any of a named list of exception types, up to a fixed number of times. It - also has a list of "fatal" exceptions that should never be retried, and - this list overrides the retryable list so that it can be used to give - finer control over the retry behavior: - - SimpleRetryPolicy policy = new SimpleRetryPolicy(); -// Set the max retry attempts -policy.setMaxAttempts(5); -// Retry on all exceptions (this is the default) -policy.setRetryableExceptions(new Class[] {Exception.class}); -// ... but never retry IllegalStateException -policy.setFatalExceptions(new Class[] {IllegalStateException.class}); - -// Use the policy... -RetryTemplate template = new RetryTemplate(); -template.setRetryPolicy(policy); -template.execute(new RetryCallback<Foo>() { - public Foo doWithRetry(RetryContext context) { - // business logic here - } -}); - - There is also a more flexible implementation called - ExceptionClassifierRetryPolicy, which allows the - user to configure different retry behavior for an arbitrary set of - exception types though the ExceptionClassifier - abstraction. The policy works by calling on the classifier to convert an - exception into a delegate RetryPolicy, so for - example, one exception type can be retried more times before failure than - another by mapping it to a different policy. - - Users might need to implement their own retry policies for more - customized decisions. For instance, if there is a well-known, - solution-specific, classification of exceptions into retryable and not - retryable. -
- -
- Backoff Policies - - When retrying after a transient failure it often helps to wait a bit - before trying again, because usually the failure is caused by some problem - that will only be resolved by waiting. If a - RetryCallback fails, the - RetryTemplate can pause execution according to the - BackoffPolicy in place. - - public interface BackoffPolicy { - - BackOffContext start(RetryContext context); - - void backOff(BackOffContext backOffContext) - throws BackOffInterruptedException; - -} - A BackoffPolicy is free to implement - the backOff in any way it chooses. The policies provided by Spring Batch - out of the box all use Object.wait(). A common use case is to - backoff with an exponentially increasing wait period, to avoid two retries - getting into lock step and both failing - this is a lesson learned from - the ethernet. For this purpose Spring Batch provides the - ExponentialBackoffPolicy. -
- -
- Listeners - - Often it is useful to be able to receive additional callbacks for - cross cutting concerns across a number of different retries. For this - purpose Spring Batch provides the RetryListener - interface. The RetryTemplate allows users to - register RetryListeners, and they will be given - callbacks with the RetryContext and - Throwable where available during the - iteration. - - The interface looks like this: - - public interface RetryListener { - - void open(RetryContext context, RetryCallback<T> callback); - - void onError(RetryContext context, RetryCallback<T> callback, Throwable e); - - void close(RetryContext context, RetryCallback<T> callback, Throwable e); -} - The open and - close callbacks come before and after the entire - retry in the simplest case and onError applies to - the individual RetryCallback calls. The - close method might also receive a - Throwable; if there has been an error it is the - last one thrown by the RetryCallback. - - Note that when there is more than one listener, they are in a list, - so there is an order. In this case open will be - called in the same order while onError and - close will be called in reverse order. -
- -
- Declarative Retry - - Sometimes there is some business processing that you know you want - to retry every time it happens. The classic example of this is the remote - service call. Spring Batch provides an AOP interceptor that wraps a method - call in a RetryOperations for just this purpose. - The RetryOperationsInterceptor executes the - intercepted method and retries on failure according to the - RetryPolicy in the provided - RepeatTemplate. - - Here is an example of declarative iteration using the Spring AOP - namespace to repeat a service call to a method called - remoteCall (for more detail on how to configure - AOP interceptors see the Spring User Guide): - - <aop:config> - <aop:pointcut id="transactional" - expression="execution(* com..*Service.remoteCall(..))" /> - <aop:advisor pointcut-ref="transactional" - advice-ref="retryAdvice" order="-1"/> -</aop:config> - -<bean id="retryAdvice" - class="org.springframework.batch.retry.interceptor.RetryOperationsInterceptor"/> - - The example above uses a default - RetryTemplate inside the interceptor. To change the - policies or listeners, you only need to inject an instance of - RetryTemplate into the interceptor. -
-
diff --git a/src/site/docbook/reference/scalability.xml b/src/site/docbook/reference/scalability.xml deleted file mode 100644 index d4d83d140..000000000 --- a/src/site/docbook/reference/scalability.xml +++ /dev/null @@ -1,409 +0,0 @@ - - - - Scaling and Parallel Processing - - Many batch processing problems can be solved with single threaded, - single process jobs, so it is always a good idea to properly check if that - meets your needs before thinking about more complex implementations. Measure - the performance of a realistic job and see if the simplest implementation - meets your needs first: you can read and write a file of several hundred - megabytes in well under a minute, even with standard hardware. - - When you are ready to start implementing a job with some parallel - processing, Spring Batch offers a range of options, which are described in - this chapter, although some features are covered elsewhere. At a high level - there are two modes of parallel processing: single process, multi-threaded; - and multi-process. These break down into categories as well, as - follows: - - - - Multi-threaded Step (single process) - - - - Parallel Steps (single process) - - - - Remote Chunking of Step (multi process) - - - - Partitioning a Step (single or multi process) - - - - Next we review the single-process options first, and then the - multi-process options. - -
- Multi-threaded Step - - The simplest way to start parallel processing is to add a - TaskExecutor to your Step configuration, e.g. as an - attribute of the tasklet: - - <step id="loading"> - <tasklet task-executor="taskExecutor">...</tasklet> -</step> - - In this example the taskExecutor is a reference to another bean - definition, implementing the TaskExecutor - interface. TaskExecutor is a standard Spring - interface, so consult the Spring User Guide for details of available - implementations. The simplest multi-threaded - TaskExecutor is a - SimpleAsyncTaskExecutor. - - The result of the above configuration will be that the Step - executes by reading, processing and writing each chunk of items - (each commit interval) in a separate thread of execution. Note - that this means there is no fixed order for the items to be - processed, and a chunk might contain items that are - non-consecutive compared to the single-threaded case. In addition - to any limits placed by the task executor (e.g. if it is backed by - a thread pool), there is a throttle limit in the tasklet - configuration which defaults to 4. You may need to increase this - to ensure that a thread pool is fully utilised, e.g. - - <step id="loading"> <tasklet - task-executor="taskExecutor" - throttle-limit="20">...</tasklet> -</step> - - Note also that there may be limits placed on concurrency by - any pooled resources used in your step, such as - a DataSource. Be sure to make the pool in - those resources at least as large as the desired number of - concurrent threads in the step. - - There are some practical limitations of using multi-threaded Steps - for some common Batch use cases. Many participants in a Step (e.g. readers - and writers) are stateful, and if the state is not segregated by thread, - then those components are not usable in a multi-threaded Step. In - particular most of the off-the-shelf readers and writers from Spring Batch - are not designed for multi-threaded use. It is, however, possible to work - with stateless or thread safe readers and writers, and there is a sample - (parallelJob) in the Spring Batch Samples that show the use of a process - indicator (see ) to keep - track of items that have been processed in a database input table. - - Spring Batch provides some implementations of - ItemWriter and - ItemReader. Usually they say in the - Javadocs if they are thread safe or not, or what you have to do to - avoid problems in a concurrent environment. If there is no - information in Javadocs, you can check the implementation to see - if there is any state. If a reader is not thread safe, it may - still be efficient to use it in your own synchronizing delegator. - You can synchronize the call to read() and as - long as the processing and writing is the most expensive part of - the chunk your step may still complete much faster than in a - single threaded configuration. - - -
- -
- Parallel Steps - - As long as the application logic that needs to be parallelized can - be split into distinct responsibilities, and assigned to individual steps - then it can be parallelized in a single process. Parallel Step execution - is easy to configure and use, for example, to execute steps - (step1,step2) in parallel with - step3, you could configure a flow like this: - - <job id="job1"> - <split id="split1" task-executor="taskExecutor" next="step4"> - <flow> - <step id="step1" parent="s1" next="step2"/> - <step id="step2" parent="s2"/> - </flow> - <flow> - <step id="step3" parent="s3"/> - </flow> - </split> - <step id="step4" parent="s4"/> -</job> - -<beans:bean id="taskExecutor" class="org.spr...SimpleAsyncTaskExecutor"/> - - The configurable "task-executor" attribute is used to specify which - TaskExecutor implementation should be used to execute the individual - flows. The default is SyncTaskExecutor, but an - asynchronous TaskExecutor is required to run the steps in parallel. Note - that the job will ensure that every flow in the split completes before - aggregating the exit statuses and transitioning. - - See the section on for more - detail. -
- -
- Remote Chunking - - In Remote Chunking the Step processing is split across multiple - processes, communicating with each other through some middleware. Here is - a picture of the pattern in action: - - - - - - - - The Master component is a single process, and the Slaves are - multiple remote processes. Clearly this pattern works best if the Master - is not a bottleneck, so the processing must be more expensive than the - reading of items (this is often the case in practice). - - The Master is just an implementation of a Spring Batch - Step, with the ItemWriter replaced with a generic - version that knows how to send chunks of items to the middleware as - messages. The Slaves are standard listeners for whatever middleware is - being used (e.g. with JMS they would be - MesssageListeners), and their role is to process - the chunks of items using a standard ItemWriter or - ItemProcessor plus - ItemWriter, through the - ChunkProcessor interface. One of the advantages of - using this pattern is that the reader, processor and writer components are - off-the-shelf (the same as would be used for a local execution of the - step). The items are divided up dynamically and work is shared through the - middleware, so if the listeners are all eager consumers, then load - balancing is automatic. - - The middleware has to be durable, with guaranteed delivery and - single consumer for each message. JMS is the obvious candidate, but other - options exist in the grid computing and shared memory product space (e.g. - Java Spaces). -
- -
- Partitioning - - Spring Batch also provides an SPI for partitioning a Step execution - and executing it remotely. In this case the remote participants are simply - Step instances that could just as easily have been configured and used for - local processing. Here is a picture of the pattern in action: - - - - - - - - The Job is executing on the left hand side as a sequence of Steps, - and one of the Steps is labelled as a Master. The Slaves in this picture - are all identical instances of a Step, which could in fact take the place - of the Master resulting in the same outcome for the Job. The Slaves are - typically going to be remote services, but could also be local threads of - execution. The messages sent by the Master to the Slaves in this pattern - do not need to be durable, or have guaranteed delivery: Spring Batch - meta-data in the JobRepository will ensure that - each Slave is executed once and only once for each Job execution. - - The SPI in Spring Batch consists of a special implementation of Step - (the PartitionStep), and two strategy interfaces - that need to be implemented for the specific environment. The strategy - interfaces are PartitionHandler and - StepExecutionSplitter, and their role is show in - the sequence diagram below: - - - - - - - - The Step on the right in this case is the "remote" Slave, so - potentially there are many objects and or processes playing this role, and - the PartitionStep is shown driving the execution. The PartitionStep - configuration looks like this: - - <step id="step1.master"> - <partition step="step1" partitioner="partitioner"> - <handler grid-size="10" task-executor="taskExecutor"/> - </partition> -</step> - - Similar to the multi-threaded step's throttle-limit - attribute, the grid-size attribute prevents the task executor from - being saturated with requests from a single step. - - There is a simple example which can be copied and extended in the - unit test suite for Spring Batch Samples (see - *PartitionJob.xml configuration). - - Spring Batch creates step executions for the partitions called - "step1:partition0", etc., so many people prefer to call the master step - "step1:master" for consistency. With Spring 3.0 you can do this using an - alias for the step (specifying the name attribute - instead of the id). - -
- PartitionHandler - - The PartitionHandler is the component that - knows about the fabric of the remoting or grid environment. It is able - to send StepExecution requests to the remote - Steps, wrapped in some fabric-specific format, like a DTO. It does not - have to know how to split up the input data, or how to aggregate the - result of multiple Step executions. Generally speaking it probably also - doesn't need to know about resilience or failover, since those are - features of the fabric in many cases, and anyway Spring Batch always - provides restartability independent of the fabric: a failed Job can - always be restarted and only the failed Steps will be - re-executed. - - The PartitionHandler interface can have - specialized implementations for a variety of fabric types: e.g. simple - RMI remoting, EJB remoting, custom web service, JMS, Java Spaces, shared - memory grids (like Terracotta or Coherence), grid execution fabrics - (like GridGain). Spring Batch does not contain implementations for any - proprietary grid or remoting fabrics. - - Spring Batch does however provide a useful implementation of - PartitionHandler that executes Steps locally in - separate threads of execution, using the - TaskExecutor strategy from Spring. The - implementation is called - TaskExecutorPartitionHandler, and it is the - default for a step configured with the XML namespace as above. It can - also be configured explicitly like this: - - <step id="step1.master"> - <partition step="step1" handler="handler"/> -</step> - -<bean class="org.spr...TaskExecutorPartitionHandler"> - <property name="taskExecutor" ref="taskExecutor"/> - <property name="step" ref="step1" /> - <property name="gridSize" value="10" /> -</bean> - - The gridSize determines the number of separate - step executions to create, so it can be matched to the size of the - thread pool in the TaskExecutor, or else it can - be set to be larger than the number of threads available, in which case - the blocks of work are smaller. - - The TaskExecutorPartitionHandler is quite - useful for IO intensive Steps, like copying large numbers of files or - replicating filesystems into content management systems. It can also be - used for remote execution by providing a Step implementation that is a - proxy for a remote invocation (e.g. using Spring Remoting). -
- -
- Partitioner - - The Partitioner has a simpler responsibility: to generate - execution contexts as input parameters for new step executions only (no - need to worry about restarts). It has a single method: - - public interface Partitioner { - Map<String, ExecutionContext> partition(int gridSize); -} - - The return value from this method associates a unique name for - each step execution (the String), with input - parameters in the form of an ExecutionContext. - The names show up later in the Batch meta data as the step name in the - partitioned StepExecutions. The - ExecutionContext is just a bag of name-value - pairs, so it might contain a range of primary keys, or line numbers, or - the location of an input file. The remote Step - then normally binds to the context input using #{...} - placeholders (late binding in step scope), as illustrated in the next - section. - - The names of the step executions (the keys in the - Map returned by - Partitioner) need to be unique amongst the step - executions of a Job, but do not have any other specific requirements. - The easiest way to do this, and to make the names meaningful for users, - is to use a prefix+suffix naming convention, where the prefix is the - name of the step that is being executed (which itself is unique in the - Job), and the suffix is just a counter. There is - a SimplePartitioner in the framework that uses - this convention. - - An optional interface - PartitioneNameProvider can be used to - provide the partition names separately from the partitions - themselves. If a Partitioner implements - this interface then on a restart only the names will be queried. - If partitioning is expensive this can be a useful optimisation. - Obviously the names provided by the - PartitioneNameProvider must match those - provided by the Partitioner. - -
- -
- Binding Input Data to Steps - - It is very efficient for the steps that are executed by the - PartitionHandler to have identical configuration, and for their input - parameters to be bound at runtime from the ExecutionContext. This is - easy to do with the StepScope feature of Spring Batch (covered in more - detail in the section on ). For example - if the Partitioner creates - ExecutionContext instances with an attribute key - fileName, pointing to a different file (or - directory) for each step invocation, the - Partitioner output might look like this: - - - Example step execution name to execution context provided by - Partitioner targeting directory processing - - - - - Step Execution Name - (key) - - ExecutionContext - (value) - - - - filecopy:partition0 - - fileName=/home/data/one - - - - filecopy:partition1 - - fileName=/home/data/two - - - - filecopy:partition2 - - fileName=/home/data/three - - - -
- - Then the file name can be bound to a step using late binding to - the execution context: - - <bean id="itemReader" scope="step" - class="org.spr...MultiResourceItemReader"> - <property name="resource" value="#{stepExecutionContext[fileName]}/*"/> -</bean> -
-
-
diff --git a/src/site/docbook/reference/schema-appendix.xml b/src/site/docbook/reference/schema-appendix.xml deleted file mode 100644 index d476fb08d..000000000 --- a/src/site/docbook/reference/schema-appendix.xml +++ /dev/null @@ -1,646 +0,0 @@ - - - - Meta-Data Schema - -
- Overview - - The Spring Batch Meta-Data tables very closely match the Domain - objects that represent them in Java. For example, - JobInstance, JobExecution, - JobParameters, and - StepExecution map to BATCH_JOB_INSTANCE, - BATCH_JOB_EXECUTION, BATCH_JOB_EXECUTION_PARAMS, and BATCH_STEP_EXECUTION, - respectively. ExecutionContext maps to both - BATCH_JOB_EXECUTION_CONTEXT and BATCH_STEP_EXECUTION_CONTEXT. The - JobRepository is responsible for saving and storing - each Java object into its correct table. The following appendix describes - the meta-data tables in detail, along with many of the design decisions - that were made when creating them. When viewing the various table creation - statements below, it is important to realize that the data types used are - as generic as possible. Spring Batch provides many schemas as examples, - which all have varying data types due to variations in individual database - vendors' handling of data types. Below is an ERD model of all 6 tables and - their relationships to one another: - - - - - - - - - - - -
- Example DDL Scripts - - The Spring Batch Core JAR file contains example - scripts to create the relational tables for a number of database - platforms (which are in turn auto-detected by the job repository factory - bean or namespace equivalent). These scripts can be used as is, or - modified with additional indexes and constraints as desired. The file - names are in the form schema-*.sql, where "*" is the - short name of the target database platform. The scripts are in - the package org.springframework.batch.core. -
- -
- Version - - Many of the database tables discussed in this appendix contain a - version column. This column is important because Spring Batch employs an - optimistic locking strategy when dealing with updates to the database. - This means that each time a record is 'touched' (updated) the value in - the version column is incremented by one. When the repository goes back - to try and save the value, if the version number has change it will - throw OptimisticLockingFailureException, - indicating there has been an error with concurrent access. This check is - necessary since, even though different batch jobs may be running in - different machines, they are all using the same database tables. -
- -
- Identity - - BATCH_JOB_INSTANCE, BATCH_JOB_EXECUTION, and BATCH_STEP_EXECUTION - each contain columns ending in _ID. These fields act as primary keys for - their respective tables. However, they are not database generated keys, - but rather they are generated by separate sequences. This is necessary - because after inserting one of the domain objects into the database, the - key it is given needs to be set on the actual object so that they can be - uniquely identified in Java. Newer database drivers (Jdbc 3.0 and up) - support this feature with database generated keys, but rather than - requiring it, sequences were used. Each variation of the schema will - contain some form of the following: - - CREATE SEQUENCE BATCH_STEP_EXECUTION_SEQ; -CREATE SEQUENCE BATCH_JOB_EXECUTION_SEQ; -CREATE SEQUENCE BATCH_JOB_SEQ; - - Many database vendors don't support sequences. In these cases, - work-arounds are used, such as the following for MySQL: - - CREATE TABLE BATCH_STEP_EXECUTION_SEQ (ID BIGINT NOT NULL) type=InnoDB; -INSERT INTO BATCH_STEP_EXECUTION_SEQ values(0); -CREATE TABLE BATCH_JOB_EXECUTION_SEQ (ID BIGINT NOT NULL) type=InnoDB; -INSERT INTO BATCH_JOB_EXECUTION_SEQ values(0); -CREATE TABLE BATCH_JOB_SEQ (ID BIGINT NOT NULL) type=InnoDB; -INSERT INTO BATCH_JOB_SEQ values(0); - - In the above case, a table is used in place of each sequence. The - Spring core class MySQLMaxValueIncrementer will - then increment the one column in this sequence in order to give similar - functionality. -
-
- -
- BATCH_JOB_INSTANCE - - The BATCH_JOB_INSTANCE table holds all information relevant to a - JobInstance, and serves as the top of the overall - hierarchy. The following generic DDL statement is used to create - it: - - CREATE TABLE BATCH_JOB_INSTANCE ( - JOB_INSTANCE_ID BIGINT PRIMARY KEY , - VERSION BIGINT, - JOB_NAME VARCHAR(100) NOT NULL , - JOB_KEY VARCHAR(2500) -); - - Below are descriptions of each column in the table: - - - - JOB_INSTANCE_ID: The unique id that will identify the instance, - which is also the primary key. The value of this column should be - obtainable by calling the getId method on - JobInstance. - - - - VERSION: See above section. - - - - JOB_NAME: Name of the job obtained from the - Job object. Because it is required to identify - the instance, it must not be null. - - - - JOB_KEY: A serialization of the - JobParameters that uniquely identifies separate - instances of the same job from one another. - (JobInstances with the same job name must have - different JobParameters, and thus, different - JOB_KEY values). - - -
- -
- BATCH_JOB_EXECUTION_PARAMS - - The BATCH_JOB_EXECUTION_PARAMS table holds all information relevant to the - JobParameters object. It contains 0 or more - key/value pairs passed to a Job and serve as a record of the parameters - a job was run with. For each parameter that contributes to the generation of a job's identity, - the IDENTIFYING flag is set to true. It should be noted that the table has been - denormalized. Rather than creating a separate table for each type, there - is one table with a column indicating the type: - - CREATE TABLE BATCH_JOB_EXECUTION_PARAMS ( - JOB_EXECUTION_ID BIGINT NOT NULL , - TYPE_CD VARCHAR(6) NOT NULL , - KEY_NAME VARCHAR(100) NOT NULL , - STRING_VAL VARCHAR(250) , - DATE_VAL DATETIME DEFAULT NULL , - LONG_VAL BIGINT , - DOUBLE_VAL DOUBLE PRECISION , - IDENTIFYING CHAR(1) NOT NULL , - constraint JOB_EXEC_PARAMS_FK foreign key (JOB_EXECUTION_ID) - references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) -); - - Below are descriptions for each column: - - - - JOB_EXECUTION_ID: Foreign Key from the BATCH_JOB_EXECUTION table - that indicates the job execution the parameter entry belongs to. It - should be noted that multiple rows (i.e key/value pairs) may exist for - each execution. - - - - TYPE_CD: String representation of the type of value stored, - which can be either a string, date, long, or double. Because the type - must be known, it cannot be null. - - - - KEY_NAME: The parameter key. - - - - STRING_VAL: Parameter value, if the type is string. - - - - DATE_VAL: Parameter value, if the type is date. - - - - LONG_VAL: Parameter value, if the type is a long. - - - - DOUBLE_VAL: Parameter value, if the type is double. - - - - IDENTIFYING: Flag indicating if the parameter contributed to the identity of the related JobInstance. - - - - It is worth noting that there is no primary key for this table. This - is simply because the framework has no use for one, and thus doesn't - require it. If a user so chooses, one may be added with a database - generated key, without causing any issues to the framework itself. -
- -
- BATCH_JOB_EXECUTION - - The BATCH_JOB_EXECUTION table holds all information relevant to the - JobExecution object. Every time a - Job is run there will always be a new - JobExecution, and a new row in this table: - - CREATE TABLE BATCH_JOB_EXECUTION ( - JOB_EXECUTION_ID BIGINT PRIMARY KEY , - VERSION BIGINT, - JOB_INSTANCE_ID BIGINT NOT NULL, - CREATE_TIME TIMESTAMP NOT NULL, - START_TIME TIMESTAMP DEFAULT NULL, - END_TIME TIMESTAMP DEFAULT NULL, - STATUS VARCHAR(10), - EXIT_CODE VARCHAR(20), - EXIT_MESSAGE VARCHAR(2500), - LAST_UPDATED TIMESTAMP, - JOB_CONFIGURATION_LOCATION VARCHAR(2500) NULL, - constraint JOB_INSTANCE_EXECUTION_FK foreign key (JOB_INSTANCE_ID) - references BATCH_JOB_INSTANCE(JOB_INSTANCE_ID) -) ; - - Below are descriptions for each column: - - - - JOB_EXECUTION_ID: Primary key that uniquely identifies this - execution. The value of this column is obtainable by calling the - getId method of the - JobExecution object. - - - - VERSION: See above section. - - - - JOB_INSTANCE_ID: Foreign key from the BATCH_JOB_INSTANCE table - indicating the instance to which this execution belongs. There may be - more than one execution per instance. - - - - CREATE_TIME: Timestamp representing the time that the execution - was created. - - - - START_TIME: Timestamp representing the time the execution was - started. - - - - END_TIME: Timestamp representing the time the execution was - finished, regardless of success or failure. An empty value in this - column even though the job is not currently running indicates that - there has been some type of error and the framework was unable to - perform a last save before failing. - - - - STATUS: Character string representing the status of the - execution. This may be COMPLETED, STARTED, etc. The object - representation of this column is the - BatchStatus enumeration. - - - - EXIT_CODE: Character string representing the exit code of the - execution. In the case of a command line job, this may be converted - into a number. - - - - EXIT_MESSAGE: Character string representing a more detailed - description of how the job exited. In the case of failure, this might - include as much of the stack trace as is possible. - - - - LAST_UPDATED: Timestamp representing the last time this - execution was persisted. - - -
- -
- BATCH_STEP_EXECUTION - - The BATCH_STEP_EXECUTION table holds all information relevant to the - StepExecution object. This table is very similar in - many ways to the BATCH_JOB_EXECUTION table and there will always be at - least one entry per Step for each - JobExecution created: - - CREATE TABLE BATCH_STEP_EXECUTION ( - STEP_EXECUTION_ID BIGINT PRIMARY KEY , - VERSION BIGINT NOT NULL, - STEP_NAME VARCHAR(100) NOT NULL, - JOB_EXECUTION_ID BIGINT NOT NULL, - START_TIME TIMESTAMP NOT NULL , - END_TIME TIMESTAMP DEFAULT NULL, - STATUS VARCHAR(10), - COMMIT_COUNT BIGINT , - READ_COUNT BIGINT , - FILTER_COUNT BIGINT , - WRITE_COUNT BIGINT , - READ_SKIP_COUNT BIGINT , - WRITE_SKIP_COUNT BIGINT , - PROCESS_SKIP_COUNT BIGINT , - ROLLBACK_COUNT BIGINT , - EXIT_CODE VARCHAR(20) , - EXIT_MESSAGE VARCHAR(2500) , - LAST_UPDATED TIMESTAMP, - constraint JOB_EXECUTION_STEP_FK foreign key (JOB_EXECUTION_ID) - references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) -) ; - - Below are descriptions for each column: - - - - STEP_EXECUTION_ID: Primary key that uniquely identifies this - execution. The value of this column should be obtainable by calling - the getId method of the - StepExecution object. - - - - VERSION: See above section. - - - - STEP_NAME: The name of the step to which this execution - belongs. - - - - JOB_EXECUTION_ID: Foreign key from the BATCH_JOB_EXECUTION table - indicating the JobExecution to which this StepExecution belongs. There - may be only one StepExecution for a given - JobExecution for a given - Step name. - - - - START_TIME: Timestamp representing the time the execution was - started. - - - - END_TIME: Timestamp representing the time the execution was - finished, regardless of success or failure. An empty value in this - column even though the job is not currently running indicates that - there has been some type of error and the framework was unable to - perform a last save before failing. - - - - STATUS: Character string representing the status of the - execution. This may be COMPLETED, STARTED, etc. The object - representation of this column is the - BatchStatus enumeration. - - - - COMMIT_COUNT: The number of times in which the step has - committed a transaction during this execution. - - - - READ_COUNT: The number of items read during this - execution. - - - - FILTER_COUNT: The number of items filtered out of this - execution. - - - - WRITE_COUNT: The number of items written and committed during - this execution. - - - - READ_SKIP_COUNT: The number of items skipped on read during this - execution. - - - - WRITE_SKIP_COUNT: The number of items skipped on write during - this execution. - - - - PROCESS_SKIP_COUNT: The number of items skipped during - processing during this execution. - - - - ROLLBACK_COUNT: The number of rollbacks during this execution. - Note that this count includes each time rollback occurs, including - rollbacks for retry and those in the skip recovery procedure. - - - - EXIT_CODE: Character string representing the exit code of the - execution. In the case of a command line job, this may be converted - into a number. - - - - EXIT_MESSAGE: Character string representing a more detailed - description of how the job exited. In the case of failure, this might - include as much of the stack trace as is possible. - - - - LAST_UPDATED: Timestamp representing the last time this - execution was persisted. - - -
- -
- BATCH_JOB_EXECUTION_CONTEXT - - The BATCH_JOB_EXECUTION_CONTEXT table holds all information relevant - to an Job's - ExecutionContext. There is exactly one - Job ExecutionContext per - JobExecution, and it contains all of the job-level - data that is needed for a particular job execution. This data typically - represents the state that must be retrieved after a failure so that a - JobInstance can 'start from where it left - off'. - - CREATE TABLE BATCH_JOB_EXECUTION_CONTEXT ( - JOB_EXECUTION_ID BIGINT PRIMARY KEY, - SHORT_CONTEXT VARCHAR(2500) NOT NULL, - SERIALIZED_CONTEXT CLOB, - constraint JOB_EXEC_CTX_FK foreign key (JOB_EXECUTION_ID) - references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) -) ; - - Below are descriptions for each column: - - - - JOB_EXECUTION_ID: Foreign key representing the - JobExecution to which the context belongs. - There may be more than one row associated to a given execution. - - - - SHORT_CONTEXT: A string version of the - SERIALIZED_CONTEXT. - - - - SERIALIZED_CONTEXT: The entire context, serialized. - - -
- -
- BATCH_STEP_EXECUTION_CONTEXT - - The BATCH_STEP_EXECUTION_CONTEXT table holds all information - relevant to an Step's - ExecutionContext. There is exactly one - ExecutionContext per - StepExecution, and it contains all of the data that - needs to persisted for a particular step execution. This data typically - represents the state that must be retrieved after a failure so that a - JobInstance can 'start from where it left - off'. - - CREATE TABLE BATCH_STEP_EXECUTION_CONTEXT ( - STEP_EXECUTION_ID BIGINT PRIMARY KEY, - SHORT_CONTEXT VARCHAR(2500) NOT NULL, - SERIALIZED_CONTEXT CLOB, - constraint STEP_EXEC_CTX_FK foreign key (STEP_EXECUTION_ID) - references BATCH_STEP_EXECUTION(STEP_EXECUTION_ID) -) ; - - Below are descriptions for each column: - - - - STEP_EXECUTION_ID: Foreign key representing the - StepExecution to which the context belongs. - There may be more than one row associated to a given execution. - - - - SHORT_CONTEXT: A string version of the - SERIALIZED_CONTEXT. - - - - SERIALIZED_CONTEXT: The entire context, serialized. - - -
- -
- Archiving - - Because there are entries in multiple tables every time a batch job - is run, it is common to create an archive strategy for the meta-data - tables. The tables themselves are designed to show a record of what - happened in the past, and generally won't affect the run of any job, with - a couple of notable exceptions pertaining to restart: - - - - The framework will use the meta-data tables to determine if a - particular JobInstance has been run before. If it has been run, and - the job is not restartable, then an exception will be thrown. - - - - If an entry for a JobInstance is removed without having - completed successfully, the framework will think that the job is new, - rather than a restart. - - - - If a job is restarted, the framework will use any data that has - been persisted to the ExecutionContext to restore the Job's state. - Therefore, removing any entries from this table for jobs that haven't - completed successfully will prevent them from starting at the correct - point if run again. - - -
- -
- International and Multi-byte Characters - - If you are using multi-byte character sets (e.g. Chines or Cyrillic) - in your business processing, then those characters might need to be - persisted in the Spring Batch schema. Many users find that - simply changing the schema to double the length of the VARCHAR - columns is enough. Others prefer to configure the JobRepository with max-varchar-length half the value of the VARCHAR column length is enough. Some users have also reported that - they use NVARCHAR in place of VARCHAR - in their schema definitions. The best result will depend on the database - platform and the way the database server has been configured locally. -
- -
- Recommendations for Indexing Meta Data Tables - - Spring Batch provides DDL samples for the meta-data tables in the - Core jar file for several common database platforms. Index declarations - are not included in that DDL because there are too many variations in how - users may want to index depending on their precise platform, local - conventions and also the business requirements of how the jobs will be - operated. The table below provides some indication as to which columns are - going to be used in a WHERE clause by the Dao implementations provided by - Spring Batch, and how frequently they might be used, so that individual - projects can make up their own minds about indexing. - - - Where clauses in SQL statements (excluding primary keys) and - their approximate frequency of use. - - - - - Default Table Name - - Where Clause - - Frequency - - - - BATCH_JOB_INSTANCE - - JOB_NAME = ? and JOB_KEY = ? - - Every time a job is launched - - - - BATCH_JOB_EXECUTION - - JOB_INSTANCE_ID = ? - - Every time a job is restarted - - - - BATCH_EXECUTION_CONTEXT - - EXECUTION_ID = ? and KEY_NAME = ? - - On commit interval, a.k.a. chunk - - - - BATCH_STEP_EXECUTION - - VERSION = ? - - On commit interval, a.k.a. chunk (and at start and end of - step) - - - - BATCH_STEP_EXECUTION - - STEP_NAME = ? and JOB_EXECUTION_ID = ? - - Before each step execution - - - -
-
-
diff --git a/src/site/docbook/reference/spring-batch-integration.xml b/src/site/docbook/reference/spring-batch-integration.xml deleted file mode 100644 index 8b7391b6d..000000000 --- a/src/site/docbook/reference/spring-batch-integration.xml +++ /dev/null @@ -1,902 +0,0 @@ - - - - Spring Batch Integration - - - Spring Batch Integration Introduction - - Many users of Spring Batch may encounter requirements that are - outside the scope of Spring Batch, yet may be efficiently and - concisely implemented using Spring Integration. Conversely, Spring - Batch users may encounter Spring Batch requirements and need a way - to efficiently integrate both frameworks. In this context several - patterns and use-cases emerge and Spring Batch Integration will - address those requirements. - - - The line between Spring Batch and Spring Integration is not always - clear, but there are guidelines that one can follow. Principally, - these are: think about granularity, and apply common patterns. Some - of those common patterns are described in this reference manual - section. - - - Adding messaging to a batch process enables automation of - operations, and also separation and strategizing of key concerns. - For example a message might trigger a job to execute, and then the - sending of the message can be exposed in a variety of ways. Or when - a job completes or fails that might trigger a message to be sent, - and the consumers of those messages might have operational concerns - that have nothing to do with the application itself. Messaging can - also be embedded in a job, for example reading or writing items for - processing via channels. Remote partitioning and remote chunking - provide methods to distribute workloads over an number of workers. - - - Some key concepts that we will cover are: - - - - - Namespace Support - - - - - Launching - Batch Jobs through Messages - - - - - Providing - Feedback with Informational Messages - - - - - Asynchronous - Processors - - - - - Externalizing - Batch Process Execution - - - - - Namespace Support - - Since Spring Batch Integration 1.3, dedicated XML Namespace - support was added, with the aim to provide an easier configuration - experience. In order to activate the namespace, add the following - namespace declarations to your Spring XML Application Context - file: - - <beans xmlns="http://www.springframework.org/schema/beans" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:batch-int="http://www.springframework.org/schema/batch-integration" - xsi:schemaLocation=" - http://www.springframework.org/schema/batch-integration - http://www.springframework.org/schema/batch-integration/spring-batch-integration.xsd"> - - ... - -</beans> - - A fully configured Spring XML Application Context file for Spring - Batch Integration may look like the following: - - <beans xmlns="http://www.springframework.org/schema/beans" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:int="http://www.springframework.org/schema/integration" - xmlns:batch="http://www.springframework.org/schema/batch" - xmlns:batch-int="http://www.springframework.org/schema/batch-integration" - xsi:schemaLocation=" - http://www.springframework.org/schema/batch-integration - http://www.springframework.org/schema/batch-integration/spring-batch-integration.xsd - http://www.springframework.org/schema/batch - http://www.springframework.org/schema/batch/spring-batch.xsd - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans.xsd - http://www.springframework.org/schema/integration - http://www.springframework.org/schema/integration/spring-integration.xsd"> - - ... - -</beans> - - Appending version numbers to the referenced XSD file is also - allowed but, as a version-less declaration will always use the - latest schema, we generally don't recommend appending the version - number to the XSD name. Adding a version number, for instance, - would create possibly issues when updating the Spring Batch - Integration dependencies as they may require more recent versions - of the XML schema. - - - - Launching Batch Jobs through Messages - - When starting batch jobs using the core Spring Batch API you - basically have 2 options: - - - - - Command line via the CommandLineJobRunner - - - - - Programatically via either - JobOperator.start() or - JobLauncher.run(). - - - - - For example, you may want to use the - CommandLineJobRunner when invoking Batch Jobs - using a shell script. Alternatively, you may use the - JobOperator directly, for example when using - Spring Batch as part of a web application. However, what about - more complex use-cases? Maybe you need to poll a remote (S)FTP - server to retrieve the data for the Batch Job. Or your application - has to support multiple different data sources simultaneously. For - example, you may receive data files not only via the web, but also - FTP etc. Maybe additional transformation of the input files is - needed before invoking Spring Batch. - - - Therefore, it would be much more powerful to execute the batch job - using Spring Integration and its numerous adapters. For example, - you can use a File Inbound Channel Adapter to - monitor a directory in the file-system and start the Batch Job as - soon as the input file arrives. Additionally you can create Spring - Integration flows that use multiple different adapters to easily - ingest data for your Batch Jobs from multiple sources - simultaneously using configuration only. Implementing all these - scenarios with Spring Integration is easy as it allow for an - decoupled event-driven execution of the - JobLauncher. - - - Spring Batch Integration provides the - JobLaunchingMessageHandler class that you can - use to launch batch jobs. The input for the - JobLaunchingMessageHandler is provided by a - Spring Integration message, which payload is of type - JobLaunchRequest. This class is a wrapper around the Job - that needs to be launched as well as the JobParameters - necessary to launch the Batch job. - - - The following image illustrates the typical Spring Integration - message flow in order to start a Batch job. The - EIP (Enterprise IntegrationPatterns) website - provides a full overview of messaging icons and their descriptions. - - - - - - - - - - - - - Transforming a file into a JobLaunchRequest - package io.spring.sbi; - -import org.springframework.batch.core.Job; -import org.springframework.batch.core.JobParametersBuilder; -import org.springframework.batch.integration.launch.JobLaunchRequest; -import org.springframework.integration.annotation.Transformer; -import org.springframework.messaging.Message; - -import java.io.File; - -public class FileMessageToJobRequest { - private Job job; - private String fileParameterName; - - public void setFileParameterName(String fileParameterName) { - this.fileParameterName = fileParameterName; - } - - public void setJob(Job job) { - this.job = job; - } - - @Transformer - public JobLaunchRequest toRequest(Message<File> message) { - JobParametersBuilder jobParametersBuilder = - new JobParametersBuilder(); - - jobParametersBuilder.addString(fileParameterName, - message.getPayload().getAbsolutePath()); - - return new JobLaunchRequest(job, jobParametersBuilder.toJobParameters()); - } -} - - - The JobExecution Response - - When a Batch Job is being executed, a - JobExecution instance is returned. This - instance can be used to determine the status of an execution. If - a JobExecution was able to be created - successfully, it will always be returned, regardless of whether - or not the actual execution was successful. - - - The exact behavior on how the JobExecution - instance is returned depends on the provided - TaskExecutor. If a - synchronous (single-threaded) - TaskExecutor implementation is used, the - JobExecution response is only returned - after the job completes. When using an - asynchronous - TaskExecutor, the - JobExecution instance is returned - immediately. Users can then take the id of - JobExecution instance - (JobExecution.getJobId()) and query the - JobRepository for the job's updated status - using the JobExplorer. For more - information, please refer to the Spring - Batch reference documentation on - Querying - the Repository. - - - The following configuration will create a file - inbound-channel-adapter to listen for CSV - files in the provided directory, hand them off to our - transformer (FileMessageToJobRequest), - launch the job via the Job Launching - Gateway then simply log the output of the - JobExecution via the - logging-channel-adapter. - - - - Spring Batch Integration Configuration - <int:channel id="inboundFileChannel"/> -<int:channel id="outboundJobRequestChannel"/> -<int:channel id="jobLaunchReplyChannel"/> - -<int-file:inbound-channel-adapter id="filePoller" - channel="inboundFileChannel" - directory="file:/tmp/myfiles/" - filename-pattern="*.csv"> - <int:poller fixed-rate="1000"/> -</int-file:inbound-channel-adapter> - -<int:transformer input-channel="inboundFileChannel" - output-channel="outboundJobRequestChannel"> - <bean class="io.spring.sbi.FileMessageToJobRequest"> - <property name="job" ref="personJob"/> - <property name="fileParameterName" value="input.file.name"/> - </bean> -</int:transformer> - -<batch-int:job-launching-gateway request-channel="outboundJobRequestChannel" - reply-channel="jobLaunchReplyChannel"/> - -<int:logging-channel-adapter channel="jobLaunchReplyChannel"/> - - Now that we are polling for files and launching jobs, we need to - configure for example our Spring Batch - ItemReader to utilize found file - represented by the job parameter "input.file.name": - - - - Example ItemReader Configuration - <bean id="itemReader" class="org.springframework.batch.item.file.FlatFileItemReader" - scope="step"> - <property name="resource" value="file://#{jobParameters['input.file.name']}"/> - ... -</bean> - - The main points of interest here are injecting the value of - #{jobParameters['input.file.name']} - as the Resource property value and setting the ItemReader bean - to be of Step scope to take advantage of - the late binding support which allows access to the - jobParameters variable. - - - Available Attributes of the Job-Launching Gateway - - - - id Identifies the - underlying Spring bean definition, which is an instance of - either: - - - - - EventDrivenConsumer - - - - - PollingConsumer - - - - - The exact implementation depends on whether the component's - input channel is a: - - - - - SubscribableChannel or - - - - - PollableChannel - - - - - - - - - auto-startup - Boolean flag to indicate that the endpoint should start automatically on - startup. The default is true. - - - - - request-channel - The input MessageChannel of this endpoint. - - - - - reply-channel Message Channel - to which the resulting JobExecution payload will be sent. - - - - - reply-timeout - Allows you to specify how long this gateway will wait for the reply message - to be sent successfully to the reply channel before throwing - an exception. This attribute only applies when the channel - might block, for example when using a bounded queue channel - that is currently full. Also, keep in mind that when sending to a - DirectChannel, the invocation will occur - in the sender's thread. Therefore, the failing of the send - operation may be caused by other components further downstream. - The reply-timeout attribute maps to the - sendTimeout property of the underlying - MessagingTemplate instance. The attribute - will default, if not specified, to-1, - meaning that by default, the Gateway will wait indefinitely. - The value is specified in milliseconds. - - - - - job-launcher - Pass in a - custom - JobLauncher - bean reference. This - attribute is optional. If not specified the adapter will - re-use the instance that is registered under the id - jobLauncher. If no default instance - exists an exception is thrown. - - - - - order - Specifies the order - for invocation when this endpoint is connected as a subscriber - to a SubscribableChannel. - - - - - - Sub-Elements - - When this Gateway is receiving messages from a - PollableChannel, you must either provide - a global default Poller or provide a Poller sub-element to the - Job Launching Gateway: - - <batch-int:job-launching-gateway request-channel="queueChannel" - reply-channel="replyChannel" job-launcher="jobLauncher"> - <int:poller fixed-rate="1000"/> -</batch-int:job-launching-gateway> - - - - - Providing Feedback with Informational Messages - - As Spring Batch jobs can run for long times, providing progress - information will be critical. For example, stake-holders may want - to be notified if a some or all parts of a Batch Job has failed. - Spring Batch provides support for this information being gathered - through: - - - - - Active polling or - - - - - Event-driven, using listeners. - - - - - When starting a Spring Batch job asynchronously, e.g. by using the - Job Launching Gateway, a - JobExecution instance is returned. Thus, - JobExecution.getJobId() can be used to - continuously poll for status updates by retrieving updated - instances of the JobExecution from the - JobRepository using the - JobExplorer. However, this is considered - sub-optimal and an event-driven approach should be preferred. - - - Therefore, Spring Batch provides listeners such as: - - - - - StepListener - - - - - ChunkListener - - - - - JobExecutionListener - - - - - In the following example, a Spring Batch job was configured with a - StepExecutionListener. Thus, Spring - Integration will receive and process any step before/after step - events. For example, the received - StepExecution can be inspected using a - Router. Based on the results of that - inspection, various things can occur for example routing a message - to a Mail Outbound Channel Adapter, so that an Email notification - can be sent out based on some condition. - - - - - - - - - - - Below is an example of how a listener is configured to send a - message to a Gateway for - StepExecution events and log its output to a - logging-channel-adapter: - - - First create the notifications integration beans: - - <int:channel id="stepExecutionsChannel"/> - -<int:gateway id="notificationExecutionsListener" - service-interface="org.springframework.batch.core.StepExecutionListener" - default-request-channel="stepExecutionsChannel"/> - -<int:logging-channel-adapter channel="stepExecutionsChannel"/> - - Then modify your job to add a step level listener: - - <job id="importPayments"> - <step id="step1"> - <tasklet ../> - <chunk ../> - <listeners> - <listener ref="notificationExecutionsListener"/> - </listeners> - </tasklet> - ... - </step> -</job> - - - Asynchronous Processors - - Asynchronous Processors help you to to scale the processing of - items. In the asynchronous processor use-case, an - AsyncItemProcessor serves as a dispatcher, - executing the ItemProcessor's logic for an - item on a new thread. The Future is passed to - the AsynchItemWriter to be written once the - processor completes. - - - Therefore, you can increase performance by using asynchronous item - processing, basically allowing you to implement - fork-join scenarios. The - AsyncItemWriter will gather the results and - write back the chunk as soon as all the results become available. - - - Configuration of both the AsyncItemProcessor - and AsyncItemWriter are simple, first the - AsyncItemProcessor: - - <bean id="processor" - class="org.springframework.batch.integration.async.AsyncItemProcessor"> - <property name="delegate"> - <bean class="your.ItemProcessor"/> - </property> - <property name="taskExecutor"> - <bean class="org.springframework.core.task.SimpleAsyncTaskExecutor"/> - </property> -</bean> - - The property "delegate" is actually - a reference to your ItemProcessor bean and - the "taskExecutor" property is a - reference to the TaskExecutor of your choice. - - - Then we configure the AsyncItemWriter: - - <bean id="itemWriter" - class="org.springframework.batch.integration.async.AsyncItemWriter"> - <property name="delegate"> - <bean id="itemWriter" class="your.ItemWriter"/> - </property> -</bean> - - Again, the property "delegate" is - actually a reference to your ItemWriter bean. - - - - Externalizing Batch Process Execution - - The integration approaches discussed so far suggest use-cases - where Spring Integration wraps Spring Batch like an outer-shell. - However, Spring Batch can also use Spring Integration internally. - Using this approach, Spring Batch users can delegate the - processing of items or even chunks to outside processes. This - allows you to offload complex processing. Spring Batch Integration - provides dedicated support for: - - - - - Remote Chunking - - - - - Remote Partitioning - - - - - Remote Chunking - - - - - - - - - - Taking things one step further, one can also externalize the - chunk processing using the - ChunkMessageChannelItemWriter which is - provided by Spring Batch Integration which will send items out - and collect the result. Once sent, Spring Batch will continue the - process of reading and grouping items, without waiting for the results. - Rather it is the responsibility of the ChunkMessageChannelItemWriter - to gather the results and integrate them back into the Spring Batch process. - - - Using Spring Integration you have full - control over the concurrency of your processes, for instance by - using a QueueChannel instead of a - DirectChannel. Furthermore, by relying on - Spring Integration's rich collection of Channel Adapters (E.g. - JMS or AMQP), you can distribute chunks of a Batch job to - external systems for processing. - - - A simple job with a step to be remotely chunked would have a - configuration similar to the following: - - <job id="personJob"> - <step id="step1"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter" commit-interval="200"/> - </tasklet> - ... - </step> -</job> - - The ItemReader reference would point to the bean you would like - to use for reading data on the master. The ItemWriter reference - points to a special ItemWriter - "ChunkMessageChannelItemWriter" - as described above. The processor (if any) is left off the - master configuration as it is configured on the slave. The - following configuration provides a basic master setup. It's - advised to check any additional component properties such as - throttle limits and so on when implementing your use case. - - <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> - <property name="brokerURL" value="tcp://localhost:61616"/> -</bean> - -<int-jms:outbound-channel-adapter id="requests" destination-name="requests"/> - -<bean id="messagingTemplate" - class="org.springframework.integration.core.MessagingTemplate"> - <property name="defaultChannel" ref="requests"/> - <property name="receiveTimeout" value="2000"/> -</bean> - -<bean id="itemWriter" - class="org.springframework.batch.integration.chunk.ChunkMessageChannelItemWriter" - scope="step"> - <property name="messagingOperations" ref="messagingTemplate"/> - <property name="replyChannel" ref="replies"/> -</bean> - -<bean id="chunkHandler" - class="org.springframework.batch.integration.chunk.RemoteChunkHandlerFactoryBean"> - <property name="chunkWriter" ref="itemWriter"/> - <property name="step" ref="step1"/> -</bean> - -<int:channel id="replies"> - <int:queue/> -</int:channel> - -<int-jms:message-driven-channel-adapter id="jmsReplies" - destination-name="replies" - channel="replies"/> - - This configuration provides us with a number of beans. We - configure our messaging middleware using ActiveMQ and - inbound/outbound JMS adapters provided by Spring Integration. As - shown, our itemWriter bean which is - referenced by our job step utilizes the - ChunkMessageChannelItemWriter for writing chunks over the - configured middleware. - - - Now lets move on to the slave configuration: - - <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> - <property name="brokerURL" value="tcp://localhost:61616"/> -</bean> - -<int:channel id="requests"/> -<int:channel id="replies"/> - -<int-jms:message-driven-channel-adapter id="jmsIn" - destination-name="requests" - channel="requests"/> - -<int-jms:outbound-channel-adapter id="outgoingReplies" - destination-name="replies" - channel="replies"> -</int-jms:outbound-channel-adapter> - -<int:service-activator id="serviceActivator" - input-channel="requests" - output-channel="replies" - ref="chunkProcessorChunkHandler" - method="handleChunk"/> - -<bean id="chunkProcessorChunkHandler" - class="org.springframework.batch.integration.chunk.ChunkProcessorChunkHandler"> - <property name="chunkProcessor"> - <bean class="org.springframework.batch.core.step.item.SimpleChunkProcessor"> - <property name="itemWriter"> - <bean class="io.spring.sbi.PersonItemWriter"/> - </property> - <property name="itemProcessor"> - <bean class="io.spring.sbi.PersonItemProcessor"/> - </property> - </bean> - </property> -</bean> - - Most of these configuration items should look familiar from the - master configuration. Slaves do not need access to things like - the Spring Batch JobRepository nor access - to the actual job configuration file. The main bean of interest - is the - "chunkProcessorChunkHandler". The - chunkProcessor property of - ChunkProcessorChunkHandler takes a - configured SimpleChunkProcessor which is - where you would provide a reference to your - ItemWriter and optionally your - ItemProcessor that will run on the slave - when it receives chunks from the master. - - - For more information, please also consult the Spring Batch - manual, specifically the chapter on - Remote - Chunking. - - - - Remote Partitioning - - - - - - - - - - Remote Partitioning, on the other hand, is useful when the - problem is not the processing of items, but the associated I/O - represents the bottleneck. Using Remote Partitioning, work can - be farmed out to slaves that execute complete Spring Batch - steps. Thus, each slave has its own - ItemReader, - ItemProcessor and - ItemWriter. For this purpose, Spring Batch - Integration provides the - MessageChannelPartitionHandler. - - - This implementation of the PartitionHandler - interface uses MessageChannel instances to - send instructions to remote workers and receive their responses. - This provides a nice abstraction from the transports (E.g. JMS - or AMQP) being used to communicate with the remote workers. - - - The reference manual section - Remote - Partitioning provides an overview of the concepts and - components needed to configure Remote Partitioning and shows an - example of using the default - TaskExecutorPartitionHandler to partition - in separate local threads of execution. For Remote Partitioning - to multiple JVM's, two additional components are required: - - - - - Remoting fabric or grid environment - - - - - A PartitionHandler implementation that supports the desired - remoting fabric or grid environment - - - - - Similar to Remote Chunking JMS can be used as the "remoting - fabric" and the PartitionHandler implementation to be used - as described above is the - MessageChannelPartitionHandler. The example - shown below assumes an existing partitioned job and focuses on - the MessageChannelPartitionHandler and JMS - configuration: - - <bean id="partitionHandler" - class="org.springframework.batch.integration.partition.MessageChannelPartitionHandler"> - <property name="stepName" value="step1"/> - <property name="gridSize" value="3"/> - <property name="replyChannel" ref="outbound-replies"/> - <property name="messagingOperations"> - <bean class="org.springframework.integration.core.MessagingTemplate"> - <property name="defaultChannel" ref="outbound-requests"/> - <property name="receiveTimeout" value="100000"/> - </bean> - </property> -</bean> - -<int:channel id="outbound-requests"/> -<int-jms:outbound-channel-adapter destination="requestsQueue" - channel="outbound-requests"/> - -<int:channel id="inbound-requests"/> -<int-jms:message-driven-channel-adapter destination="requestsQueue" - channel="inbound-requests"/> - -<bean id="stepExecutionRequestHandler" - class="org.springframework.batch.integration.partition.StepExecutionRequestHandler"> - <property name="jobExplorer" ref="jobExplorer"/> - <property name="stepLocator" ref="stepLocator"/> -</bean> - -<int:service-activator ref="stepExecutionRequestHandler" input-channel="inbound-requests" - output-channel="outbound-staging"/> - -<int:channel id="outbound-staging"/> -<int-jms:outbound-channel-adapter destination="stagingQueue" - channel="outbound-staging"/> - -<int:channel id="inbound-staging"/> -<int-jms:message-driven-channel-adapter destination="stagingQueue" - channel="inbound-staging"/> - -<int:aggregator ref="partitionHandler" input-channel="inbound-staging" - output-channel="outbound-replies"/> - -<int:channel id="outbound-replies"> - <int:queue/> -</int:channel> - -<bean id="stepLocator" - class="org.springframework.batch.integration.partition.BeanFactoryStepLocator" /> - - Also ensure the partition handler attribute - maps to the partitionHandler bean: - - <job id="personJob"> - <step id="step1.master"> - <partition partitioner="partitioner" handler="partitionHandler"/> - ... - </step> -</job> - - - - diff --git a/src/site/docbook/reference/spring-batch-intro.xml b/src/site/docbook/reference/spring-batch-intro.xml deleted file mode 100644 index aec896f3f..000000000 --- a/src/site/docbook/reference/spring-batch-intro.xml +++ /dev/null @@ -1,523 +0,0 @@ - - - - Spring Batch Introduction - - Many applications within the enterprise domain require bulk processing - to perform business operations in mission critical environments. These - business operations include automated, complex processing of large volumes - of information that is most efficiently processed without user interaction. - These operations typically include time based events (e.g. month-end - calculations, notices or correspondence), periodic application of complex - business rules processed repetitively across very large data sets (e.g. - Insurance benefit determination or rate adjustments), or the integration of - information that is received from internal and external systems that - typically requires formatting, validation and processing in a transactional - manner into the system of record. Batch processing is used to process - billions of transactions every day for enterprises. - - Spring Batch is a lightweight, comprehensive batch framework designed - to enable the development of robust batch applications vital for the daily - operations of enterprise systems. Spring Batch builds upon the productivity, - POJO-based development approach, and general ease of use capabilities people - have come to know from the Spring Framework, while making it easy for - developers to access and leverage more advance enterprise services when - necessary. Spring Batch is not a scheduling framework. There are many good - enterprise schedulers available in both the commercial and open source - spaces such as Quartz, Tivoli, Control-M, etc. It is intended to work in - conjunction with a scheduler, not replace a scheduler. - - Spring Batch provides reusable functions that are essential in - processing large volumes of records, including logging/tracing, transaction - management, job processing statistics, job restart, skip, and resource - management. It also provides more advance technical services and features - that will enable extremely high-volume and high performance batch jobs - though optimization and partitioning techniques. Simple as well as complex, - high-volume batch jobs can leverage the framework in a highly scalable - manner to process significant volumes of information. - -
- Background - - While open source software projects and associated communities have - focused greater attention on web-based and SOA messaging-based - architecture frameworks, there has been a notable lack of focus on - reusable architecture frameworks to accommodate Java-based batch - processing needs, despite continued needs to handle such processing within - enterprise IT environments. The lack of a standard, reusable batch - architecture has resulted in the proliferation of many one-off, in-house - solutions developed within client enterprise IT functions. - - SpringSource and Accenture have collaborated to change this. - Accenture's hands-on industry and technical experience in implementing - batch architectures, SpringSource's depth of technical experience, and - Spring's proven programming model together mark a natural and powerful - partnership to create high-quality, market relevant software aimed at - filling an important gap in enterprise Java. Both companies are also - currently working with a number of clients solving similar problems - developing Spring-based batch architecture solutions. This has provided - some useful additional detail and real-life constraints helping to ensure - the solution can be applied to the real-world problems posed by clients. - For these reasons and many more, SpringSource and Accenture have teamed to - collaborate on the development of Spring Batch. - - Accenture has contributed previously proprietary batch processing - architecture frameworks, based upon decades worth of experience in - building batch architectures with the last several generations of - platforms, (i.e., COBOL/Mainframe, C++/Unix, and now Java/anywhere) to the - Spring Batch project along with committer resources to drive support, - enhancements, and the future roadmap. - - The collaborative effort between Accenture and SpringSource aims to - promote the standardization of software processing approaches, frameworks, - and tools that can be consistently leveraged by enterprise users when - creating batch applications. Companies and government agencies desiring to - deliver standard, proven solutions to their enterprise IT environments - will benefit from Spring Batch. -
- -
- Usage Scenarios - - A typical batch program generally reads a large number of records - from a database, file, or queue, processes the data in some fashion, and - then writes back data in a modified form. Spring Batch automates this - basic batch iteration, providing the capability to process similar - transactions as a set, typically in an offline environment without any - user interaction. Batch jobs are part of most IT projects and Spring Batch - is the only open source framework that provides a robust, enterprise-scale - solution. - - Business Scenarios - - Commit batch process periodically - - - - Concurrent batch processing: parallel processing of a - job - - - - Staged, enterprise message-driven processing - - - - Massively parallel batch processing - - - - Manual or scheduled restart after failure - - - - Sequential processing of dependent steps (with extensions to - workflow-driven batches) - - - - Partial processing: skip records (e.g. on rollback) - - - - Whole-batch transaction: for cases with a small batch size or - existing stored procedures/scripts - - - - Technical Objectives - - Batch developers use the Spring programming model: concentrate - on business logic; let the framework take care of - infrastructure. - - - - Clear separation of concerns between the infrastructure, the - batch execution environment, and the batch application. - - - - Provide common, core execution services as interfaces that all - projects can implement. - - - - Provide simple and default implementations of the core - execution interfaces that can be used ‘out of the box’. - - - - Easy to configure, customize, and extend services, by - leveraging the spring framework in all layers. - - - - All existing core services should be easy to replace or - extend, without any impact to the infrastructure layer. - - - - Provide a simple deployment model, with the architecture JARs - completely separate from the application, built using Maven. - - -
- -
- Spring Batch Architecture - - - - Spring Batch is designed with extensibility and a diverse group of - end users in mind. The figure below shows a sketch of the layered - architecture that supports the extensibility and ease of use for end-user - developers. - - - - - - - - - Figure 1.1: Spring Batch Layered - Architecture - - - This layered architecture highlights three major high level - components: Application, Core, and Infrastructure. The application - contains all batch jobs and custom code written by developers using Spring - Batch. The Batch Core contains the core runtime classes necessary to - launch and control a batch job. It includes things such as a - JobLauncher, Job, and - Step implementations. Both Application and Core are - built on top of a common infrastructure. This infrastructure contains - common readers and writers, and services such as the - RetryTemplate, which are used both by application - developers(ItemReader and - ItemWriter) and the core framework itself. - (retry) -
- -
- General Batch Principles and Guidelines - The following are a number of key principles, guidelines, and general considerations to take into consideration when building a batch solution. - - - A batch architecture typically affects on-line architecture and vice versa. Design with both architectures and environments in mind using common building blocks when possible. - - - Simplify as much as possible and avoid building complex logical structures in single batch applications. - - - Process data as close to where the data physically resides as possible or vice versa (i.e., keep your data where your processing occurs). - - - Minimize system resource use, especially I/O. Perform as many operations as possible in internal memory. - - - Review application I/O (analyze SQL statements) to ensure that unnecessary physical I/O is avoided. In particular, the following four common flaws need to be looked for: - - - Reading data for every transaction when the data could be read once and kept cached or in the working storage; - - - Rereading data for a transaction where the data was read earlier in the same transaction; - - - Causing unnecessary table or index scans; - - - Not specifying key values in the WHERE clause of an SQL statement. - - - - - - Do not do things twice in a batch run. For instance, if you need data summarization for reporting purposes, increment stored totals if possible when data is being initially processed, so your reporting application does not have to reprocess the same data. - - - Allocate enough memory at the beginning of a batch application to avoid time-consuming reallocation during the process. - - - Always assume the worst with regard to data integrity. Insert adequate checks and record validation to maintain data integrity. - - - Implement checksums for internal validation where possible. For example, flat files should have a trailer record telling the total of records in the file and an aggregate of the key fields. - - - Plan and execute stress tests as early as possible in a production-like environment with realistic data volumes. - - - In large batch systems backups can be challenging, especially if the system is running concurrent with on-line on a 24-7 basis. Database backups are typically well taken care of in the on-line design, but file backups should be considered to be just as important. If the system depends on flat files, file backup procedures should not only be in place and documented, but regularly tested as well. - - -
- -
- Batch Processing Strategies - To help design and implement batch systems, basic batch application building blocks and patterns should be provided to the designers and programmers in form of sample structure charts and code shells. When starting to design a batch job, the business logic should be decomposed into a series of steps which can be implemented using the following standard building blocks: - - - - Conversion Applications: For each type of file supplied by or generated to an external system, a conversion application will need to be created to convert the transaction records supplied into a standard format required for processing. This type of batch application can partly or entirely consist of translation utility modules (see Basic Batch Services). - - - Validation Applications: Validation applications ensure that all input/output records are correct and consistent. Validation is typically based on file headers and trailers, checksums and validation algorithms as well as record level cross-checks. - - - Extract Applications: An application that reads a set of records from a database or input file, selects records based on predefined rules, and writes the records to an output file. - - - Extract/Update Applications: An application that reads records from a database or an input file, and makes changes to a database or an output file driven by the data found in each input record. - - - Processing and Updating Applications: An application that performs processing on input transactions from an extract or a validation application. The processing will usually involve reading a database to obtain data required for processing, potentially updating the database and creating records for output processing. - - - Output/Format Applications: Applications reading an input file, restructures data from this record according to a standard format, and produces an output file for printing or transmission to another program or system. - - - - Additionally a basic application shell should be provided for business logic that cannot be built using the previously mentioned building blocks. - - In addition to the main building blocks, each application may use one or more of standard utility steps, such as: - - - - Sort - A Program that reads an input file and produces an output file where records have been re-sequenced according to a sort key field in the records. Sorts are usually performed by standard system utilities. - - - Split - A program that reads a single input file, and writes each record to one of several output files based on a field value. Splits can be tailored or performed by parameter-driven standard system utilities. - - - Merge - A program that reads records from multiple input files and produces one output file with combined data from the input files. Merges can be tailored or performed by parameter-driven standard system utilities. - - - - Batch applications can additionally be categorized by their input source: - - - - Database-driven applications are driven by rows or values retrieved from the database. - - - File-driven applications are driven by records or values retrieved from a file. - - - Message-driven applications are driven by messages retrieved from a message queue. - - - - The foundation of any batch system is the processing strategy. Factors affecting the selection of the strategy include: estimated batch system volume, concurrency with on-line or with another batch systems, available batch windows (and with more enterprises wanting to be up and running 24x7, this leaves no obvious batch windows). - - Typical processing options for batch are: - - - - Normal processing in a batch window during off-line - - - Concurrent batch / on-line processing - - - Parallel processing of many different batch runs or jobs at the same time - - - Partitioning (i.e. processing of many instances of the same job at the same time) - - - A combination of these - - - - The order in the list above reflects the implementation complexity, processing in a batch window being the easiest and partitioning the most complex to implement. - - Some or all of these options may be supported by a commercial scheduler. - - In the following section these processing options are discussed in more detail. It is important to notice that the commit and locking strategy adopted by batch processes will be dependent on the type of processing performed, and as a rule of thumb and the on-line locking strategy should also use the same principles. Therefore, the batch architecture cannot be simply an afterthought when designing an overall architecture. - - The locking strategy can use only normal database locks, or an additional custom locking service can be implemented in the architecture. The locking service would track database locking (for example by storing the necessary information in a dedicated db-table) and give or deny permissions to the application programs requesting a db operation. Retry logic could also be implemented by this architecture to avoid aborting a batch job in case of a lock situation. - - 1. Normal processing in a batch window - For simple batch processes running in a separate batch window, where the data being updated is not required by on-line users or other batch processes, concurrency is not an issue and a single commit can be done at the end of the batch run. - - In most cases a more robust approach is more appropriate. A thing to keep in mind is that batch systems have a tendency to grow as time goes by, both in terms of complexity and the data volumes they will handle. If no locking strategy is in place and the system still relies on a single commit point, modifying the batch programs can be painful. Therefore, even with the simplest batch systems, consider the need for commit logic for restart-recovery options as well as the information concerning the more complex cases below. - - 2. Concurrent batch / on-line processing - Batch applications processing data that can simultaneously be updated by on-line users, should not lock any data (either in the database or in files) which could be required by on-line users for more than a few seconds. Also updates should be committed to the database at the end of every few transaction. This minimizes the portion of data that is unavailable to other processes and the elapsed time the data is unavailable. - - Another option to minimize physical locking is to have a logical row-level locking implemented using either an Optimistic Locking Pattern or a Pessimistic Locking Pattern. - - - - Optimistic locking assumes a low likelihood of record contention. It typically means inserting a timestamp column in each database table used concurrently by both batch and on-line processing. When an application fetches a row for processing, it also fetches the timestamp. As the application then tries to update the processed row, the update uses the original timestamp in the WHERE clause. If the timestamp matches, the data and the timestamp will be updated successfully. If the timestamp does not match, this indicates that another application has updated the same row between the fetch and the update attempt and therefore the update cannot be performed. - - - Pessimistic locking is any locking strategy that assumes there is a high likelihood of record contention and therefore either a physical or logical lock needs to be obtained at retrieval time. One type of pessimistic logical locking uses a dedicated lock-column in the database table. When an application retrieves the row for update, it sets a flag in the lock column. With the flag in place, other applications attempting to retrieve the same row will logically fail. When the application that set the flag updates the row, it also clears the flag, enabling the row to be retrieved by other applications. Please note, that the integrity of data must be maintained also between the initial fetch and the setting of the flag, for example by using db locks (e.g., SELECT FOR UPDATE). Note also that this method suffers from the same downside as physical locking except that it is somewhat easier to manage building a time-out mechanism that will get the lock released if the user goes to lunch while the record is locked. - - - - These patterns are not necessarily suitable for batch processing, but they might be used for concurrent batch and on-line processing (e.g. in cases where the database doesn't support row-level locking). As a general rule, optimistic locking is more suitable for on-line applications, while pessimistic locking is more suitable for batch applications. Whenever logical locking is used, the same scheme must be used for all applications accessing data entities protected by logical locks. - - Note that both of these solutions only address locking a single record. Often we may need to lock a logically related group of records. With physical locks, you have to manage these very carefully in order to avoid potential deadlocks. With logical locks, it is usually best to build a logical lock manager that understands the logical record groups you want to protect and can ensure that locks are coherent and non-deadlocking. This logical lock manager usually uses its own tables for lock management, contention reporting, time-out mechanism, etc. - - 3. Parallel Processing - Parallel processing allows multiple batch runs / jobs to run in parallel to minimize the total elapsed batch processing time. This is not a problem as long as the jobs are not sharing the same files, db-tables or index spaces. If they do, this service should be implemented using partitioned data. Another option is to build an architecture module for maintaining interdependencies using a control table. A control table should contain a row for each shared resource and whether it is in use by an application or not. The batch architecture or the application in a parallel job would then retrieve information from that table to determine if it can get access to the resource it needs or not. - - If the data access is not a problem, parallel processing can be implemented through the use of additional threads to process in parallel. In the mainframe environment, parallel job classes have traditionally been used, in order to ensure adequate CPU time for all the processes. Regardless, the solution has to be robust enough to ensure time slices for all the running processes. - - Other key issues in parallel processing include load balancing and the availability of general system resources such as files, database buffer pools etc. Also note that the control table itself can easily become a critical resource. - - 4. Partitioning - Using partitioning allows multiple versions of large batch applications to run concurrently. The purpose of this is to reduce the elapsed time required to process long batch jobs. Processes which can be successfully partitioned are those where the input file can be split and/or the main database tables partitioned to allow the application to run against different sets of data. - - In addition, processes which are partitioned must be designed to only process their assigned data set. A partitioning architecture has to be closely tied to the database design and the database partitioning strategy. Please note, that the database partitioning doesn't necessarily mean physical partitioning of the database, although in most cases this is advisable. The following picture illustrates the partitioning approach: - - - - - - - - - - - Figure 1.2: Partitioned Process - - - - - - - - The architecture should be flexible enough to allow dynamic configuration of the number of partitions. Both automatic and user controlled configuration should be considered. Automatic configuration may be based on parameters such as the input file size and/or the number of input records. - - 4.1 Partitioning Approaches - The following lists some of the possible partitioning approaches. Selecting a partitioning approach has to be done on a case-by-case basis. - - 1. Fixed and Even Break-Up of Record Set - - This involves breaking the input record set into an even number of portions (e.g. 10, where each portion will have exactly 1/10th of the entire record set). Each portion is then processed by one instance of the batch/extract application. - - In order to use this approach, preprocessing will be required to split the recordset up. The result of this split will be a lower and upper bound placement number which can be used as input to the batch/extract application in order to restrict its processing to its portion alone. - - Preprocessing could be a large overhead as it has to calculate and determine the bounds of each portion of the record set. - - 2. Breakup by a Key Column - - This involves breaking up the input record set by a key column such as a location code, and assigning data from each key to a batch instance. In order to achieve this, column values can either be - - 3. Assigned to a batch instance via a partitioning table (see below for details). - - 4. Assigned to a batch instance by a portion of the value (e.g. values 0000-0999, 1000 - 1999, etc.) - - Under option 1, addition of new values will mean a manual reconfiguration of the batch/extract to ensure that the new value is added to a particular instance. - - Under option 2, this will ensure that all values are covered via an instance of the batch job. However, the number of values processed by one instance is dependent on the distribution of column values (i.e. there may be a large number of locations in the 0000-0999 range, and few in the 1000-1999 range). Under this option, the data range should be designed with partitioning in mind. - - Under both options, the optimal even distribution of records to batch instances cannot be realized. There is no dynamic configuration of the number of batch instances used. - - 5. Breakup by Views - - This approach is basically breakup by a key column, but on the database level. It involves breaking up the recordset into views. These views will be used by each instance of the batch application during its processing. The breakup will be done by grouping the data. - - With this option, each instance of a batch application will have to be configured to hit a particular view (instead of the master table). Also, with the addition of new data values, this new group of data will have to be included into a view. There is no dynamic configuration capability, as a change in the number of instances will result in a change to the views. - - 6. Addition of a Processing Indicator - - This involves the addition of a new column to the input table, which acts as an indicator. As a preprocessing step, all indicators would be marked to non-processed. During the record fetch stage of the batch application, records are read on the condition that that record is marked non-processed, and once they are read (with lock), they are marked processing. When that record is completed, the indicator is updated to either complete or error. Many instances of a batch application can be started without a change, as the additional column ensures that a record is only processed once. - - With this option, I/O on the table increases dynamically. In the case of an updating batch application, this impact is reduced, as a write will have to occur anyway. - - 7. Extract Table to a Flat File - - This involves the extraction of the table into a file. This file can then be split into multiple segments and used as input to the batch instances. - - With this option, the additional overhead of extracting the table into a file, and splitting it, may cancel out the effect of multi-partitioning. Dynamic configuration can be achieved via changing the file splitting script. - - 8. Use of a Hashing Column - - This scheme involves the addition of a hash column (key/index) to the database tables used to retrieve the driver record. This hash column will have an indicator to determine which instance of the batch application will process this particular row. For example, if there are three batch instances to be started, then an indicator of 'A' will mark that row for processing by instance 1, an indicator of 'B' will mark that row for processing by instance 2, etc. - - The procedure used to retrieve the records would then have an additional WHERE clause to select all rows marked by a particular indicator. The inserts in this table would involve the addition of the marker field, which would be defaulted to one of the instances (e.g. 'A'). - - A simple batch application would be used to update the indicators such as to redistribute the load between the different instances. When a sufficiently large number of new rows have been added, this batch can be run (anytime, except in the batch window) to redistribute the new rows to other instances. - - Additional instances of the batch application only require the running of the batch application as above to redistribute the indicators to cater for a new number of instances. - - 4.2 Database and Application design Principles - - An architecture that supports multi-partitioned applications which run against partitioned database tables using the key column approach, should include a central partition repository for storing partition parameters. This provides flexibility and ensures maintainability. The repository will generally consist of a single table known as the partition table. - - Information stored in the partition table will be static and in general should be maintained by the DBA. The table should consist of one row of information for each partition of a multi-partitioned application. The table should have columns for: Program ID Code, Partition Number (Logical ID of the partition), Low Value of the db key column for this partition, High Value of the db key column for this partition. - - On program start-up the program id and partition number should be passed to the application from the architecture (Control Processing Tasklet). These variables are used to read the partition table, to determine what range of data the application is to process (if a key column approach is used). In addition the partition number must be used throughout the processing to: - - - - Add to the output files/database updates in order for the merge process to work properly - - - Report normal processing to the batch log and any errors that occur during execution to the architecture error handler - - - - 4.3 Minimizing Deadlocks - When applications run in parallel or partitioned, contention in database resources and deadlocks may occur. It is critical that the database design team eliminates potential contention situations as far as possible as part of the database design. - - Also ensure that the database index tables are designed with deadlock prevention and performance in mind. - - Deadlocks or hot spots often occur in administration or architecture tables such as log tables, control tables, and lock tables. The implications of these should be taken into account as well. A realistic stress test is crucial for identifying the possible bottlenecks in the architecture. - - To minimize the impact of conflicts on data, the architecture should provide services such as wait-and-retry intervals when attaching to a database or when encountering a deadlock. This means a built-in mechanism to react to certain database return codes and instead of issuing an immediate error handling, waiting a predetermined amount of time and retrying the database operation. - - 4.4 Parameter Passing and Validation - - The partition architecture should be relatively transparent to application developers. The architecture should perform all tasks associated with running the application in a partitioned mode including: - - - - Retrieve partition parameters before application start-up - - - Validate partition parameters before application start-up - - - Pass parameters to application at start-up - - - - The validation should include checks to ensure that: - - - - the application has sufficient partitions to cover the whole data range - - - there are no gaps between partitions - - - - If the database is partitioned, some additional validation may be necessary to ensure that a single partition does not span database partitions. - - Also the architecture should take into consideration the consolidation of partitions. Key questions include: - - - - Must all the partitions be finished before going into the next job step? - - - What happens if one of the partitions aborts? - - - -
-
diff --git a/src/site/docbook/reference/step.xml b/src/site/docbook/reference/step.xml deleted file mode 100644 index 338af0310..000000000 --- a/src/site/docbook/reference/step.xml +++ /dev/null @@ -1,1741 +0,0 @@ - - - - Configuring a Step - - As discussed in , a - Step is a domain object that encapsulates an - independent, sequential phase of a batch job and contains all of the - information necessary to define and control the actual batch processing. - This is a necessarily vague description because the contents of any given - Step are at the discretion of the developer writing a - Job. A Step can be as simple or complex as the - developer desires. A simple Step might load data from - a file into the database, requiring little or no code. (depending upon the - implementations used) A more complex Step may have - complicated business rules that are applied as part of the - processing. - - - - - - - - - - - -
- Chunk-Oriented Processing - - Spring Batch uses a 'Chunk Oriented' processing style within its - most common implementation. Chunk oriented processing refers to reading - the data one at a time, and creating 'chunks' that will be written out, - within a transaction boundary. One item is read in from an - ItemReader, handed to an - ItemProcessor, and aggregated. Once the number of - items read equals the commit interval, the entire chunk is written out via - the ItemWriter, and then the transaction is committed. - - - - - - - - - - - - Below is a code representation of the same concepts shown - above: - - List items = new Arraylist(); -for(int i = 0; i < commitInterval; i++){ - Object item = itemReader.read() - Object processedItem = itemProcessor.process(item); - items.add(processedItem); -} -itemWriter.write(items); - -
- Configuring a Step - - Despite the relatively short list of required dependencies for a - Step, it is an extremely complex class that can - potentially contain many collaborators. In order to ease configuration, - the Spring Batch namespace can be used: - - <job id="sampleJob" job-repository="jobRepository"> - <step id="step1"> - <tasklet transaction-manager="transactionManager"> - <chunk reader="itemReader" writer="itemWriter" commit-interval="10"/> - </tasklet> - </step> -</job> - - The configuration above represents the only required dependencies - to create a item-oriented step: - - reader - The ItemReader that provides - items for processing. - - - - writer - The ItemWriter that - processes the items provided by the - ItemReader. - - - - transaction-manager - Spring's - PlatformTransactionManager that will be - used to begin and commit transactions during processing. - - - - job-repository - The JobRepository - that will be used to periodically store the - StepExecution and - ExecutionContext during processing (just - before committing). For an in-line <step/> (one defined - within a <job/>) it is an attribute on the <job/> - element; for a standalone step, it is defined as an attribute of - the <tasklet/>. - - - - commit-interval - The number of items that will be processed - before the transaction is committed. - - - - It should be noted that, job-repository defaults to - "jobRepository" and transaction-manager defaults to "transactionManger". - Furthermore, the ItemProcessor is optional, not - required, since the item could be directly passed from the reader to the - writer. -
- -
- Inheriting from a Parent Step - - If a group of Steps share similar - configurations, then it may be helpful to define a "parent" - Step from which the concrete - Steps may inherit properties. Similar to class - inheritance in Java, the "child" Step will - combine its elements and attributes with the parent's. The child will - also override any of the parent's Steps. - - In the following example, the Step - "concreteStep1" will inherit from "parentStep". It will be instantiated - with 'itemReader', 'itemProcessor', 'itemWriter', startLimit=5, and - allowStartIfComplete=true. Additionally, the commitInterval will be '5' - since it is overridden by the "concreteStep1": - - <step id="parentStep"> - <tasklet allow-start-if-complete="true"> - <chunk reader="itemReader" writer="itemWriter" commit-interval="10"/> - </tasklet> -</step> - -<step id="concreteStep1" parent="parentStep"> - <tasklet start-limit="5"> - <chunk processor="itemProcessor" commit-interval="5"/> - </tasklet> -</step> - - The id attribute is still required on the step within the job - element. This is for two reasons: - - The id will be used as the step name when persisting the - StepExecution. If the same standalone step is referenced in more - than one step in the job, an error will occur. - - - - When creating job flows, as described later in this chapter, - the next attribute should be referring to the step in the flow, - not the standalone step. - - - -
- Abstract Step - - Sometimes it may be necessary to define a parent - Step that is not a complete - Step configuration. If, for instance, the - reader, writer, and tasklet attributes are left off of a - Step configuration, then initialization will - fail. If a parent must be defined without these properties, then the - "abstract" attribute should be used. An "abstract" - Step will not be instantiated; it is used only - for extending. - - In the following example, the Step - "abstractParentStep" would not instantiate if it were not declared to - be abstract. The Step "concreteStep2" will have - 'itemReader', 'itemWriter', and commitInterval=10. - - <step id="abstractParentStep" abstract="true"> - <tasklet> - <chunk commit-interval="10"/> - </tasklet> -</step> - -<step id="concreteStep2" parent="abstractParentStep"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter"/> - </tasklet> -</step> -
- -
- Merging Lists - - Some of the configurable elements on - Steps are lists; the <listeners/> - element, for instance. If both the parent and child - Steps declare a <listeners/> element, - then the child's list will override the parent's. In order to allow a - child to add additional listeners to the list defined by the parent, - every list element has a "merge" attribute. If the element specifies - that merge="true", then the child's list will be combined with the - parent's instead of overriding it. - - In the following example, the Step - "concreteStep3" will be created will two listeners: - listenerOne and - listenerTwo: - - <step id="listenersParentStep" abstract="true"> - <listeners> - <listener ref="listenerOne"/> - <listeners> -</step> - -<step id="concreteStep3" parent="listenersParentStep"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter" commit-interval="5"/> - </tasklet> - <listeners merge="true"> - <listener ref="listenerTwo"/> - <listeners> -</step> -
-
- -
- The Commit Interval - - As mentioned above, a step reads in and writes out items, - periodically committing using the supplied - PlatformTransactionManager. With a - commit-interval of 1, it will commit after writing each individual item. - This is less than ideal in many situations, since beginning and - committing a transaction is expensive. Ideally, it is preferable to - process as many items as possible in each transaction, which is - completely dependent upon the type of data being processed and the - resources with which the step is interacting. For this reason, the - number of items that are processed within a commit can be - configured. - - <job id="sampleJob"> - <step id="step1"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter" commit-interval="10"/> - </tasklet> - </step> -</job> - - In the example above, 10 items will be processed within each - transaction. At the beginning of processing a transaction is begun, and - each time read is called on the - ItemReader, a counter is incremented. When it - reaches 10, the list of aggregated items is passed to the - ItemWriter, and the transaction will be - committed. -
- -
- Configuring a Step for Restart - - In , restarting a - Job was discussed. Restart has numerous impacts - on steps, and as such may require some specific configuration. - -
- Setting a StartLimit - - There are many scenarios where you may want to control the - number of times a Step may be started. For - example, a particular Step might need to be - configured so that it only runs once because it invalidates some - resource that must be fixed manually before it can be run again. This - is configurable on the step level, since different steps may have - different requirements. A Step that may only be - executed once can exist as part of the same Job - as a Step that can be run infinitely. Below is - an example start limit configuration: - - <step id="step1"> - <tasklet start-limit="1"> - <chunk reader="itemReader" writer="itemWriter" commit-interval="10"/> - </tasklet> -</step> - - The simple step above can be run only once. Attempting to run it - again will cause an exception to be thrown. It should be noted that - the default value for the start-limit is - Integer.MAX_VALUE. -
- -
- Restarting a completed step - - In the case of a restartable job, there may be one or more steps - that should always be run, regardless of whether or not they were - successful the first time. An example might be a validation step, or a - Step that cleans up resources before - processing. During normal processing of a restarted job, any step with - a status of 'COMPLETED', meaning it has already been completed - successfully, will be skipped. Setting allow-start-if-complete to - "true" overrides this so that the step will always run: - - <step id="step1"> - <tasklet allow-start-if-complete="true"> - <chunk reader="itemReader" writer="itemWriter" commit-interval="10"/> - </tasklet> -</step> -
- -
- Step Restart Configuration Example - - <job id="footballJob" restartable="true"> - <step id="playerload" next="gameLoad"> - <tasklet> - <chunk reader="playerFileItemReader" writer="playerWriter" - commit-interval="10" /> - </tasklet> - </step> - <step id="gameLoad" next="playerSummarization"> - <tasklet allow-start-if-complete="true"> - <chunk reader="gameFileItemReader" writer="gameWriter" - commit-interval="10"/> - </tasklet> - </step> - <step id="playerSummarization"> - <tasklet start-limit="3"> - <chunk reader="playerSummarizationSource" writer="summaryWriter" - commit-interval="10"/> - </tasklet> - </step> -</job> - - The above example configuration is for a job that loads in - information about football games and summarizes them. It contains - three steps: playerLoad, gameLoad, and playerSummarization. The - playerLoad Step loads player information from a - flat file, while the gameLoad Step does the - same for games. The final Step, - playerSummarization, then summarizes the statistics for each player - based upon the provided games. It is assumed that the file loaded by - 'playerLoad' must be loaded only once, but that 'gameLoad' will load - any games found within a particular directory, deleting them after - they have been successfully loaded into the database. As a result, the - playerLoad Step contains no additional - configuration. It can be started almost limitlessly, and if complete - will be skipped. The 'gameLoad' Step, however, - needs to be run every time in case extra files have been dropped since - it last executed. It has 'allow-start-if-complete' set to 'true' in - order to always be started. (It is assumed that the database tables - games are loaded into has a process indicator on it, to ensure new - games can be properly found by the summarization step). The - summarization Step, which is the most important - in the Job, is configured to have a start limit - of 3. This is useful because if the step continually fails, a new exit - code will be returned to the operators that control job execution, and - it won't be allowed to start again until manual intervention has taken - place. - - - This job is purely for example purposes and is not the same as - the footballJob found in the samples project. - - - Run 1: - - - - playerLoad is executed and completes successfully, adding - 400 players to the 'PLAYERS' table. - - - - gameLoad is executed and processes 11 files worth of game - data, loading their contents into the 'GAMES' table. - - - - playerSummarization begins processing and fails after 5 - minutes. - - - - Run 2: - - - - playerLoad is not run, since it has already completed - successfully, and allow-start-if-complete is 'false' (the - default). - - - - gameLoad is executed again and processes another 2 files, - loading their contents into the 'GAMES' table as well (with a - process indicator indicating they have yet to be processed) - - - - playerSummarization begins processing of all remaining game - data (filtering using the process indicator) and fails again after - 30 minutes. - - - - Run 3: - - - - playerLoad is not run, since it has already completed - successfully, and allow-start-if-complete is 'false' (the - default). - - - - gameLoad is executed again and processes another 2 files, - loading their contents into the 'GAMES' table as well (with a - process indicator indicating they have yet to be processed) - - - - playerSummarization is not start, and the job is immediately - killed, since this is the third execution of playerSummarization, - and its limit is only 2. The limit must either be raised, or the - Job must be executed as a new - JobInstance. - - -
-
- -
- Configuring Skip Logic - - There are many scenarios where errors encountered while processing - should not result in Step failure, but should be - skipped instead. This is usually a decision that must be made by someone - who understands the data itself and what meaning it has. Financial data, - for example, may not be skippable because it results in money being - transferred, which needs to be completely accurate. Loading a list of - vendors, on the other hand, might allow for skips. If a vendor is not - loaded because it was formatted incorrectly or was missing necessary - information, then there probably won't be issues. Usually these bad - records are logged as well, which will be covered later when discussing - listeners. - - <step id="step1"> - <tasklet> - <chunk reader="flatFileItemReader" writer="itemWriter" - commit-interval="10" skip-limit="10"> - <skippable-exception-classes> - <include class="org.springframework.batch.item.file.FlatFileParseException"/> - </skippable-exception-classes> - </chunk> - </tasklet> -</step> - - In this example, a FlatFileItemReader is - used, and if at any point a - FlatFileParseException is thrown, it will be - skipped and counted against the total skip limit of 10. Separate counts - are made of skips on read, process and write inside the step execution, - and the limit applies across all. Once the skip limit is reached, the - next exception found will cause the step to fail. - - One problem with the example above is that any other exception - besides a FlatFileParseException will cause the - Job to fail. In certain scenarios this may be the - correct behavior. However, in other scenarios it may be easier to - identify which exceptions should cause failure and skip everything - else: - - <step id="step1"> - <tasklet> - <chunk reader="flatFileItemReader" writer="itemWriter" - commit-interval="10" skip-limit="10"> - <skippable-exception-classes> - <include class="java.lang.Exception"/> - <exclude class="java.io.FileNotFoundException"/> - </skippable-exception-classes> - </chunk> - </tasklet> -</step> - - By 'including' java.lang.Exception as a - skippable exception class, the configuration indicates that all - Exceptions are skippable. However, by 'excluding' - java.io.FileNotFoundException, the configuration - refines the list of skippable exception classes to be all - Exceptions except - FileNotFoundException. Any excluded exception - classes will be fatal if encountered (i.e. not skipped). - - For any exception encountered, the skippability will be determined - by the nearest superclass in the class hierarchy. Any unclassifed - exception will be treated as 'fatal'. The order of the - <include/> and <exclude/> elements - does not matter. -
- -
- Configuring Retry Logic - - In most cases you want an exception to cause either a skip or - Step failure. However, not all exceptions are - deterministic. If a FlatFileParseException is - encountered while reading, it will always be thrown for that record; - resetting the ItemReader will not help. However, - for other exceptions, such as a - DeadlockLoserDataAccessException, which indicates - that the current process has attempted to update a record that another - process holds a lock on, waiting and trying again might result in - success. In this case, retry should be configured: - - <step id="step1"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter" - commit-interval="2" retry-limit="3"> - <retryable-exception-classes> - <include class="org.springframework.dao.DeadlockLoserDataAccessException"/> - </retryable-exception-classes> - </chunk> - </tasklet> -</step> - - The Step allows a limit for the number of - times an individual item can be retried, and a list of exceptions that - are 'retryable'. More details on how retry works can be found in . -
- -
- Controlling Rollback - - By default, regardless of retry or skip, any exceptions thrown - from the ItemWriter will cause the transaction - controlled by the Step to rollback. If skip is - configured as described above, exceptions thrown from the - ItemReader will not cause a rollback. However, - there are many scenarios in which exceptions thrown from the - ItemWriter should not cause a rollback because no - action has taken place to invalidate the transaction. For this reason, - the Step can be configured with a list of - exceptions that should not cause rollback. - - <step id="step1"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter" commit-interval="2"/> - <no-rollback-exception-classes> - <include class="org.springframework.batch.item.validator.ValidationException"/> - </no-rollback-exception-classes> - </tasklet> -</step> - -
- Transactional Readers - - The basic contract of the ItemReader is - that it is forward only. The step buffers reader input, so that in the - case of a rollback the items don't need to be re-read from the reader. - However, there are certain scenarios in which the reader is built on - top of a transactional resource, such as a JMS queue. In this case, - since the queue is tied to the transaction that is rolled back, the - messages that have been pulled from the queue will be put back on. For - this reason, the step can be configured to not buffer the - items: - - <step id="step1"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter" commit-interval="2" - is-reader-transactional-queue="true"/> - </tasklet> -</step> -
-
- -
- Transaction Attributes - - Transaction attributes can be used to control the isolation, - propagation, and timeout settings. More information on setting - transaction attributes can be found in the spring core - documentation. - - <step id="step1"> - <tasklet> - <chunk reader="itemReader" writer="itemWriter" commit-interval="2"/> - <transaction-attributes isolation="DEFAULT" - propagation="REQUIRED" - timeout="30"/> - </tasklet> -</step> -
- -
- Registering ItemStreams with the Step - - The step has to take care of ItemStream - callbacks at the necessary points in its lifecycle. (for more - information on the ItemStream interface, please - refer to ) This is vital if a step fails, - and might need to be restarted, because the - ItemStream interface is where the step gets the - information it needs about persistent state between executions. - - If the ItemReader, - ItemProcessor, or - ItemWriter itself implements the - ItemStream interface, then these will be - registered automatically. Any other streams need to be registered - separately. This is often the case where there are indirect dependencies - such as delegates being injected into the reader and writer. A stream - can be registered on the Step through the - 'streams' element, as illustrated below: - - <step id="step1"> - <tasklet> - <chunk reader="itemReader" writer="compositeWriter" commit-interval="2"> - <streams> - <stream ref="fileItemWriter1"/> - <stream ref="fileItemWriter2"/> - </streams> - </chunk> - </tasklet> -</step> - -<beans:bean id="compositeWriter" - class="org.springframework.batch.item.support.CompositeItemWriter"> - <beans:property name="delegates"> - <beans:list> - <beans:ref bean="fileItemWriter1" /> - <beans:ref bean="fileItemWriter2" /> - </beans:list> - </beans:property> -</beans:bean> - - In the example above, the - CompositeItemWriter is not an - ItemStream, but both of its delegates are. - Therefore, both delegate writers must be explicitly registered as - streams in order for the framework to handle them correctly. The - ItemReader does not need to be explicitly - registered as a stream because it is a direct property of the - Step. The step will now be restartable and the - state of the reader and writer will be correctly persisted in the event - of a failure. -
- -
- Intercepting Step Execution - - Just as with the Job, there are many events - during the execution of a Step where a user may - need to perform some functionality. For example, in order to write out - to a flat file that requires a footer, the - ItemWriter needs to be notified when the - Step has been completed, so that the footer can - written. This can be accomplished with one of many - Step scoped listeners. - - Any class that implements one of the extensions - of StepListener (but not that interface - itself since it is empty) can be applied to a step via the - listeners element. The listeners element is valid inside a - step, tasklet or chunk declaration. It is recommended that you - declare the listeners at the level which its function applies, - or if it is multi-featured - (e.g. StepExecutionListener - and ItemReadListener) then declare it at - the most granular level that it applies (chunk in the example - given). - - <step id="step1"> - <tasklet> - <chunk reader="reader" writer="writer" commit-interval="10"/> - <listeners> - <listener ref="chunkListener"/> - </listeners> - </tasklet> -</step> - - An ItemReader, - ItemWriter or - ItemProcessor that itself implements one of the - StepListener interfaces will be registered - automatically with the Step if using the - namespace <step> element, or one of the the - *StepFactoryBean factories. This only applies to - components directly injected into the Step: if - the listener is nested inside another component, it needs to be - explicitly registered (as described above). - - In addition to the StepListener interfaces, - annotations are provided to address the same concerns. Plain old Java - objects can have methods with these annotations that are then converted - into the corresponding StepListener type. It is - also common to annotate custom implementations of chunk components like - ItemReader or ItemWriter - or Tasklet. The annotations are analysed by the - XML parser for the <listener/> elements, so all you - need to do is use the XML namespace to register the listeners with a - step. - -
- StepExecutionListener - - StepExecutionListener represents the most - generic listener for Step execution. It allows - for notification before a Step is started and - after it has ends, whether it ended normally or failed: - - public interface StepExecutionListener extends StepListener { - - void beforeStep(StepExecution stepExecution); - - ExitStatus afterStep(StepExecution stepExecution); - -} - - ExitStatus is the return type of - afterStep in order to allow listeners the - chance to modify the exit code that is returned upon completion of a - Step. - - The annotations corresponding to this interface are: - - - - @BeforeStep - - - - @AfterStep - - -
- -
- ChunkListener - - A chunk is defined as the items processed within the scope of a - transaction. Committing a transaction, at each commit interval, - commits a 'chunk'. A ChunkListener can be - useful to perform logic before a chunk begins processing or after a - chunk has completed successfully: - - public interface ChunkListener extends StepListener { - - void beforeChunk(); - void afterChunk(); - -} - - The beforeChunk method is called after - the transaction is started, but before read - is called on the ItemReader. Conversely, - afterChunk is called after the chunk has been - committed (and not at all if there is a rollback). - - The annotations corresponding to this interface are: - - - - @BeforeChunk - - - - @AfterChunk - - - - A ChunkListener can be applied - when there is no chunk declaration: it is - the TaskletStep that is responsible for - calling the ChunkListener so it applies - to a non-item-oriented tasklet as well (called before and - after the tasklet). - -
- -
- ItemReadListener - - When discussing skip logic above, it was mentioned that it may - be beneficial to log the skipped records, so that they can be deal - with later. In the case of read errors, this can be done with an - ItemReaderListener: - - public interface ItemReadListener<T> extends StepListener { - - void beforeRead(); - void afterRead(T item); - void onReadError(Exception ex); - -} - - The beforeRead method will be called - before each call to read on the - ItemReader. The - afterRead method will be called after each - successful call to read, and will be passed - the item that was read. If there was an error while reading, the - onReadError method will be called. The - exception encountered will be provided so that it can be - logged. - - The annotations corresponding to this interface are: - - - - @BeforeRead - - - - @AfterRead - - - - @OnReadError - - -
- -
- ItemProcessListener - - Just as with the ItemReadListener, the - processing of an item can be 'listened' to: - - public interface ItemProcessListener<T, S> extends StepListener { - - void beforeProcess(T item); - void afterProcess(T item, S result); - void onProcessError(T item, Exception e); - -} - - The beforeProcess method will be called - before process on the - ItemProcessor, and is handed the item that will - be processed. The afterProcess method will be - called after the item has been successfully processed. If there was an - error while processing, the onProcessError - method will be called. The exception encountered and the item that was - attempted to be processed will be provided, so that they can be - logged. - - The annotations corresponding to this interface are: - - - - @BeforeProcess - - - - @AfterProcess - - - - @OnProcessError - - -
- -
- ItemWriteListener - - The writing of an item can be 'listened' to with the - ItemWriteListener: - - public interface ItemWriteListener<S> extends StepListener { - - void beforeWrite(List<? extends S> items); - void afterWrite(List<? extends S> items); - void onWriteError(Exception exception, List<? extends S> items); - -} - - The beforeWrite method will be called - before write on the - ItemWriter, and is handed the item that will be - written. The afterWrite method will be called - after the item has been successfully written. If there was an error - while writing, the onWriteError method will - be called. The exception encountered and the item that was attempted - to be written will be provided, so that they can be logged. - - The annotations corresponding to this interface are: - - - - @BeforeWrite - - - - @AfterWrite - - - - @OnWriteError - - -
- -
- SkipListener - - ItemReadListener, - ItemProcessListener, and - ItemWriteListner all provide mechanisms for - being notified of errors, but none will inform you that a record has - actually been skipped. onWriteError, for - example, will be called even if an item is retried and successful. For - this reason, there is a separate interface for tracking skipped - items: - - public interface SkipListener<T,S> extends StepListener { - - void onSkipInRead(Throwable t); - void onSkipInProcess(T item, Throwable t); - void onSkipInWrite(S item, Throwable t); - -} - - onSkipInRead will be called whenever an - item is skipped while reading. It should be noted that rollbacks may - cause the same item to be registered as skipped more than once. - onSkipInWrite will be called when an item is - skipped while writing. Because the item has been read successfully - (and not skipped), it is also provided the item itself as an - argument. - - The annotations corresponding to this interface are: - - - - @OnSkipInRead - - - - @OnSkipInWrite - - - - @OnSkipInProcess - - - -
- SkipListeners and Transactions - - One of the most common use cases for a - SkipListener is to log out a skipped item, so - that another batch process or even human process can be used to - evaluate and fix the issue leading to the skip. Because there are - many cases in which the original transaction may be rolled back, - Spring Batch makes two guarantees: - - - - The appropriate skip method (depending on when the error - happened) will only be called once per item. - - - - The SkipListener will always be - called just before the transaction is committed. This is to - ensure that any transactional resources call by the listener are - not rolled back by a failure within the - ItemWriter. - - -
-
-
-
- -
- TaskletStep - - Chunk-oriented processing is not the only way to process in a - Step. What if a Step must - consist as a simple stored procedure call? You could implement the call as - an ItemReader and return null after the procedure - finishes, but it is a bit unnatural since there would need to be a no-op - ItemWriter. Spring Batch provides the - TaskletStep for this scenario. - - The Tasklet is a simple interface that has - one method, execute, which will be a called - repeatedly by the TaskletStep until it either - returns RepeatStatus.FINISHED or throws an exception to - signal a failure. Each call to the Tasklet is - wrapped in a transaction. Tasklet implementors - might call a stored procedure, a script, or a simple SQL update statement. - To create a TaskletStep, the 'ref' attribute of the - <tasklet/> element should reference a bean defining a - Tasklet object; no <chunk/> element should be - used within the <tasklet/>: - - <step id="step1"> - <tasklet ref="myTasklet"/> -</step> - - - TaskletStep will automatically register the - tasklet as StepListener if it implements this - interface - - -
- TaskletAdapter - - As with other adapters for the ItemReader - and ItemWriter interfaces, the - Tasklet interface contains an implementation that - allows for adapting itself to any pre-existing class: - TaskletAdapter. An example where this may be - useful is an existing DAO that is used to update a flag on a set of - records. The TaskletAdapter can be used to call - this class without having to write an adapter for the - Tasklet interface: - - <bean id="myTasklet" class="o.s.b.core.step.tasklet.MethodInvokingTaskletAdapter"> - <property name="targetObject"> - <bean class="org.mycompany.FooDao"/> - </property> - <property name="targetMethod" value="updateFoo" /> -</bean> -
- -
- Example Tasklet Implementation - - Many batch jobs contain steps that must be done before the main - processing begins in order to set up various resources or after - processing has completed to cleanup those resources. In the case of a - job that works heavily with files, it is often necessary to delete - certain files locally after they have been uploaded successfully to - another location. The example below taken from the Spring Batch samples - project, is a Tasklet implementation with just - such a responsibility: - - public class FileDeletingTasklet implements Tasklet, InitializingBean { - - private Resource directory; - - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - File dir = directory.getFile(); - Assert.state(dir.isDirectory()); - - File[] files = dir.listFiles(); - for (int i = 0; i < files.length; i++) { - boolean deleted = files[i].delete(); - if (!deleted) { - throw new UnexpectedJobExecutionException("Could not delete file " + - files[i].getPath()); - } - } - return RepeatStatus.FINISHED; - } - - public void setDirectoryResource(Resource directory) { - this.directory = directory; - } - - public void afterPropertiesSet() throws Exception { - Assert.notNull(directory, "directory must be set"); - } -} - - The above Tasklet implementation will - delete all files within a given directory. It should be noted that the - execute method will only be called once. All - that is left is to reference the Tasklet from the - Step: - - <job id="taskletJob"> - <step id="deleteFilesInDir"> - <tasklet ref="fileDeletingTasklet"/> - </step> -</job> - -<beans:bean id="fileDeletingTasklet" - class="org.springframework.batch.sample.tasklet.FileDeletingTasklet"> - <beans:property name="directoryResource"> - <beans:bean id="directory" - class="org.springframework.core.io.FileSystemResource"> - <beans:constructor-arg value="target/test-outputs/test-dir" /> - </beans:bean> - </beans:property> -</beans:bean> -
-
- -
- Controlling Step Flow - - With the ability to group steps together within an owning job comes - the need to be able to control how the job 'flows' from one step to - another. The failure of a Step doesn't necessarily - mean that the Job should fail. Furthermore, there - may be more than one type of 'success' which determines which - Step should be executed next. Depending upon how a - group of Steps is configured, certain steps may not even be processed at - all. - -
- Sequential Flow - - The simplest flow scenario is a job where all of the steps execute - sequentially: - - - - - - - - - - - - This can be achieved using the 'next' attribute of the step - element: - - <job id="job"> - <step id="stepA" parent="s1" next="stepB" /> - <step id="stepB" parent="s2" next="stepC"/> - <step id="stepC" parent="s3" /> -</job> - - In the scenario above, 'step A' will execute - first because it is the first Step listed. If - 'step A' completes normally, then 'step B' will execute, and so on. - However, if 'step A' fails, then the entire Job - will fail and 'step B' will not execute. - - - With the Spring Batch namespace, the first step listed in the - configuration will always be the first step - executed by the Job. The order of the other - step elements does not matter, but the first step must always appear - first in the xml. - -
- -
- Conditional Flow - - In the example above, there are only two possibilities: - - - - The Step is successful and the next - Step should be executed. - - - - The Step failed and thus the - Job should fail. - - - - In many cases, this may be sufficient. However, what about a - scenario in which the failure of a Step should - trigger a different Step, rather than causing - failure? - - - - - - - - - - In order to handle more complex scenarios, the - Spring Batch namespace allows transition elements to be defined within - the step element. One such transition is the "next" element. Like the - "next" attribute, the "next" element will tell the - Job which Step to execute - next. However, unlike the attribute, any number of "next" elements are - allowed on a given Step, and there is no default - behavior the case of failure. This means that if transition elements are - used, then all of the behavior for the Step's - transitions must be defined explicitly. Note also that a single step - cannot have both a "next" attribute and a transition element. - - The next element specifies a pattern to match and the step to - execute next: - - <job id="job"> - <step id="stepA" parent="s1"> - <next on="*" to="stepB" /> - <next on="FAILED" to="stepC" /> - </step> - <step id="stepB" parent="s2" next="stepC" /> - <step id="stepC" parent="s3" /> -</job> - - The "on" attribute of a transition element uses a simple - pattern-matching scheme to match the ExitStatus - that results from the execution of the Step. Only - two special characters are allowed in the pattern: - - - - "*" will zero or more characters - - - - "?" will match exactly one character - - - - For example, "c*t" will match "cat" and "count", while "c?t" will - match "cat" but not "count". - - While there is no limit to the number of transition elements on a - Step, if the Step's - execution results in an ExitStatus that is not - covered by an element, then the framework will throw an exception and - the Job will fail. The framework will - automatically order transitions from most specific to - least specific. This means that even if the elements were swapped for - "stepA" in the example above, an ExitStatus of - "FAILED" would still go to "stepC". - -
- Batch Status vs. Exit Status - - When configuring a Job for conditional - flow, it is important to understand the difference between - BatchStatus and - ExitStatus. BatchStatus - is an enumeration that is a property of both - JobExecution and - StepExecution and is used by the framework to - record the status of a Job or - Step. It can be one of the following values: - COMPLETED, STARTING, STARTED, STOPPING, STOPPED, FAILED, ABANDONED or - UNKNOWN. Most of them are self explanatory: COMPLETED is the status - set when a step or job has completed successfully, FAILED is set when - it fails, and so on. The example above contains the following 'next' - element: - - <next on="FAILED" to="stepB" /> - - At first glance, it would appear that the 'on' attribute - references the BatchStatus of the - Step to which it belongs. However, it actually - references the ExitStatus of the - Step. As the name implies, - ExitStatus represents the status of a - Step after it finishes execution. More - specifically, the 'next' element above references the exit code of the - ExitStatus. To write it in English, it says: - "go to stepB if the exit code is FAILED". By default, the exit code is - always the same as the BatchStatus for the - Step, which is why the entry above works. However, what if the exit - code needs to be different? A good example comes from the skip sample - job within the samples project: - - <step id="step1" parent="s1"> - <end on="FAILED" /> - <next on="COMPLETED WITH SKIPS" to="errorPrint1" /> - <next on="*" to="step2" /> -</step> - - The above step has three possibilities: - - - - The Step failed, in which case the - job should fail. - - - - The Step completed - successfully. - - - - The Step completed successfully, but - with an exit code of 'COMPLETED WITH SKIPS'. In this case, a - different step should be run to handle the errors. - - - - The above configuration will work. However, something needs to - change the exit code based on the condition of the execution having - skipped records: - - public class SkipCheckingListener extends StepExecutionListenerSupport { - public ExitStatus afterStep(StepExecution stepExecution) { - String exitCode = stepExecution.getExitStatus().getExitCode(); - if (!exitCode.equals(ExitStatus.FAILED.getExitCode()) && - stepExecution.getSkipCount() > 0) { - return new ExitStatus("COMPLETED WITH SKIPS"); - } - else { - return null; - } - } -} - - The above code is a StepExecutionListener - that first checks to make sure the Step was - successful, and next if the skip count on the - StepExecution is higher than 0. If both - conditions are met, a new ExitStatus with an - exit code of "COMPLETED WITH SKIPS" is returned. -
-
- -
- Configuring for Stop - - After the discussion of BatchStatus and - ExitStatus, one might wonder how the - BatchStatus and ExitStatus - are determined for the Job. While these statuses - are determined for the Step by the code that is - executed, the statuses for the Job will be - determined based on the configuration. - - So far, all of the job configurations discussed have had at least - one final Step with no transitions. For example, - after the following step executes, the Job will - end: - - <step id="stepC" parent="s3"/> - - If no transitions are defined for a Step, - then the Job's statuses will be defined as - follows: - - - - If the Step ends with - ExitStatus FAILED, then the - Job's BatchStatus and - ExitStatus will both be FAILED. - - - - Otherwise, the Job's - BatchStatus and - ExitStatus will both be COMPLETED. - - - - While this method of terminating a batch job is sufficient for - some batch jobs, such as a simple sequential step job, custom defined - job-stopping scenarios may be required. For this purpose, Spring Batch - provides three transition elements to stop a Job - (in addition to the "next" element - that we discussed previously). Each of these stopping elements will stop - a Job with a particular - BatchStatus. It is important to note that the - stop transition elements will have no effect on either the - BatchStatus or ExitStatus - of any Steps in the Job: - these elements will only affect the final statuses of the - Job. For example, it is possible for every step - in a job to have a status of FAILED but the job to have a status of - COMPLETED, or vise versa. - -
- The 'End' Element - - The 'end' element instructs a Job to stop - with a BatchStatus of COMPLETED. A - Job that has finished with status COMPLETED - cannot be restarted (the framework will throw a - JobInstanceAlreadyCompleteException). The 'end' - element also allows for an optional 'exit-code' attribute that can be - used to customize the ExitStatus of the - Job. If no 'exit-code' attribute is given, then - the ExitStatus will be "COMPLETED" by default, - to match the BatchStatus. - - In the following scenario, if step2 fails, then the - Job will stop with a - BatchStatus of COMPLETED and an - ExitStatus of "COMPLETED" and step3 will not - execute; otherwise, execution will move to step3. Note that if step2 - fails, the Job will not be restartable (because - the status is COMPLETED). - - <step id="step1" parent="s1" next="step2"> - -<step id="step2" parent="s2"> - <end on="FAILED"/> - <next on="*" to="step3"/> -</step> - -<step id="step3" parent="s3"> -
- -
- The 'Fail' Element - - The 'fail' element instructs a Job to - stop with a BatchStatus of FAILED. Unlike the - 'end' element, the 'fail' element will not prevent the - Job from being restarted. The 'fail' element - also allows for an optional 'exit-code' attribute that can be used to - customize the ExitStatus of the - Job. If no 'exit-code' attribute is given, then - the ExitStatus will be "FAILED" by default, to - match the BatchStatus. - - In the following scenario, if step2 fails, then the - Job will stop with a - BatchStatus of FAILED and an - ExitStatus of "EARLY TERMINATION" and step3 - will not execute; otherwise, execution will move to step3. - Additionally, if step2 fails, and the Job is - restarted, then execution will begin again on step2. - - <step id="step1" parent="s1" next="step2"> - -<step id="step2" parent="s2"> - <fail on="FAILED" exit-code="EARLY TERMINATION"/> - <next on="*" to="step3"/> -</step> - -<step id="step3" parent="s3"> -
- -
- The 'Stop' Element - - The 'stop' element instructs a Job to - stop with a BatchStatus of STOPPED. Stopping a - Job can provide a temporary break in processing - so that the operator can take some action before restarting the - Job. The 'stop' element requires a 'restart' - attribute that specifies the step where execution should pick up when - the Job is restarted. - - In the following scenario, if step1 finishes with COMPLETE, then - the job will then stop. Once it is restarted, execution will begin on - step2. - - <step id="step1" parent="s1"> - <stop on="COMPLETED" restart="step2"/> -</step> - -<step id="step2" parent="s2"/> -
-
- -
- Programmatic Flow Decisions - - In some situations, more information than the - ExitStatus may be required to decide which step - to execute next. In this case, a - JobExecutionDecider can be used to assist in the - decision. - - public class MyDecider implements JobExecutionDecider { - public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { - if (someCondition) { - return "FAILED"; - } - else { - return "COMPLETED"; - } - } -} - - In the job configuration, a "decision" tag will specify the - decider to use as well as all of the transitions. - - <job id="job"> - <step id="step1" parent="s1" next="decision" /> - - <decision id="decision" decider="decider"> - <next on="FAILED" to="step2" /> - <next on="COMPLETED" to="step3" /> - </decision> - - <step id="step2" parent="s2" next="step3"/> - <step id="step3" parent="s3" /> -</job> - -<beans:bean id="decider" class="com.MyDecider"/> -
- -
- Split Flows - - Every scenario described so far has involved a - Job that executes its - Steps one at a time in a linear fashion. In - addition to this typical style, the Spring Batch namespace also allows - for a job to be configured with parallel flows using the 'split' - element. As is seen below, the 'split' element contains one or more - 'flow' elements, where entire separate flows can be defined. A 'split' - element may also contain any of the previously discussed transition - elements such as the 'next' attribute or the 'next', 'end', 'fail', or - 'pause' elements. - - <split id="split1" next="step4"> - <flow> - <step id="step1" parent="s1" next="step2"/> - <step id="step2" parent="s2"/> - </flow> - <flow> - <step id="step3" parent="s3"/> - </flow> -</split> -<step id="step4" parent="s4"/> -
- -
- Externalizing Flow Definitions and Dependencies Between - Jobs - - Part of the flow in a job can be externalized as a separate bean - definition, and then re-used. There are two ways to do this, and the - first is to simply declare the flow as a reference to one defined - elsewhere: - - <job id="job"> - <flow id="job1.flow1" parent="flow1" next="step3"/> - <step id="step3" parent="s3"/> -</job> - -<flow id="flow1"> - <step id="step1" parent="s1" next="step2"/> - <step id="step2" parent="s2"/> -</flow> - - The effect of defining an external flow like this is simply to - insert the steps from the external flow into the job as if they had been - declared inline. In this way many jobs can refer to the same template - flow and compose such templates into different logical flows. This is - also a good way to separate the integration testing of the individual - flows. - - The other form of an externalized flow is to use a - JobStep. A JobStep is - similar to a FlowStep, but actually creates and - launches a separate job execution for the steps in the flow specified. - Here is an example: - - <job id="jobStepJob" restartable="true"> - <step id="jobStepJob.step1"> - <job ref="job" job-launcher="jobLauncher" - job-parameters-extractor="jobParametersExtractor"/> - </step> -</job> - -<job id="job" restartable="true">...</job> - -<bean id="jobParametersExtractor" class="org.spr...DefaultJobParametersExtractor"> - <property name="keys" value="input.file"/> -</bean> - - The job parameters extractor is a strategy that determines how a - the ExecutionContext for the - Step is converted into - JobParameters for the Job that is executed. The - JobStep is useful when you want to have some more - granular options for monitoring and reporting on jobs and steps. Using - JobStep is also often a good answer to the - question: "How do I create dependencies between jobs?". It is a good way - to break up a large system into smaller modules and control the flow of - jobs. -
-
- -
- Late Binding of Job and Step Attributes - - Both the XML and Flat File examples above use the Spring - Resource abstraction to obtain a file. This works - because Resource has a getFile - method, which returns a java.io.File. Both XML and - Flat File resources can be configured using standard Spring - constructs: - - <bean id="flatFileItemReader" - class="org.springframework.batch.item.file.FlatFileItemReader"> - <property name="resource" - value="file://outputs/20070122.testStream.CustomerReportStep.TEMP.txt" /> -</bean> - - The above Resource will load the file from - the file system location specified. Note that absolute locations have to - start with a double slash ("//"). In most spring applications, this - solution is good enough because the names of these are known at compile - time. However, in batch scenarios, the file name may need to be determined - at runtime as a parameter to the job. This could be solved using '-D' - parameters, i.e. a system property: - - <bean id="flatFileItemReader" - class="org.springframework.batch.item.file.FlatFileItemReader"> - <property name="resource" value="${input.file.name}" /> -</bean> - - All that would be required for this solution to work would be a - system argument (-Dinput.file.name="file://file.txt"). (Note that although - a PropertyPlaceholderConfigurer can be used here, - it is not necessary if the system property is always set because the - ResourceEditor in Spring already filters and does - placeholder replacement on system properties.) - - Often in a batch setting it is preferable to parameterize the file - name in the JobParameters of the - job, instead of through system properties, and access them that way. To - accomplish this, Spring Batch allows for the late binding of various Job - and Step attributes: - - <bean id="flatFileItemReader" scope="step" - class="org.springframework.batch.item.file.FlatFileItemReader"> - <property name="resource" value="#{jobParameters['input.file.name']}" /> -</bean> - - Both the JobExecution and - StepExecution level - ExecutionContext can be accessed in the same - way: - - <bean id="flatFileItemReader" scope="step" - class="org.springframework.batch.item.file.FlatFileItemReader"> - <property name="resource" value="#{jobExecutionContext['input.file.name']}" /> -</bean> - - <bean id="flatFileItemReader" scope="step" - class="org.springframework.batch.item.file.FlatFileItemReader"> - <property name="resource" value="#{stepExecutionContext['input.file.name']}" /> -</bean> - - - Any bean that uses late-binding must be declared with - scope="step". See for more - information. - - - - If you are using Spring 3.0 (or above) the expressions in - step-scoped beans are in the Spring Expression Language, a powerful - general purpose language with many interesting features. To provide - backward compatibility, if Spring Batch detects the presence of older - versions of Spring it uses a native expression language that is less - powerful, and has slightly different parsing rules. The main difference - is that the map keys in the example above do not need to be quoted with - Spring 2.5, but the quotes are mandatory in Spring 3.0. - - -
- Step Scope - - All of the late binding examples from above have a scope of "step" - declared on the bean definition: - - <bean id="flatFileItemReader" scope="step" - class="org.springframework.batch.item.file.FlatFileItemReader"> - <property name="resource" value="#{jobParameters[input.file.name]}" /> -</bean> - - Using a scope of Step is required in order - to use late binding since the bean cannot actually be instantiated until - the Step starts, which allows the attributes to - be found. Because it is not part of the Spring container by default, the - scope must be added explicitly, either by using the - batch namespace: - - <beans xmlns="http://www.springframework.org/schema/beans" - xmlns:batch="http://www.springframework.org/schema/batch" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="..."> -<batch:job .../> -... -</beans> - - or by including a bean definition explicitly for the - StepScope (but not both): - - <bean class="org.springframework.batch.core.scope.StepScope" /> -
- -
- Job Scope - - Job scope, introduced in Spring Batch 3.0 is similar to Step scope - in configuration but is a Scope for the Job context so there is only one - instance of such a bean per executing job. Additionally, support is provided - for late binding of references accessible from the JobContext using - #{..} placeholders. Using this feature, bean properties can be pulled from - the job or job execution context and the job parameters. E.g. - - <bean id="..." class="..." scope="job"> - <property name="name" value="#{jobParameters[input]}" /> -</bean> - - <bean id="..." class="..." scope="job"> - <property name="name" value="#{jobExecutionContext['input.name']}.txt" /> -</bean> - - - Because it is not part of the Spring container by default, the scope - must be added explicitly, either by using the batch namespace: - - <beans xmlns="http://www.springframework.org/schema/beans" - xmlns:batch="http://www.springframework.org/schema/batch" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="..."> - - <batch:job .../> - ... - </beans> - - Or by including a bean definition explicitly for the JobScope (but not both): - - <bean class="org.springframework.batch.core.scope.JobScope" /> -
-
-
diff --git a/src/site/docbook/reference/testing.xml b/src/site/docbook/reference/testing.xml deleted file mode 100644 index bb41efae7..000000000 --- a/src/site/docbook/reference/testing.xml +++ /dev/null @@ -1,278 +0,0 @@ - - - - Unit Testing - - Just as with other application styles, it is extremely important to - unit test any code written as part of a batch job as well. The Spring core - documentation covers how to unit and integration test with Spring in great - detail, so it won't be repeated here. It is important, however, to think - about how to 'end to end' test a batch job, which is what this chapter will - focus on. The spring-batch-test project includes classes that will help - facilitate this end-to-end test approach. - -
- Creating a Unit Test Class - - In order for the unit test to run a batch job, the framework must - load the job's ApplicationContext. Two annotations are used to trigger - this: - - - - @RunWith(SpringJUnit4ClassRunner.class): - Indicates that the class should use Spring's JUnit facilities - - - - @ContextConfiguration(locations = {...}): - Indicates which XML files contain the ApplicationContext. - - - - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", - "/jobs/skipSampleJob.xml" }) -public class SkipSampleFunctionalTests { ... } -
- -
- End-To-End Testing of Batch Jobs - - 'End To End' testing can be defined as testing the complete run of a - batch job from beginning to end. This allows for a test that sets up a - test condition, executes the job, and verifies the end result. - - In the example below, the batch job reads from the database and - writes to a flat file. The test method begins by setting up the database - with test data. It clears the CUSTOMER table and then inserts 10 new - records. The test then launches the Job using the - launchJob() method. The - launchJob() method is provided by the - JobLauncherTestUtils class. Also provided by the - utils class is launchJob(JobParameters), which - allows the test to give particular parameters. The - launchJob() method returns the - JobExecution object which is useful for asserting - particular information about the Job run. In the - case below, the test verifies that the Job ended - with status "COMPLETED". - - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", - "/jobs/skipSampleJob.xml" }) -public class SkipSampleFunctionalTests { - - @Autowired - private JobLauncherTestUtils jobLauncherTestUtils; - - private SimpleJdbcTemplate simpleJdbcTemplate; - - @Autowired - public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); - } - - @Test - public void testJob() throws Exception { - simpleJdbcTemplate.update("delete from CUSTOMER"); - for (int i = 1; i <= 10; i++) { - simpleJdbcTemplate.update("insert into CUSTOMER values (?, 0, ?, 100000)", - i, "customer" + i); - } - - JobExecution jobExecution = jobLauncherTestUtils.launchJob().getStatus(); - - - Assert.assertEquals("COMPLETED", jobExecution.getExitStatus()); - } -} -
- -
- Testing Individual Steps - - For complex batch jobs, test cases in the end-to-end testing - approach may become unmanageable. It these cases, it may be more useful to - have test cases to test individual steps on their own. The - AbstractJobTests class contains a method - launchStep that takes a step name and runs just - that particular Step. This approach allows for more - targeted tests by allowing the test to set up data for just that step and - to validate its results directly. - - JobExecution jobExecution = jobLauncherTestUtils.launchStep("loadFileStep"); -
- -
- Testing Step-Scoped Components - - Often the components that are configured for your steps at runtime - use step scope and late binding to inject context from the step or job - execution. These are tricky to test as standalone components unless you - have a way to set the context as if they were in a step execution. That is - the goal of two components in Spring Batch: the - StepScopeTestExecutionListener and the - StepScopeTestUtils. - - The listener is declared at the class level, and its job is to - create a step execution context for each test method. For example: - - @ContextConfiguration -@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, - StepScopeTestExecutionListener.class }) -@RunWith(SpringJUnit4ClassRunner.class) -public class StepScopeTestExecutionListenerIntegrationTests { - - // This component is defined step-scoped, so it cannot be injected unless - // a step is active... - @Autowired - private ItemReader<String> reader; - - public StepExecution getStepExection() { - StepExecution execution = MetaDataInstanceFactory.createStepExecution(); - execution.getExecutionContext().putString("input.data", "foo,bar,spam"); - return execution; - } - - @Test - public void testReader() { - // The reader is initialized and bound to the input data - assertNotNull(reader.read()); - } - -} - - There are two TestExecutionListeners, one - from the regular Spring Test framework and handles dependency injection - from the configured application context, injecting the reader, and the - other is the Spring Batch - StepScopeTestExecutionListener. It works by looking - for a factory method in the test case for a - StepExecution, and using that as the context for - the test method, as if that execution was active in a Step at runtime. The - factory method is detected by its signature (it just has to return a - StepExecution). If a factory method is not provided - then a default StepExecution is created. - - The listener approach is convenient if you want the duration of the - step scope to be the execution of the test method. For a more flexible, - but more invasive approach you can use the - StepScopeTestUtils. For example, to count the - number of items available in the reader above: - - int count = StepScopeTestUtils.doInStepScope(stepExecution, - new Callable<Integer>() { - public Integer call() throws Exception { - - int count = 0; - - while (reader.read() != null) { - count++; - } - return count; - } -}); -
- -
- Validating Output Files - - When a batch job writes to the database, it is easy to query the - database to verify that the output is as expected. However, if the batch - job writes to a file, it is equally important that the output be verified. - Spring Batch provides a class AssertFile to - facilitate the verification of output files. The method - assertFileEquals takes two - File objects (or two - Resource objects) and asserts, line by line, that - the two files have the same content. Therefore, it is possible to create a - file with the expected output and to compare it to the actual - result: - - private static final String EXPECTED_FILE = "src/main/resources/data/input.txt"; -private static final String OUTPUT_FILE = "target/test-outputs/output.txt"; - -AssertFile.assertFileEquals(new FileSystemResource(EXPECTED_FILE), - new FileSystemResource(OUTPUT_FILE)); -
- -
- Mocking Domain Objects - - Another common issue encountered while writing unit and integration - tests for Spring Batch components is how to mock domain objects. A good - example is a StepExecutionListener, as illustrated - below: - - public class NoWorkFoundStepExecutionListener extends StepExecutionListenerSupport { - - public ExitStatus afterStep(StepExecution stepExecution) { - if (stepExecution.getReadCount() == 0) { - throw new NoWorkFoundException("Step has not processed any items"); - } - return stepExecution.getExitStatus(); - } -} - - The above listener is provided by the framework and checks a - StepExecution for an empty read count, thus - signifying that no work was done. While this example is fairly simple, it - serves to illustrate the types of problems that may be encountered when - attempting to unit test classes that implement interfaces requiring Spring - Batch domain objects. Consider the above listener's unit test: - - private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener(); - -@Test -public void testAfterStep() { - StepExecution stepExecution = new StepExecution("NoProcessingStep", - new JobExecution(new JobInstance(1L, new JobParameters(), - "NoProcessingJob"))); - - stepExecution.setReadCount(0); - - try { - tested.afterStep(stepExecution); - fail(); - } catch (NoWorkFoundException e) { - assertEquals("Step has not processed any items", e.getMessage()); - } -} - - Because the Spring Batch domain model follows good object orientated - principles, the StepExecution requires a - JobExecution, which requires a - JobInstance and - JobParameters in order to create a valid - StepExecution. While this is good in a solid domain - model, it does make creating stub objects for unit testing verbose. To - address this issue, the Spring Batch test module includes a factory for - creating domain objects: MetaDataInstanceFactory. - Given this factory, the unit test can be updated to be more - concise: - - private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener(); - -@Test -public void testAfterStep() { - StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(); - - stepExecution.setReadCount(0); - - try { - tested.afterStep(stepExecution); - fail(); - } catch (NoWorkFoundException e) { - assertEquals("Step has not processed any items", e.getMessage()); - } -} - - The above method for creating a simple - StepExecution is just one convenience method - available within the factory. A full method listing can be found in its - Javadoc. -
-
diff --git a/src/site/docbook/reference/whatsnew.xml b/src/site/docbook/reference/whatsnew.xml deleted file mode 100644 index 093a582a0..000000000 --- a/src/site/docbook/reference/whatsnew.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - What's New in Spring Batch 4.0 - - The Spring Batch 4.0 release has three major themes: - - - - Java 8 Requirement - - - - Dependencies re-baseline - - - - Builders for ItemReaders and ItemWriters - - - -
- Java 8 Requirement - - Spring Batch has historically followed Spring Framework's baselines for both - java version as well as third party dependencies. With Spring Batch 4, the Spring - Framework version is being upgraded to Spring Framework 5. As such, the java - version requirement for Spring Batch is also increasing to Java 8. - -
- -
- Dependencies re-baseline - - In order to continue to integrate with supported versions of the third party - libraries Spring Batch utilizes, Spring Batch 4 is updating the dependencies across - the board. The new dependency versions are in alignment with Spring Framework 5. - -
- -
- Provide builders for the ItemReaders and ItemWriters - - Spring Batch 4 is providing a collection of builders for all of the ItemReaders - and ItemWriters that come with the framework. As of this release, builders for the - FlatFileItemReader, FlatFileItemWriter, JdbcCursorItemReader, and - JdbcBatchItemWriter are available. More information can be found in the javadoc - for Spring Batch. -
-
diff --git a/src/site/fml/faq.fml b/src/site/fml/faq.fml deleted file mode 100644 index 6c057ff3d..000000000 --- a/src/site/fml/faq.fml +++ /dev/null @@ -1,325 +0,0 @@ - - - - - - What's the current release and what are the plans for - future releases? - - - You can track the progress and planning in - JIRA - (http://opensource.atlassian.com/projects/spring/browse/BATCH). - - - - - Is it possible to execute jobs in multiple threads or - multiple processes? - - - There are three ways to approach this - but we recommend - exercising - caution in the analysis of - such requirements (is it - really - necessary?). -
    -
  • Add a TaskExecutor to the repeatTemplate used to control - step execution (the outer step operations). The - FactoryBeans - provided for configuring Steps (e.g. - FaultTolerantStepFactoryBean) - have a "taskExecutor" property you - can set. This works as long as - the - step is intrinsically - restartable (idempotent effectively). The - parallel - job sample - shows - how it might work in practice - this - uses a - "process indicator" - pattern to mark input - records as complete, - inside - the business - transaction.
  • -
  • Use the PartitionStep to split your step execution - explicitly amongst several Step instances. Spring Batch - has a - local multi-threaded implementation of the main strategy - for this - (PartitionHandler), - which makes it a great - choice for IO intensive - jobs. Remember to use scope="step" for the stateful components in - a step executing in this - fashion, so that separate instances are - created per step execution, and there is no cross talk between - threads. See - below for more details.
  • -
  • Use the Remote Chunking approach as implemented in the - spring-batch-integration subproject. This requires - some durable - middleware (e.g. JMS) for reliable communication between the - driving step and - the remote workers. The - basic idea is to use a - special ItemWriter on the driving process, and a listener pattern - on the worker processes - (via a ChunkProcessor). See below for more - details.
  • -
-
-
- - How can I make an item reader thread safe - You can synchronize the read() method (e.g. by wrapping it in a delegator that does the synchronization). Remember that you will lose restartability, so best practice is to mark the step as not restartable and to be safe (and efficient) you can also set saveState=false on the reader. - - - - What is the Spring Batch philosophy on the use of - flexible - strategies and default implementations? Can you - add a public getter - for this or that property? - - -

- There are a great many extension points in Spring Batch - for the - framework developer (as opposed to the - implementor of - business - logic). We expect clients to - create their own more specific - strategies that can be - plugged in to control - things like commit - intervals ( - CompletionPolicy - ), rules about how to deal with exceptions ( - ExceptionHandler - ), and many others. -

-

- In general we try to dissuade users from extending framework - classes. - The Java language doesn't give us as much - flexibility to - mark classes and interfaces as internal. Generally you can expect - anything at the top level of the - source tree in packages - org.springframework.batch.* - to be public, but not necessarily sub-classable. Extending our - concrete implementations of most - strategies is - discouraged in favour - of a composition or forking - approach. If your code can use only the - interfaces from Spring - Batch, that gives you the greatest possible - portability. -

-
-
- - - How does Spring Batch differ from Quartz? Is there a - place - for them both in a solution? - - -

- Spring Batch and Quartz have different goals. Spring - Batch provides - functionality for processing large - volumes of data - and Quartz - provides functionality - for scheduling tasks. So Quartz could - complement - Spring Batch, but are not excluding - technologies. A - common combination would be to use Quartz as a - trigger for a Spring - Batch job using a Cron - expression - and the Spring Core convenience - SchedulerFactoryBean - . -

-
-
- - - How do I schedule a job with Spring Batch? - - -

- Use a scheduling tool. There are plenty of them out - there. - Examples: Quartz, Control-M, Autosys. Quartz - doesn't have - all the - features of Control-M or - Autosys - it is supposed to be lightweight. - If you - want something even more - lightweight you can just - use the OS - (cron, at, etc.). -

-

- Simple sequential dependencies can be implemented - using the - job-steps model of Spring Batch, and the non-sequential - features in - Spring Batch 2.0. We think - this is quite common. And - in fact it makes - it easier - to correct a common mis-use - of scehdulers - - having - hundreds - of jobs configured, many of which are not - independent, but only - depend on one other. -

-
-
- - - How does Spring Batch allow project to optimize for - performance and scalability (through parallel processing - or other)? - - - We see this as one of the roles of the Job or Step. - A specific - implementation of the - Step - deals with the concern of breaking apart the business - logic and - sharing it efficiently between parallel - processes or - processors (see - PartitionStep - ). - There are a number of - technologies that could play a role here. The - essence is - just a set of concurrent remote calls - to distributed - agents that can handle some business processing. Since - the business - processing is already typically - modularised - - e.g. input an item, - process it - Spring Batch can - strategise the distribution in a number - of ways. One - implementation that we have had some experience with - is a - set of remote web services - handling the - business processing. - We send a - specific range - of primary keys for - the inputs to each of - a number of - remote calls. The same basic - strategy would - work with - any - of the Spring - Remoting protocols (plain - RMI, - HttpInvoker, JMS, - Hessian etc.) with - little more than a - couple of - lines change in the - execution layer - configuration. - - - - - How can messaging be used to scale batch architectures? - - - There is a good deal of practical evidence from existing - projects - that a pipeline approach to batch processing is - highly beneficial, - leading to resilience and high - throughput. We are often faced with - mission-critical - applications - where audit trails are essential, and - guaranteed processing is demanded, but where there are - extremely - tight limits on - performance under load, or - where high throughput - gives a competitive advantage. - Matt Welsh's work shows that a Staged - Event Driven - Architecture (SEDA) has enormous benefits over more - rigid processing architectures, and message-oriented - middleware (JMS, - AQ, MQ, Tibco etc.) gives us a lot of - resilience out of the box. - There are particular benefits - in a - system where there is feedback - between downstream - and upstream stages, so the number of consumers - can be - adjusted to - account for the amount of demand. So how - does this - fit into Spring Batch? The - spring-batch-integration - project has this pattern implemented in Spring Integration, and can - be used to scale up the remote processing of any - step with many - items to process. See in particular the "chunk" package, and the ItemWriter and ChunkHandler - implementations in there. - - - - How can I contribute to Spring Batch? - - Use the community forum to get involved in discussions - about - the product and its design. There is a process for - contributions and - eventually becoming a committer. The - process is pretty standard for - all Apache-licensed - projects. You - make contributions through JIRA (so - sign - up now); you assign the copyright of any contributions - using a - standard - Apache-like CLA (see the Apache one for - example - ours might - be slightly different); when the - contributions reach a - certain level, - or you convince us - otherwise that you are going to be committed long - term, - even if part time, then you - can become a committer. - - -
-
diff --git a/src/site/ppt/ExecutionEnvironment.ppt b/src/site/ppt/ExecutionEnvironment.ppt deleted file mode 100644 index 70875e745..000000000 Binary files a/src/site/ppt/ExecutionEnvironment.ppt and /dev/null differ diff --git a/src/site/ppt/Figures.ppt b/src/site/ppt/Figures.ppt deleted file mode 100644 index adae980ec..000000000 Binary files a/src/site/ppt/Figures.ppt and /dev/null differ diff --git a/src/site/ppt/RuntimeDependencies.ppt b/src/site/ppt/RuntimeDependencies.ppt deleted file mode 100644 index d0c60d386..000000000 Binary files a/src/site/ppt/RuntimeDependencies.ppt and /dev/null differ diff --git a/src/site/resources/discussion/retry-with-mq.png b/src/site/resources/discussion/retry-with-mq.png deleted file mode 100644 index 82870a460..000000000 Binary files a/src/site/resources/discussion/retry-with-mq.png and /dev/null differ diff --git a/src/site/resources/images/ExecutionEnvironment.png b/src/site/resources/images/ExecutionEnvironment.png deleted file mode 100644 index e574236b3..000000000 Binary files a/src/site/resources/images/ExecutionEnvironment.png and /dev/null differ diff --git a/src/site/resources/images/RuntimeDependencies.png b/src/site/resources/images/RuntimeDependencies.png deleted file mode 100644 index b54c54c98..000000000 Binary files a/src/site/resources/images/RuntimeDependencies.png and /dev/null differ diff --git a/src/site/resources/images/logos/i21-banner-1.jpg b/src/site/resources/images/logos/i21-banner-1.jpg deleted file mode 100644 index c72b017b9..000000000 Binary files a/src/site/resources/images/logos/i21-banner-1.jpg and /dev/null differ diff --git a/src/site/resources/images/partitioned.png b/src/site/resources/images/partitioned.png deleted file mode 100644 index 2451b30e0..000000000 Binary files a/src/site/resources/images/partitioned.png and /dev/null differ diff --git a/src/site/site.xml b/src/site/site.xml deleted file mode 100644 index 1ee966851..000000000 --- a/src/site/site.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - ${project.name} - http://projects.spring.io/spring-batch/ - - - - - images/shim.gif - - - - - - - - - - org.springframework.maven.skins - - maven-spring-skin - 1.0.5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -