diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/jsr/JsrTestUtils.java b/spring-batch-core/src/test/java/org/springframework/batch/core/jsr/JsrTestUtils.java index af7961158..7cb05c067 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/jsr/JsrTestUtils.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/jsr/JsrTestUtils.java @@ -15,15 +15,21 @@ */ package org.springframework.batch.core.jsr; -import java.util.Date; -import java.util.Properties; -import java.util.concurrent.TimeoutException; - import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; +import java.util.Date; +import java.util.Properties; +import java.util.concurrent.TimeoutException; +/** + * Provides testing utilities to execute JSR-352 jobs and block until they are complete (since all JSR-352 based jobs + * are executed asynchronously). + * + * @author Michael Minella + * @since 3.0 + */ public class JsrTestUtils { private static JobOperator operator; diff --git a/src/site/docbook/reference/jsr-352.xml b/src/site/docbook/reference/jsr-352.xml index 1ae89eca9..cde967ecb 100644 --- a/src/site/docbook/reference/jsr-352.xml +++ b/src/site/docbook/reference/jsr-352.xml @@ -1,122 +1,123 @@ - + JSR-352 Support - As of Spring Batch 3.0 support for JSR-352 has been fully implemented. This section will briefly describe high level JSR-352 specific concepts. It is encouraged to read the full JSR-352 spec, located at the JSR-352 home page: https://jcp.org/en/jsr/detail?id=352 + 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 -
- Batch Contexts +
+ General Notes Spring Batch and JSR-352 - JSR-352 Batch Contexts provide information about the batch job and interaction with the batch runtime. Context objects can be injected into fields of batch artifact classes using the @Inject annotation. + 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. +
-
- JobContext +
+ Dependency Injection - The JobContext represents the entire batch job. There is one JobContext per job execution and exists for the life of the Job. -
+ 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. + + -
- StepContext + 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"> - The StepContext represents the current executing step. There is one StepContext per step execution and exists for the life of the Step. -
-
-
- Configuring and Running a Job + <!-- Bean defined that references an implementation of the javax.batch.api.Batchlet interface --> + <bean id="fooBatchlet" class="io.spring.FooBatchlet"> + <property name="prop" value="bar"/> + </bean> -
- Configuring a Job - -
- JSR-352 namespace - - JSR-352 API classes reside in the package namespace of javax.batch. The XML namespace also known as the Job Specification Language (JSL) in the language in which Jobs are defined in. The JSL is represented by an XML schema. Refer to the JSR-352 spec document or the XSD itself for more details. -
-
- batch.xml configuration - - The batch.xml file contains a mapping of batch artifacts to be loaded and used by the runtime. Batch artifact definitions consist of a reference identifier and a fully qualified class name. The batch.xml file resides in the META-INF directory. -
-
- Spring configuration - - In addition to configuring batch artifacts in the batch.xml file, Spring Batch allows you to configure batch artifacts in the typical Spring bean fashion. To utilize this configuration method simply define your JSR-352 job inside a Spring configuration file and reference your Spring beans via the ref tag as shown in the snippet below. - - <?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"> - - <job id="job1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0"> - <step id="step1"> - <chunk> - <reader ref="testReader"/> - </chunk> - </step> - ... + <!-- 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> + - <bean id="testReader" class="TestItemReader" scope="step"/> -</beans> -
-
-
- Running a Job + 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/ -
- JsrJobOperator + 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> + - The JsrJobOperator is a javax.batch.operations.JobOperator implementation which supports various operations for dealing with batch jobs. Job XML files are expected to reside in the META-INF/batch-jobs directory. +
- Typically used JobOperator methods for operating a job include: +
+ Batch Properties - - start(String jobXMLName, Properties jobParameters) -restart(long executionId, Properties restartParameters) -stop(long executionId) -abandon(long executionId) +
+ Property Support - When providing the jobXMLname to the start method of JobOperator, the META-INF/batch-jobs prefix nor the .xml file extension should be added. -
-
-
- Intercepting Job Execution + 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: -
- JobListener - - As with Spring Batch, JSR-352 allows for Job level listeners. Job listeners are configured as a child element of the Job in the JSL and implement the javax.batch.api.listener.JobListener interface. -
-
-
-
- Job 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> + <property name="propertyName1" value="propertyValue1"/> + <property name="propertyName2" value="propertyValue2"/> </properties> - Properties may be configured on any batch artifact. -
-
- @BatchProperty annotation + 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. As defined by JSR-352, fields for properties must be String typed. Any type conversion is up to the implementing developer to perform. + 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 ItemReader artifact could be configured with a properties block such as the one described above and accessed as such: - public class MyItemReader implements ItemReader { + 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; @@ -124,245 +125,338 @@ abandon(long executionId) ... } - The value of the field "propertyName1" will be "propertyValue1" -
-
- Property Substitution + 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 parition 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 ';'. - -
-
-
- Retry + 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 + ';'. + +
+
- JSR-352 provides support for retry by way of listeners for chunk level artifacts. Listeners are configured at the step level contained in a listeners block. +
+ Processing Models -
- Retry Listeners + 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. + + + - JSR-352 provides listener interfaces for various cases of retry handling: - - - - - - - - - Artifact Interface - - - Listener Interface - - - - javax.batch.api.chunk.ItemReader - javax.batch.api.chunk.listener.RetryReadListener - - - javax.batch.api.chunk.ItemProcessor - javax.batch.api.chunk.listener.RetryProcessListener - - - javax.batch.api.chunk.ItemWriter - javax.batch.api.chunk.listener.RetryWriteListener - - - - -
-
-
- Configuring a Step - -
- Batchlet - - Task oriented step's in the JSR-352 implementation are backed by implementations of javax.batch.api.Batchlet. A Batchlet is analogous to a Spring Batch Tasklet. -
-
- Controlling Step Flow - -
- Decider - - JSR-352 decision support for steps, splits and flows are implemented via implementations of the javax.batch.api.Decider interface. -
-
- Conditional Flow - - JSR-352 allows for both the next attribute and a next element to be present as transition elements. If both are present, the next value specified in the Step attribute will be preferred. -
-
- Configuring For Stop - - JSR-352 transition elements are matched against in the order they are defined in the JSL. -
-
-
- Intercepting Step Execution - - JSR-352 provides support for intercepting Step execution by way of listeners. Listeners are configured at the step level contained in a listeners block. - - - - - - - - - Interception Point - - - Listener Interface - - - - Step - javax.batch.api.listener.StepListener - - - Chunk - javax.batch.api.chunk.listener.ChunkListener - - - Item Reading - javax.batch.api.chunk.listener.ItemReadListener - - - Item Processing - javax.batch.api.chunk.listener.ItemProcessListener - - - Item Writing - javax.batch.api.chunk.listener.ItemWriteListener - - - Skip Read - javax.batch.api.chunk.listener.SkipReadListener - - - Skip Process - javax.batch.api.chunk.listener.SkipProcessListener - - - Skip Write - javax.batch.api.chunk.listener.SkipWriteListener - - - - -
-
- Completion Policies - -
- Checkpoint Algorithm - - By default, completion is based on reaching the end of the chunk dictated by its specified (or default) size. A custom algorithm can be created by implementing the javax.batch.api.chunk.CheckpointAlgorithm interface and referencing it via the chunk attribute "checkpoint-policy". -
-
-
-
- ItemReaders and ItemWriters - - JSR-352 provides interfaces to read, process and write data. - - - - - - - - - Role - - - Interface - - - - Reading - javax.batch.api.chunk.ItemReader - - - Processing - javax.batch.api.chunk.ItemProcessor - - - Writing - javax.batch.api.chunk.ItemProcessor - - - - -
-
- Scaling - -
- Partitioning - -
- Partition Plan - - A partition plan defines the attributes of a partitioned step. Both chunk oriented and task oriented Step's may be partitioned. Some of these items include the number of partitions, threads and the partitions properties. For example consider the following partitioned Step sample: - ... -<step> - ... - <partition> - <plan partitions="10" threads="2"> - <properties> - <property name="partitionProperty1" value="value1"/> - </properties> - </plan> - </partition> - ... +
+ 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 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> ... - -
-
- Partition Mapper + 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. + +
- The Partition Mapper provides a way to programmatically calculate the number of partitions and threads for a partitioned Step. The Partition Mapper is a child element of partition and implementations should implement the javax.batch.api.partition.PartitionMapper interface. -
-
- Partition Reducer +
+ 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> +... + +
+
- The Partition Reducer provides a way to programmatically intercept the partitioned Step's lifecycle. The Partition Reducer is a child element of partition and implementations should implement the javax.batch.api.partition.PartitionReducer interface. -
-
- Partition Collector +
+ Running a job - The Partition Collector sends results from each partition to the Partition Analyzer at the end of each checkpoint and again at the end of the partition. The Partition Collector is a child element of partition and implementations should implement the javax.batch.api.partition.PartitionCollector interface. -
-
- Partition Analyzer + 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. +
- The Partition Analyzer is a collection point for data returned by the Partition Collector's and can be used to implement custom exit status handling for the individual partitions. The Partition Analyzer is a child element of a partition and implements should implement the javax.batch.api.partition.PartitionAnalyzer interface. -
-
-