enterprise integration with spring 1 - wordpress.com · enterprise integration with spring 1.x...

21
Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the Enterprise Integration with Spring 1.x Certification Study Guide (Completed: January, 2011). The information in the document is based on the resources mentioned at the bottom and on his own understanding. Remoting General 1. The concepts involved with Spring Remoting on both server- and client-side Remoting synchronous remote procedure call (RPC), all methods are blocking in RMI Server-side: - Exporters that bind to registry or expose an endpoint declaratively, allow exposing a POJO - RmiServiceExporter knows: the service interface, service name, backing bean (implementation of service to expose) Cliet-side: - Proxy FactoryBean generates proxies that communicate with the server-side endpoints - Translate remote exceptions to a runtime hierarchy - RmiProxyFactoryBean knows: the service interface, url Client (JVM 2) 2 - Lookup 3 - Transfer RMI Registry 1 - Expose Server (JVM 1) 2. The benefits of Spring Remoting over traditional remoting technologies - Hide plumbing code (decouples business logic from remoting infrastructure) - Configure and expose services declaratively, without code changes - Support multiple protocols in a consistent way 3. The remoting protocols supported by Spring

Upload: others

Post on 28-May-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

EnterpriseIntegrationwithSpring1.x

Acknoledgement

This document was created by Horatiu Dan following the points in the Enterprise Integration with Spring

1.x Certification Study Guide (Completed: January, 2011). The information in the document is based on

the resources mentioned at the bottom and on his own understanding.

Remoting

General

1. The concepts involved with Spring Remoting on both server- and client-side

Remoting – synchronous remote procedure call (RPC), all methods are blocking in RMI

Server-side:

- Exporters that bind to registry or expose an endpoint declaratively, allow exposing a POJO

- RmiServiceExporter knows: the service interface, service name, backing bean

(implementation of service to expose)

Cliet-side:

- Proxy FactoryBean generates proxies that communicate with the server-side endpoints

- Translate remote exceptions to a runtime hierarchy

- RmiProxyFactoryBean knows: the service interface, url

Client (JVM 2)

2 - Lookup

3 - Transfer RMI Registry

1 - Expose

Server (JVM 1)

2. The benefits of Spring Remoting over traditional remoting technologies

- Hide plumbing code (decouples business logic from remoting infrastructure)

- Configure and expose services declaratively, without code changes

- Support multiple protocols in a consistent way

3. The remoting protocols supported by Spring

Page 2: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

RMI – port: 1099 + “random”, io.Serializable

Hessian – ports: 80 + 443, XML binary, more efficient

Burlap – ports: 80 + 443, XML plain, more readable

HttpInvoker – ports: 80 + 443, io.Serializable

JAX-RPC – replaced by JAX-WS from Java EE 5/ Java 6

Stateless Session Beans (EJB)

RMI-based Spring Remoting

1. How Spring Remoting-based RMI is less invasive than plain RMI

Server:

- Transparently and declaratively exposes a POJO service using a configuration-based

approach (RmiServiceExporter)

- Expose a single service for multiple protocols

- Service interfaces does not extend java.rmi.Remote

- The binding in the RMI registry is done automatically

Client:

- Invoke remote methods from existing code

- Translates the remote checked exceptions to runtime ones (RemoteAccessException)

- Dynamically generates the proxy (RmiProxyFactoryBean)

- Simpler to use than traditional RMI stub

Spring HTTP Invoker

1. How client and server interact with each other

Method invocation request is converted to HTTP POST.

Method result is returned as a HTTP response.

Method parameters are marshalled using Java Serialization.

Server: HttpInvokerServiceExporter

- Declare the bean to expose - transferService

- Declare the invoker bean

<bean name=”/transfer” class=”…HttpInvokerServiceExporter”>

<property name=”serviceInterface” value=”foo.TransferService” />

<property name=”service” ref=”transferService” />

</bean>

- Expose it using either DispatcherServlet or HttpRequestHandlerServlet (when the former is

not available, declare the servlet directly in the root application context)

Client: HttpInvokerProxy

Page 3: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- Define a factory bean to generate the proxy

<bean id=”transferService” class=”…HttpInvokerProxyFactoryBean”>

<property name=”serviceInterface” value=”foo.TransferService” />

<property name=”serviceUrl” value=”http://foo:8080/sv/transfer”/>

</bean>

Web Services

General

1. How do Web Services compare to Remoting and Messaging

- Loosely coupled - Document-Oriented contract between consumers and providers is defined

- Interoperable with other Java platforms as they are based on XML

Spring Web Services

1. The approach to building web services that Spring-WS supports

Spring uses contract-first approach – the XSD/WSDL is written first:

- Create a simple message - XML

- Infer a contract using 3rd

party tools – generate XSD from XML

- Adjust and tweak the resulting contract / message – impose restrictions, patterns

Dynamically generates the WSDL from XSD.

2. The Object-to-XML frameworks supported by Spring-OXM (Note that Spring-OXM is now a

module in Spring 3.0, not in Spring-WS, but for what you need to know that doesn't matter)

Techniques for handling SOAP requests:

- Low level parsing of XML: DOM, SAX, StAX

- Marshalling: JAXB 1, JAXB 2, Castor, XMLBeans, JiBX, XStream

- XPath argument binding

Marshaller can be declared manually:

<oxm:jaxb2-marshaller id="marshaller" contextPath="rewards.ws.types" />

No explicit marshaller bean definition is needed:

<ws:annotation-driven /> - registers all infrastructure beans needed for annotation-based

endpoints, including the JAXB2 (un)marshalling.

3. The strategies supported to map requests to endpoints

Page 4: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

Server-side:

- Entry point of the SOAP request is MessageDispatcherServlet

- Based on the EndpointMapping determines the endpoint to invoke

- The Endpoint invocation is done indirectly using EndpointAdapter, which also handles the

unmarshalling

@Endpoint annotated classes are component-scanned.

Mapping techniques:

- Message Payload (@PayloadRoot)

- SOAP Action Header (@SoapAction)

- WS-Addressing - based on SOAP Action, ReplyTo and To headers

- XPath

4. Of these strategies, how does @PayloadRoot work exactly?

@Endpoint (class) – marks the class as a web services endpoint bean

@PayloadRoot (method) – maps the root tag of the SOAP request body to the method

localPart – XSD/WSDL root element of the request payload

namespace – namespace URL

@RequestPayload - the method parameter - mapped to the payload of the request message

@ResponsePayload - the return value - used as the payload of the response message. If the return value

is void (no annotation), no response is sent.

@PayloadRoot(localPart="helloRequest", namespace="http://myapp.com/hello")

public @ResponsePayload Hello sayHello (@RequestPayload Person onePerson)

5. The functionality offered by the WebServiceTemplate

- Used on the client-side

- Simplifies the web service access

- Works directly with the XML payload:

o Body of a SOAP message

o With POX

- Can use mashallers/unmarshallers

- Can use interceptors (e.g. for validation)

- Provides methods for sending / receiving WS messages

- Provides callbacks for low level access – e.g access to SOAP message header

- Handles errors using SoapFaultMessageResolver that encapsulates errors in a

SoapFaultClientException

- Allows multiple protocols: HTTP, Mail, JMS, XMPP

- Send Source objects as request

- Receive response messages as Result

Page 5: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

Web Services Security

1. The underlying WS-Security implementations supported by Spring-WS

WS-Security in terms of authentication, signing and encryption is implemented using interceptors:

- XwsSecurityInterceptor – for Sun’s XWSS, requires Sun (Oracle) JVM and Saaj

It requires a security policy file to operate.

- Wss4jSecurityInterceptor - for integrating Apache WSS4J, supports non-Sun JVMs and

Axiom.

Standards:

o SOAP Message Security 1.0 (OASIS)

o Username Token profile 1.0

o X.509 Token Profile 1.0

2. How key stores are supported by Spring-WS for use with WS-Security

A key store is used within a security interceptor inside a KeyStoreCallbackHandler.

KeyStoreCallbackHandler has three properties:

- keyStore – for private keys, uses WS-Security to sign and decrypt

- trustStore – for determining trust relations

- symmetricStore – symmetric key (secret key), client and server store the same key

The exact stores used by the handler depend on the cryptographic operations that are to be performed.

privateKeyPassword property is used to unlock the private key(s) contained in the key store.

If symmetricStore is not set, it will default to the keyStore.

If neither keyStore nor trustStore is set, it will default to using the Java standard mechanism to load or

create it.

A key store stores three types of elements: private keys, symmetric keys (or secret key), certificates

(X509).

RESTful services with Spring-MVC

General

1. The main REST principles

REST - architectural style, based on HTTP.

HTTP is used as the application protocol and not just as a transport protocol as for SOAP.

Page 6: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- Identifiable resources - expressed by their URIs

- Uniform interface

o HTTP used as interface

o Methods:

GET – retrieves a representation of a resource (e.g. /resource/123)

� Safe

� Idempotent

� Cacheable – servers return an ETag header that is sent by clients on

subsequent request as If-None-Match header – if not modified (304), empty

body is returned

� Response – 200 OK

HEAD – similar to GET but without response body

� Safe

� Idempotent

� Not-cacheable

� Response – 200 OK

PUT – updates a resource or creates it with a known destination URI (e.g.

/resource/123)

� Not-safe

� Idempotent

� Not-cacheable

� Response – 204 No Content

POST – creates a new resource, response Location header used to indicate the URI

of the created resource

� Not-safe

� Not-idempotent

� Not-cacheable

� Response – 201 Created

DELETE – deletes a resource (e.g. /resource/123)

� Not-safe

� Idempotent

� Not-cacheable

� Response – 204 No Content

- Stateless conversation

o Server maintains no state, client maintains state through links

o Very scalable architecture – opposite to RMI

- Resource representation

o Multiple representations possible (text/html, image/png):

� Request specifies it via Accept HTTP header

Page 7: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

� Response specifies it via Content-Type HTTP header

- Hypermedia

o Resources contain links provided by the server which allow client state transitions

Security:

- Sent on every request

- HTTP Basic (user and pass concatenated by browser, encoded, not encrypted) or

- Digest (user and pass concatenated by browser, digested, not encrypted)

- SSL is needed

- XML-Encryption and XML-DSIG may be used for message level security.

Not designed for long running transactions – compensating transactions (designed and implemented by

the developer).

REST support in Spring-MVC

1. Spring-MVC is an alternative to JAX-RS, not an implementation

Two options to use Spring for REST:

JAX-RS:

- The standard for implementing RESTful Web Services (JSR-311).

- Jersey is the reference implementation; RESTEasy, CXF, Restlet support Spring as well

- Focuses more on app-to-app communication than using browsers as REST clients

- Annotations: @Path, @GET, @POST, @Produces, @PathParam

Spring-MVC:

- Uses Spring MVC annotations: @RequestMapping, @PathVariable

- URI template support: /resource/{id}

- Content negotiation

- Declarative status codes @ResponseStatus(HttpStatus.CREATED)

- Message converters:

<mvc:annotation-driven/> configures by default several converters

(e.g. Jaxb2RootElementHttpMessageConverter)

- RestTemplate for client-side

- Supports browsers as REST clients

2. The @RequestMapping annotation, including URI template support

@RequestMapping maps an HTTP request on a class (Controller) and method.

Parameters:

- value – designates the URI that may contain a template with {}. @PathVariable on a method

parameter extracts the value, converts it and sets the method parameter with it

Page 8: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- method – the HTTP request method used (RequestMethod.GET, POST, PUT, DELETE, HEAD,

OPTIONS, TRACE)

- params – parameters of the HTTP request to be mapped

- headers – HTTP headers of the mapped request

- consumes, produces – consumable and producible media types

@PathVariable:

- parameter is not necessary if the parameter name is the same as the pattern

- when a @PathVariable annotation is used on a Map<String, String> argument, the map is

populated with all URI template variables

- regular expressions can be used

@RequestMapping("/spring-web/{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}")

public void handle(@PathVariable String version, @PathVariable String ext)

3. The @RequestBody and @ResponseBody annotations

@RequestBody:

- used for PUTs and POSTs

- converts the HTTP request body to the annotated method parameter

- a converter is chosen based on the Content-Type of the request

@ResponseBody:

- used for methods that return values – e.g. GETs

- converts the annotated return value of a method into the HTTP response body

- a converter is chosen based on the Accept header of the request

4. The functionality offered by the RestTemplate

- Client-side class for consuming RESTful web services

- Supports URI templates and HttpMessageConverters

- Provides direct access to the body of the request / response

- Uses HttpEntity for modelling a HTTP request / response and access both body and headers

- Can be instantiated directly or as a bean

- Can be configured to rely on Apache Commons Http Client

Methods by methods:

GET: getForObject(String url, Class<T> responseType, String… urlVars) getForEntity(String url, Class<T> responseType, String… urlVars)

POST: postForLocation(String url, Object request, String… urlVars) postForObject(String url, Object request,Class<T> responseType, String… urlVars) postForEntity(String url, Object request,Class<T> responseType, String… urlVars)

PUT: put(String url, Object request, String… urlVars)

DELETE: delete(String url, String… urlVars)

Page 9: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

HEAD: headForHeaders(String url, String… urlVars)

OPTIONS: optionsForAllow(String url, String… urlVars)

- First part indicates what HTTP method to invoke, the second part indicates what is returned.

e.g. postForLocation() – do a POST, converting the given request Object into a HTTP request that returns

the response HTTP Location header where the newly created object may be found

- Each method takes a URL parameter as the first argument which can support URI templates.

e.g. Item[] result = template.getForObject(“http://service/resources/{id}/items”, Item[].class, “123”);

- Objects passed and returned from the methods getForObject(), postForLocation(), put() are

converted to HTTP requests and from HTTP responses by HttpMessageConverters that are

registered by default.

JMS with Spring

General

1. Where can Spring-JMS applications obtain their JMS resources from

In general:

ConnectionFactory – in an enterprise application, it is a managed resource - bound to JNDI

Connection – obtained from a ConnectionFactory

Session – created from a Connection, it is a unit-of-work, provides transactional capability, it creates

message producers, message consumers, messages of different types

In Spring:

ConnectionFactory – can be standalone (receives brokerUrl), or retrieved via JNDI.

Destination – can be standalone (receives queue name) or retrieved via JNDI.

The framework instantiates the JMS resources.

2. The functionality offered by Spring's JMS message listener container, including the use of a

MessageListenerAdapter through the 'method' attribute in the <jms:listener/> element

Spring message listener containers are an alternative to requiring an EJB container:

- Used for asynchronous message reception from JMS message queues and drive

MessageListener that is injected into it

- Provides two implementations:

Page 10: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

o SimpleMessageListenerContainer – fewest requirements on the JMS provider, uses

plain JMS client API, fixed number of sessions, does not allow dynamic adaptation to

runtime demands, cannot participate in externally managed transactions.

o DefaultMessageListenerContainer – used in most cases, adds transactional

capabilities, adds dynamic adaptation to runtime demands, scales better, can

participate in externally managed transactions, each received message is registered

with an XA transaction when configured with a JtaTransactionManager.

JMS namespace simplifies the declaration of a container containing a list of JMS listeners. Also, it

allows the configuration of concurrency, task execution strategy, container type, transaction

manager

<jms:listener-container connection-fatory="jmsCF">

<jms:listener destination="queue.order" ref="orderListener"/>

<jms:listener destination="queue.conf" ref="confListener"/>

</jms:listener-container>

Listener bean can:

- implement MessageListener (implement onMessage()) or SessionAwareMessageListener

(allows tweaking with JMS Session)

- be used in any bean directly via MessageListenerAdapter

o through the use of “method” attribute of a <jms:listener/> allows specifying a POJO

as a MDO

<jms:listener ref=”orderService”

method=”order”

destination=”queue.orders”

response-destination=”queue.conf” />

public class OrderService {

public OrderConfirmation order(Order o) {}

}

The result of a MD POJO is sent to the destination (if one exists) defined in the JMS

Reply-To property of the original Message.

3. The functionality offered by the JmsTemplate

- Reduces boilerplate code

- Manages resources transparently

- Handles exceptions properly (converts checked JMSException to the corresponding runtime)

- Provides convenience methods and callbacks

- Delegates to collaborators to handle extra work:

MessageConverter:

- converts between objects and messages (String to text, byte[] to Byte, Map to Map,

Serializable to Object )

- default is SimpleMessageConverter

- custom implementation

Page 11: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

o implement the two methods: Message toMessage(Object object, Session session)

Object fromMessage(Message message)

o suitable for XML marshalling into TextMessage – JAXB, Castor, XMLBeans, XStream

DestinationResolver

- resolves destination names at runtime

- default is DynamicDestinationResolver

- custom implementation – implement the method: Destination resolveDestinationName(Session session,

String destinationName, Boolean pubSubDomain) throws JMSException

- By using a CachingConnectionFactory, it allows reusing of the JMS resources which will

otherwise be closed; usually used when a pool is not available from the vendor

- Created by providing a connectionFactory and optionally messageConverter,

destinationResolver, defaultDestination, defaultDestinationName

- Sending:

o one-line methods for sending simple messages – convertAndSend

o callback-accepting methods when more control is needed:

void convertAndSend(Object message, MessagePostProcessor mpp) void send(MessageCreator creator) <–- createMessage(Session session)

Object execute(ProducerCallback<T> action) Object execute(SessionCallback<T> action)

- Receiving:

o Synchronous, blocking the caller thread with timeout

receive()

receive(Destination destination)

receive(String destinationName)

receiveAndConvert(destination) - MessageConverter is leveraged

Transactions

Local JMS Transactions with Spring

1. How to enable local JMS transactions with Spring's message listener container

Spring’s message listener container allows using either local JMS transactions (transacted session) or

one of the acknowledge modes. Local transaction:

- acknowledge=”transacted”

- transaction-manager=”localTransactionManager”

Mutually exclusive acknowledge attribute <jms:listener-container acknowledge = "…">:

Page 12: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- transacted

o the transaction applies only to the JMS resource

o all JMS operations must use the same session

o the transaction starts when the message is received

The following indicate when a message is successfully delivered outside a transaction:

- auto

o after every successful receive() or onMessage()

o successful reception marks the message delivered and removes it from the queue

o slower than the other modes

o results in message loss if processing after reception fails

- client

o client takes the responsibility for the acknowledgement – Message.acknowledge()

o multiple messages can be acknowledged at once

o if the client fails before acknowledging the message, it is redelivered -> duplicates

- dups_ok

o messages are lazily acknowledged

o if the JMS provider fails before acknowledgement -> duplicates

o has better performance than auto

2. If and if so, how is a local JMS transaction made available to the JmsTemplate

Used in a listener with acknowledge=“transacted” mode, JmsTemplate uses the same JMS session and is

therefore involved in the same transaction initiated by the listener.

sessionTransacted and sessionAcknowledgeMode attributes can be specified for local transacted

session or acknowledgement mode.

Read and write operations use the same Session when transaction is in progress – internally obtained

through ConnectionFactoryUtils.doGetTransactionalSession().

3. How does Spring attempt to synchronize a local JMS transaction and a local database

Transaction

Best-effort strategy is used:

- Database commit before JMS commit – never loses messages, but causes duplicates if JMS

commit fails

- Put commits close together to reduce failure possibility

Only XA distributed transactions guarantees once-and-only-once delivery.

Page 13: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

4. The functionality offered by the JmsTransactionManager

It performs local resource transactions, binding a JMS Connection / Session pair from the specified

ConnectionFactory to the thread.

JmsTemplate automatically detects an attached thread and participates automatically with Session.

It allows a CachingConnectionFactory that uses a single JMS Connection for all access (performance

gain); all Sessions belong to the same Connection.

JTA and Two-phase commit transactions with Spring

1. What guarantees does JTA provide that local transaction do not provide

- Ensures ACID principles when multiple resources are involved

- Enable multiple resources to participate in a single transaction – the commit is coordinated

- Message duplication is not an issue any more – once and only once delivery is assured

2. How to switch from local to global JTA transactions

- Through reconfiguration in XML (no code changes) – configure JtaTransactionManager

and add it to the container configuration (instead of the PlatformTransactionManager)

- JtaTransactionManager does not provide JTA support, it only integrates local

transactions with external (application server) JTA transaction manager

- If application server specific subclass is used, it allows using features that are not in the JTA

spec (transaction suspension)

- JTA is required when the transactions are handled using an EJB container (even for local

transactions), it is optional when using Spring

- TX Resources:

o JDBC and JMS – using XA-aware types is enough

o Other code (e.g. Hibernate) may require additional information to find the JTA TX

- Databases and synch JMS – no changes (@Transactional, <tx:annotation-driven />)

- Asynch JMS – pass JTA transaction manager to listener container <jms:listener-container transaction-manager=”transactionManager”>

3. Where can you obtain a JTA transaction manager from

In a J2EE application server:

- ask for the look-up of the JTA TX manager and use server-specific subclass if present: <tx:jta-transaction-manager />

- each XA transactional resource (dataSource for DB access, connectionFactory for JMS

access) can be retrieved by a JNDI look-up.

Stand-alone applications:

Page 14: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- define the JtaTransactionManager plain bean and define the properties using a third party

(e.g. Atomikos, JOTM, Jboss Transactions)

<bean id="transactionManager" class="org.sf.tr.jta.JtaTransactionManager"

p:transactionManager-ref="3rd party”

p:userTransaction-ref=”3rd party />

Batching processing with Spring Batch

General

1. Main concepts (Job, Step, Job Instance, Job Execution, Step Execution etc.)

Job Repository – is the keeper of all knowledge and metadata for each Job

Job Launcher:

- interface to start a Job with a set of Job Parameters

Job:

- defines what needs to be done, encapsulates the entire batch process

- has one or more Steps, one after another

Step:

- has one or more Tasklets

- has one or more Step Executions

- can be concurrent

Job Instance:

- is consisted of Job + Job Parameters, the same Job with different Job Parameters

- it is unique because of the Job Parameters associated with the Job

- when run a new Job Execution is created

- can be restarted and the subsequent run creates another Job Execution

Job Execution:

- every run / restart of a Job Instance

- has as many Step Executions as many Steps the Job has

- provides the ExitStatus

Step Execution:

- physical attempt to execute a Step

- for every Step in a Job there is a Step Execution in the Job Execution

2. The interfaces typically used to implement a chunk-oriented step

ItemReader<T> - T read()

- reads a chunk from the source (invoked multiple times – chunk size)

- null return value indicates no more items are left

ItemProcessor<T, S> - S process(T)

- optional

Page 15: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- processes the chunk (invoked multiple times – chunk size)

- represents the business processing of an element

- null return value indicates the item should not be written out

ItemWriter<S> - write(List<? extends S> list)

- writes the chunk to destination (invoked once)

3. How and where state can be stored

JobRepository interface provides a persistence mechanism that includes CRUD operations for Jobs’

executions and Steps’ executions.

Spring Batch provides two mechanisms:

- In memory, into a volatile Map

- In a relational database

Readers and Writers are stateful and may persist data using the ExecutionContext (key/value pairs

persisted and controlled by the framework).

Job Execution Context commits at the end of each Step.

Step Execution Context commits at the end of each Chunk.

StepExecutionListener, @BeforeStep, ItemStream

4. What are job parameters and how are they used

- represent the runtime parameters of a batch job

- together with the job provide uniqueness to the Job Instance (can be used for identification

or even as reference data of JobInstance during the run)

- can be String, Date, Long, Double

5. What is a FieldSetMapper and what is it used for

FieldSetMapper is an interface used to map the data obtained from a FieldsSet into a domain object:

T mapFieldSet (FieldSet fs)

The FieldSet provides access to the fields from a line by index, name or type.

Two types of FieldsSetMapper:

- PassThroughFieldSetMapper – returns the FieldSet unchanged

- BeanWrapperFieldSetMapper – uses introspection based on the names of the bean

properties and the name of the fields in the FieldSet

Page 16: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

Spring Integration

General

1. Main concepts (Messages, Channels, Endpoint types)

Message

- wrapper for any Java object combined with metadata used by SI

- payload contains the Java object, Map<String, Object> of headers represents the metadata

- is immutable

- has a unique identifier

Message Channel

- connects the Endpoints

- component through which the messages are moved

- effectively decouples the producer from the consumer – loose coupling

- in memory by default (no persistence), but with the ability to persist messages (JMS or JDBC

Message Store)

- may be:

o point-to-point - a message is received only once by a single consumer

o publish-subscribe – a message is received by all consumers

Message Endpoint

- abstraction layer between the application code and the messaging framework

- handles the producing and consuming of messages, interfacing with application code or

external services or applications

Types of Endpoints:

- Service Activator

o Interface between the message channel and a service instance, containing the

application code for business logic

o Invoke any bean method (if not specified) for incoming messages on input-channel

o Specify method attribute or @ServiceActivator if multiple methods exist

o void and null returning methods are supported – no response message sent,

similar to <outbound-channel-adapter>

o If no output channel is specified, the message is sent back on the input channel

o requires-reply=”true” to throw an exception

<service-activator input-channel="input" output-channel="output"

ref="someService" method="someMethod"/>

- Channel Adapter

o One way integration - connects the message channel to another system or transport

o May be:

� inbound – messages enter the application (soap, file � message)

� outbound – messages leave the application (message � mail, jms)

Page 17: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- Gateway

o 2 way integration

o Hides the messaging API provided by SI – acts as a proxy

o May be:

� inbound – bring messages into the application and wait for response

� outbound – invoke external system and bring the response back into the

application

o Gateway interface methods may return:

� a result – it is sent to the reply channel

� void – nothing is sent to the reply channel – acts as an inbound adapter

� Future<Result> - turns into async, non-blocking

<int:gateway id="cafeService" service-interface="org.ICafeService"

default-request-channel="request" default-reply-channel="reply" />

o The default-reply-channel attribute is optional. SI creates a disposable Temporary

Channel if the former is not provided.

- Filter

o Decides whether to pass or drop a message

o By default, silently drop the message

o If throw-exception-on-rejection=“true”, throw exception on rejection

o If discard-channel=”invalidItems”, pass message to discard channel on

rejection (2 way router or switch)

<filter input-channel="input" output-channel="output" ref="filterBean"

method="filter" />

- Router

o Decides which channel to send a message to, based on payload or headers

<router input-channel="input" ref="routerBean" method="route" />

- Transformer

o Service activator with specific intent:

� Payload format conversion

� Payload or header enriching

<transformer input-channel="input" output-channel="output"

ref="transformerBean" method="transform" />

- Splitter

o splits a message into multiple messages

o splitting strategy should be provided in a dedicated method

o it sets in header of the messages CORRELATION_ID (MESSAGE_ID of original),

SEQUENCE_SIZE, SEQUENCE_NUMBER

<splitter input-channel="input" output-channel="output" ref="splitterBean"

method="split" />

Page 18: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- Aggregator

o recomposes a message from multiple messages

o aggregating strategy should be provided in a dedicated method

o holds messages until a set of correlated messages is ready for release

o Correlation:

� CORRELATION_ID header is used by default

� correlation-strategy, correlation-method, correlation-expression may be set

o Release:

� SEQUENCE_SIZE header is used by default

� release-strategy, release-strategy-method, release-strategy-expression may

be set

<aggregator input-channel="input" output-channel="output"

ref="aggregatorBean"

correlation-strategy="correlationBean"

release-strategy-expression="#this.size () gt 10" />

2. How to programmatically create a new Message

- MessageBuilder.withPayload("test").setHeader("foo", "bar").build();

- new GenericMessage(payload, headers)

3. Using chains and bridges

- Chain

o Ease the configuration when working with many endpoints – unmarshal, filter

redundant messages, invoke service

o All endpoints are wired with DirectChannels in the declared order

o All endpoints except for the last must return output

o If the last endpoint returns output, either output-channel or reply-channel

must be set

o Endpoints can filter messages by returning null

<chain input-channel="input" output-channel="output">

<filter ref = "someSelector" />

<service-activator ref="someService" method="someMethod" />

</chain>

- Bridge

o Used to connect to channels or two channel adapters

o Can have a poller for throttling messages

<bridge input-channel="input" output-channel="output">

<poller max-messages-per-poll="5" fixed-rate="200"/>

</bridge>

Page 19: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

Synchronous vs. asynchronous message passing

1. The different channel types and how each of them should be used

- Point-to-point

o Only one receiver that receives the message from the sender

o May be:

� DirectChannel – send blocking, synchronous reception in the sender’s

thread, ability to have multiple subscribers in failover mode or load

balancer

� ExecutorChannel – send non-blocking, asynchronous reception in a single

thread

� QueueChannle – send non-blocking, asynchronous reception in one or more

threads based on a polling mechanism

• RendezvousChannel – zero-capacity

• PriorityChannel – header priprity

� NullChannel

- Publish-subscribe

o One or many receivers receive the same message. The message is marked as

received and removed from the channel when all receivers have consumed the

message.

o Synchronous – sequential calls in the sender thread

o Asynchronous –parallel calls, using a TaskExecutor

2. The corresponding effects on things like transactions and security

The type of channel has significant implications for applications, including transactional boundaries.

Synchronous:

- DirectChannel and PublishSubscribe Channel with no TaskExecutor

- Sending thread invokes receiver(s) directly

- Treated as method calls:

o Transactional contexts and security (ThreadLocal)

o Exceptions returned to the caller

o Low overhead

o Not scalable

<channel id=”direct” />

<publish-subscribe-channel id=”pubsub” />

Asynchronous:

- All other channel types different from above

- Receivers get the messages in different threads

- Transactions and security contexts are lost if thread boundary is broken

- Exceptions are not propagated to the caller

Page 20: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

<channel id=”direct”>

<queue capacity=”10” />

</channel>

<publish-subscribe-channel id=”pubsub” task-executor=”taskExecutor” />

Transactional context is preserved as long as it is ensured that the flow continues on the same

thread.

Transactional channels may be used where a thread boundary is being broken by using:

- Queue-backed Channel that delegates to a transactional MessageStore

- JMS-backed Channel

3. The need for active polling and how to configure that

Channels are passive so polling is required to enable the consumption of the messages from the

PollableChannels.

By default, a single thread does the polling, but a thread pool may be configured.

Endpoints use default poller when needed:

<poller default="true" task-executor="pool" fixed-delay="200" />

but can override it with their own:

<service-activator ...>

<poller task executor="otherpool" fixed-rate="500" />

</service-activator>

Pollers can be declared transactional so that the message handling flow is atomic. Pre-conditions:

- Flow is single threaded

- The transaction includes the call to receive() method of PollableChannel

<service-activator ...>

<poller fixed-rate="500">

<transactional />

</ poller>

</service-activator>

Advanced mechanisms

1. Point-to-point Dispatch

- Point-to-point SubscribableChannel ensures single handler per message, but still have

multiple subscribers

Page 21: Enterprise Integration with Spring 1 - WordPress.com · Enterprise Integration with Spring 1.x Acknoledgement This document was created by Horatiu Dan following the points in the

- By default, SI uses a round-robin load balancer with fail-over to rotate over subscribers (call

the next when an exception is thrown) – handlers can have order set, otherwise the order of

subscribing is used

- failover = “false” � exception propagates back to the caller

- load-balancer = “none” � subscribers are always called in the same order

- Asynchronous dispatching :

o ExecutorChannel instead of DirectChannel

o Sending does not block

o Subscribers still called from a single thread, other than the sender’s one

References

- Spring Framework Reference Documentation, version 3.2.13.RELEASE -

http://docs.spring.io/spring/docs/3.2.13.RELEASE/spring-framework-reference/htmlsingle/

- Spring Web Services Reference Documentation, version 2.2.0.RELEASE -

http://docs.spring.io/spring-ws/docs/2.2.0.RELEASE/reference/htmlsingle/

- Spring Batch Reference Documentation, version 3.0.3.RELEASE -

http://docs.spring.io/spring-batch/trunk/reference/html/index.html

- Spring Integration Reference Manual, version 3.0.6.RELEASE - http://docs.spring.io/spring-

integration/docs/3.0.6.RELEASE/reference/html/

- Lubos Krnac’s resources and study-notes -

http://java.dzone.com/announcements/enterprise-integration-spring

- Java et Moi resources and study-notes - http://javaetmoi.com/2012/09/certified-spring-

enterprise-integration-specialist-study-notes/