IntegrationAndMessaging

Download Report

Transcript IntegrationAndMessaging

Integration and Messaging
-Jagadeesh
9 April 2016
SCEA Exam 1 : Objectives - Module 3
• Module/Section 3: Integration and Messaging
– Explain possible approaches for communicating with an external system from a Java
EE technology-based system given an outline description of those systems and
outline the benefits and drawbacks of each approach.
– Explain typical uses of web services and XML over HTTP as mechanisms to
integrate distinct software components.
– Explain how JCA and JMS are used to integrate distinct software components as part
of an overall Java EE application.
• Today’s Agenda
– Webservice (JAX-WS)
– JMS
– JCA
– Choosing between JMS,JCA and Webservice
9 April 2016
2
Web Services
 Web service Introduction
 JAX-WS Introduction
 Creating Webservice
 Consuming Webservice
 Message Handlers
 JAXB
 Web Service Bindings
 WS-* Specification
 Stax and SAAJ
9 April 2016
3
Web Services - Introduction
• A web service is a piece of business logic, located somewhere on the Internet, that is
accessible through standard-based Internet protocols such as HTTP or SMTP.
• Identified by a URI
• Interfaces defined using XML
• Can be discovered by other systems
• Interact using XML based messages conveyed by Internet protocols
• Allow applications to interoperate in platform-neutral and language neutral
9 April 2016
4
Java API for XML Web Services
• The Java API for XML Web Services (JAX-WS) is a Java programming language API
for creating and consuming web services.
• JAX-WS 2.0 replaced the JAX-RPC API in Java Platform, Enterprise Edition 5. The
name change reflected the move away from RPC-style and toward document-style web
services.
• JAX-WS uses annotations, to simplify the development and deployment of web service
clients and endpoints.
JAX-RPC
JAX-WS
Image Source: JAX-WS Tutorial
9 April 2016
JAX-WS : Key concepts
• Port/Port Type
– A WSDL Port/port type is a named set of abstract operation definitions
• Operation
– Operation maps to a Java method in the corresponding webservice (Java service
endpoint interface)
• Endpoint – Location (URL) of the webservice.
• SEI
– A service endpoint interface or service endpoint implementation (SEI) is a Java
interface or class, respectively, that declares the methods that a client can invoke on
the service.
• An interface is not required when building a JAX-WS endpoint. The web service
implementation class implicitly defines an SEI.
9 April 2016
6
Creating Webservice – Starting from Java Class
• Code and compile implementation class.
• Use wsgen to generate the artifacts required to deploy the service.
• Package the files into a WAR file.
• Deploy the WAR file. The web service artifacts (which are used to communicate with
clients) are generated by the Application Server during deployment.
package helloservice.endpoint;
import javax.jws.WebService;
@WebService
public class Hello {
private String message = new String("Hello, ");
public void Hello() {}
@WebMethod
public String sayHello(@WebParam(name = “name") String name) {
return message + name + ".";
}
}
9 April 2016
7
Deploying Webservices – IDE and App Server
dependencies
Netbeans with Glasshfish
Eclipse with Tomcat 5.5
Code Java Class with @Webservice,
@WebMethod annotations
Install JAX-WS SI on tomcat
Right click on the project and click
deploy
Update Web.xml to include WSServlet
and WSServletContextListener
Expand Webservice node in the project
tree, right click on your webservice and
choose Test Web service to test the web
service
Create sun-jaxws.xml to declare an
endpoint for your webservice
<endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime'
version='2.0'>
<endpoint
name=helloservice'
implementation='helloservice.endpoint.Hello'
url-pattern='/helloservice'/>
</endpoints>
Code Java Class with @Webservice,
@WebMethod annotations
Run Wsgen on the compiled classes
Deploy project on app server
Create Test client to test your web
service
9 April 2016
8
Creating Webservice – Starting from WSDL
• Use wsimport to generate Service endpoint interface (This is the Java interface)
• Implement the service endpoint interface and compile
• Use wsgen to generate the artifacts required to deploy the service.
• Package the files into a WAR file.
• Deploy the WAR file. The web service artifacts (which are used to communicate with
clients) are generated by the Application Server during deployment.
9 April 2016
9
Creating Webservice Client
• Three options available for creating webservice clients
– Annotations
• Use this option if you are calling from container (E.g. Web container, Client
container)
– Dynamic Proxy APIs
• Use this option if you are not calling from container and do not want to process
XML in the program
– Dispatch Client APIs
• Use this option if you need to process the XML in your program
• Using annotations
– Use wsimport to tool to create Port (Client side proxy/stub)
– Use Annotations
public class HelloClient {
@WebServiceRef(wsdlLocation="http://localhost:8080/helloservice/hello?wsdl")
static HelloService service;
public void doTest(String[] args) {
Hello port = service.getHelloPort();
port.sayHello();
}
9 April 2016
10
Dynamic Proxy Client
• Dynamic Proxy APIs
– Dynamic Proxy client is similar to the stub client in the Java API for XML-based RPC (JAXRPC) programming model.
• The Dynamic Proxy client is dynamically generated at run time using the Java 5 Dynamic
Proxy functionality, while the JAX-RPC-based stub client is a non-portable Java file that is
generated by tooling.
– The Dynamic Proxy client invokes a Web service based on a Service Endpoint Interface
(SEI) which must be provided.
• Using Dynamic Proxy APIs
– Use wsimport to tool to create Port (Client side proxy/stub)
– Use the following code
URL wsdlLocation = new URL(" http://localhost:8080/helloservice/hello?wsdl");
javax.xml.namespace.QName serviceName = new
QName("http://localhost:8080/helloservice/hello", “HelloService");
javax.xml.ws.Service s = Service.create(wsdlLocation, serviceName);
helloservice.endpoint.Hello proxy = service.getPort(portName, helloservice.endpoint.Hello.class)
proxy.sayHello();
9 April 2016
11
Dispatch Client API
• Use Dispatch Client API when you need to work at the XML message level.
• The Dispatch client API, javax.xml.ws.Dispatch, is a dynamic JAX-WS client programming
interface.
• Two Modes
– Message - Your code is responsible for providing the entire SOAP envelope
including the <soap:Envelope>, <soap:Header>, and <soap:Body> elements.
– Payload - Your code is only responsible for providing the contents of the
<soap:Body> and JAX-WS includes the payload in a <soap:Envelope> element.
• To construct XML the following types of objects are supported
– javax.xml.transform.Source: Use Source objects to enable clients to use XML APIs
directly. You can use Source objects with SOAP or HTTP bindings.
– JAXB objects: Use JAXB objects so that clients can use JAXB objects that are
generated from an XML schema to create and manipulate XML with JAX-WS
applications. JAXB objects can only be used with SOAP or HTTP bindings.
– javax.xml.soap.SOAPMessage: Use SOAPMessage objects so that clients can work
with SOAP messages. You can only use SOAPMessage objects with SOAP bindings.
– javax.activation.DataSource: Use DataSource objects so that clients can work with
Multipurpose Internet Mail Extension (MIME) messages. Use DataSource only with
HTTP bindings.
9 April 2016
12
Dispatch Client API (Contd..)
• Example
URL wsdlLocation = new URL(" http://localhost:8080/helloservice/hello?wsdl");
javax.xml.namespace.QName serviceName = new
QName("http://localhost:8080/helloservice/hello", “HelloService");
javax.xml.ws.Service s = Service.create(wsdlLocation, serviceName);
SOAPMessage soapReqMsg = <<Construct the soap message>>;
Dispatch<Source> disp = service.createDispatch(portName, SOAPMessage.class,
PAYLOAD);
Source resMsg = disp.invoke(soapReqMsg);
• The Dispatch client is invoked in one of three ways:
– Synchronous invocation for requests and responses using the invoke method
– Asynchronous invocation for requests and responses using the invokeAsync method
with a callback or polling object
– One-way invocation using the invokeOneWay methods
9 April 2016
13
Web Service Bindings
• Defines how the web service is bound to the messaging protocol (SOAP)
• In JAX-WS the bindings are defined using annotations (@SOAPBinding) or WSDL file
• JAX-WS supports only the following bindings. Encoded bindings are not supported
– RPC/Literal ( Wrapped by default)
– Document/Literal
– Document/Literal Wrapped
9 April 2016
14
WS-* Specifications
WS-* specifications describes how to attach additional capabilities to the SOAP
messages
Specification
Purpose
WS-Security
Describes how to attach signature, security tokens and encryption
headers to SOAP messages
WS-Policy
Describe the capabilities and constraints of the security policies on
intermediaries and end points (for example,
required security tokens, supported encryption algorithms, and privacy
rules) and how to associate policies with services and end points.
WS-Transaction /
WS-Coordination
describe how to
enable transacted operations as part of Web service message
exchanges
WS-Addressing
describes how to specify identification and addressing information for
messages
9 April 2016
15
JAXB
• The Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind
between XML schemas and Java representations
– It makes easy for Java developers to incorporate XML data and processing functions
in Java applications
– JAXB provides methods for unmarshalling XML instance documents into Java
content trees
– Also provides methods for marshalling Java content trees back into XML instance
documents.
• JAX-WS uses JAXB internally to marshal and unmarshall the XML.
– The bindings (Binding declarations) are fully customizable using annotations like
@XmlRootElement, @XmlAttribute and so on.
Image Source: JAX-WS Tutorial
9 April 2016
16
Message Handlers
• Message handlers are like filters or interceptors for the web service.
– Handlers are used to perform additional processing
on inbound and outbound message
– Handler chains can be configured per
port basis, per protocol, per-service basis.
• Two type of Message Handlers
– Protocol Handlers - This is to be used to manipulate protocol specific information.
• Currently we have only SOAPHandler.
– Logical Handlers - This is used to manipulate messages (Payload)
• For more information please refer to
– https://jax-ws.dev.java.net/articles/handlers_introduction.html
Image Source: JAX-WS Website
9 April 2016
17
JAX-WS – Key points to remember
• JAX-RPC 2.0 is renamed as JAX-WS 2.0. There is no JAX-WS 1.0
• Better platform independence for Java applications
– JAX-WS produces artifacts that are portable.
– Does not rely on the vendor dependent stubs generated at build time. The proxies
are generated dynamically at runtime.
• Uses Annotations
• Can invoke Webservices asynchronously
• Webservices can be injected as resources.
• Supports dynamic and static clients
• Supports attachments including binary file attachments using Message Transmission
Optimization Mechanism (MTOM)
• Supports SOAP and HTTP (Raw XML over HTTP) bindings
• Supports multiple data binding technology
– JAXB
– SAAJ
– XML Source
• Supports both SOAP 1.1 and 1.2
• Supports both message oriented (SOAP) and RPC oriented (REST) web services
• Full integration into JAXB. The bindings (Object Binding declarations) are fully
customizable.
• Provides message handlers (protocol and logical). These handlers can be chained
9 April 2016
18
StAX
• StAX provides a standard, bidirectional pull parser interface for streaming
XML processing.
– Streaming pull parsing refers to a programming model in which a client application
calls methods on an XML parsing library when it needs to interact with an XML
infoset
– Streaming push parsing refers to a programming model in which an XML parser
sends (pushes) XML data to the client as the parser encounters elements in an XML
infoset
• Pull parsing provides several advantages over push parsing when working with XML
streams:
– Pull parsing libraries can be much smaller and the client code to interact with those
libraries are much simpler than with push libraries, even for more complex
documents.
– With pull parsing, the client controls the application thread, and can call methods on
the parser when needed.
• By contrast, with push processing, the parser controls the application thread, and
the client can only accept invocations from the parser.
– Pull clients can read multiple documents at one time with a single thread.
– A StAX pull parser can filter XML documents such that elements unnecessary to the
client can be ignored, and it can support XML views of non-XML data
•.
9 April 2016
19
StAX Vs SAX and DOM
• StAX offers a simpler programming model than SAX and more efficient memory
management than DOM.
Image Source: JAX-WS Tutorial
9 April 2016
20
SAAJ
• SAAJ – SOAP with Attachment API for Java
• Use SAAJ instead of JAX-WS if you need to handle SOAP messages directly in your
application.
• With the SAAJ API, you can create XML messages that conform to the SOAP
1.1 or 1.2 specification and to the WS-I Basic Profile 1.1 specification simply by making
Java API calls.
• SAAJ also provides SOAPConnection object to send and receive SOAP messages as
request-response paradigm.
Image Source: JAX-WS Tutorial
9 April 2016
21
Q&A
9 April 2016
JAVA MESSAGE SERVICE
(JMS) API
9 April 2016
23
Introduction to JMS
• Messaging is a method of communication between software components or applications.
– A messaging system is a peer-to-peer facility: a messaging client can send messages
to, and receive messages from, any other client.
– Each client connects to a messaging agent that provides facilities for creating,
sending, receiving, and reading messages.
• The Java Message Service (JMS) API is a messaging standard that allows application
components based on the Java Platform to create, send, receive, and read messages.
– It enables distributed communication that is
• Loosely coupled – Sender need not be aware about receiver and vice versa
• Reliable - JMS API can ensure that a message is delivered once and only once.
• Asynchronous – The sender and receiver need not be available at the same time to
communicate
– Message-driven beans can be used to consume JMS message asynchronously
– Message sends and receives can participate in Java Transaction API (JTA)
transactions.
– JEE Connector Architecture interfaces that allow JMS implementations from different
vendors to be externally plugged into a JEE application server.
9 April 2016
- 24
-
Messaging – Key Concepts
Concept
Guaranteed Messaging
Description
The message is persisted by MOM (Message Oriented Middleware) and
held till acknowledgement is received from the consumer
Certified Messaging
Guaranteed Messaging + acknowledgment is sent to message producer
The MOM need not to be active. The producer spools the message and
Store and Forward Messaging send it to MOM when it become active
Durable Messaging
In Durable, the subscriber need not be online. The message will be
stored and delivered. This applies only for publish/subscribe model
Non-Durable Messaging
Message Delivery Mode PERSISTENT
Message Delivery Mode –
NON-PERSISTENT
Non-Durable subscriber need to be online. The message will NOT be
stored and delivered
PERSISTENT means that delivery of a message is guaranteed. It will
continue to exist until all subscribers who requested it receive it. The
message is delivered only once.
NON-PERSISTENT delivery means that every reasonable attempt is made
to deliver the message. But in the event of some kind of system failure, the
message may be lost. These messages are delivered at most once.
9 April 2016
- 25
-
Messaging – Key Concepts (Contd..)
Concept
Description
In JMS the transaction is only between Sender and MOM or MOM and
Receiver.
The JMS session can be run in transaction mode.
Transaction
Message acknowledgment
Duplicate messages
If a JMS session is transacted, messages are acknowledged automatically by
the commit mechanism and recovered by the rollback mechanism. If a
session is not transacted, recovery must be handled manually, and messages
are acknowledged in one of three ways:
AUTO_ACKNOWLEDGE: For each message, the session automatically
acknowledges the receipt of the message
CLIENT_ACKNOWLEDGE: Client acknowledges the message by calling the
acknowledge method on the message.
DUPS_OK_ACKNOWLEDGE: Because the session lazily acknowledges the
delivery of messages, duplication of messages may result if the JMS provider
fails.
If MOM/JMS provider does not receive acknowledgement receipt from
receiver. The MOM will resend the message with redelivery flag set. The
application needs to handle duplicate messages
9 April 2016
- 26
-
Message Driven Bean – Key Concepts
• Point to Point Messaging (Queue)
– Each message has only one consumer.
– A sender and a receiver of a message
have no timing dependencies. The receiver can fetch the message whether or not it was
running when the client sent the message.
– The receiver acknowledges the successful processing of a message
• Publish/Subscribe Messaging (Topic)
– Each message can have multiple
consumers.
– Publishers and subscribers have a
timing dependency. A client that
subscribes to a topic can consume only
messages published after the client has
created a subscription, and the
subscriber must continue to be active in order for it to consume messages.
9 April 2016
27
JMS API Architecture
A JMS application is composed of the following parts.
• A JMS provider is a messaging system that implements the JMS interfaces and provides
administrative and control features. An implementation of the J2EE platform at release
1.3 includes a JMS provider.
• JMS clients are the programs or components, written in the JavaTM programming
language, that produce and consume messages.
• Messages are the objects that communicate information between JMS clients.
• Administered objects are preconfigured JMS objects created by an administrator for the
use of clients. The two kinds of administered objects are destinations and connection
factories.
• Native clients are programs that use a messaging product's native client API instead of
the JMS API. An application first created before the JMS API became available and
subsequently modified is likely to include both JMS and native clients.
JMS API Architecture
9 April 2016
- 28
-
Message Consumption
Messaging products are inherently asynchronous in that no fundamental timing
dependency exists between the production and the consumption of a message.
However, the JMS Specification uses this term in a more precise sense.
Messages can be consumed in either of two ways:
• Synchronously. A subscriber or a receiver explicitly fetches the message from the
destination by calling the receive method. The receive method can block until a message
arrives or can time out if a message does not arrive within a specified time limit.
– Use JMS API directly
• Asynchronously. A client can register a message listener with a consumer. A message
listener is similar to an event listener. Whenever a message arrives at the destination, the
JMS provider delivers the message by calling the listener's onMessage method, which
acts on the contents of the message.
– Use Message Driven Beans (MDB)
9 April 2016
- 29
-
When JMS API/Messaging can be used?
• Loosely Coupled
– When the enterprise application provider wants the components not to
depend on information about other components' interfaces, so that
components can be easily replaced.
• Asyncronous
– The provider wants the application to run whether or not all components are
up and running simultaneously.
– The application business model allows a component to send information to
another and continue to operate without receiving an immediate response.
• one-to-many communication. E.g. Broadcasting of stock prices to traders
• Point-to-point communication
• Guaranteed messaging
• Transactional messaging.
• When integration of incompatible systems is necessary.
9 April 2016
- 30
-
JMS API - Example
9 April 2016
31
Sample example – Sending Messages
•Instantiate a Message Queue QueueConnectionFactory administered object.
QueueConnectionFactory myQConnFactory =
new com.sun.messaging.QueueConnectionFactory();
•Create a connection to the message server
QueueConnection myQConn =
myQConnFactory.createQueueConnection();
•Create a session within the connection.
A QueueSession object is a single-threaded context for producing and consuming
messages. It enables clients to create producers and consumers of messages for a
queue destination.
QueueSession myQSess = myQConn.createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
The myQSess object created above is non-transacted and automatically acknowledges
messages upon consumption by a consumer.
9 April 2016
- 32
-
Sample example – Sending Messages (Contd..)
•Instantiate a Message Queue administered object that corresponds to a queue
destination in the message server.
Queue myQueue = new.com.sun.messaging.Queue("world");
•Create a QueueSender message producer
QueueSender myQueueSender = myQSess.createSender(myQueue);
•Create and send a message to the queue.
TextMessage myTextMsg = myQSess.createTextMessage();
myTextMsg.setText("Hello World");
System.out.println(“Sending Message: “ + myTextMsg.getText());
myQueueSender.send(myTextMsg);
9 April 2016
- 33
-
Sample example – Receiving Messages (Contd..)
•Create the Message Sessiona and Queue as shown in the sending messages
example
•Create a QueueReceiver message consumer.
QueueReceiver myQueueReceiver = myQSess.createReceiver(myQueue);
•Start the QueueConnection you created
myQConn.start();
•Receive a message from the queue
Message msg = myQueueReceiver.receive();
•Process the Message
if (msg instanceof TextMessage) {
TextMessage txtMsg = (TextMessage) msg;
System.out.println("Read Message: " + txtMsg.getText());
}
9 April 2016
- 34
-
JAVA CONNECTOR
ARCHITECTURE (JCA)
9 April 2016
35
Java Connector Architecture
• Java EE Connector Architecture (JCA) is a Java-based technology solution for connecting
application servers and enterprise information systems (EIS) as part of enterprise
application integration (EAI) solutions.
• This defines a standard architecture for connecting J2EE compliant applications to
heterogeneous information systems.
• While JDBC is specifically used to connect Java EE applications to databases, JCA is a
more generic architecture for connection to legacy systems (including databases).
9 April 2016
- 36
-
JCA - Contracts
Contract
Lifecycle Management
Description
Handles the lifecycle of the JCA component
Workload Management Threads are managed by App Server. The thread are then allocated to
Resource Adapters on request
(Thread)
Contract between app server and EIS for outbound connectivity
•Connection Management contract for connection pooling
•Transaction Management contract for XA transaction. Local transaction
can be managed by Resource adapter
•Security Management contract authentication and authroization between
App Server and EIS
Outbound Contract
Contract between app server and EIS for inbound connectivity
• Message Contract for inbound messages from EIS. MDB is used for
message handling.
•These message are not JMS messages. It can be custom messages, the
adapter implements the message contract to enable MDB to received
messages
•Transaction Inbound contract to enable EIS to start transaction and
propagate the transaction to app server
Inbound Contract
9 April 2016
37
JCA Interfaces – Common Client Interface
• Common Client Interface is an API for clients to access adapters.
• Example APIs are available
– Connection handling - ConnectionFactory, Connection, ConnectionSpec,
ConnectionEventListener
– Record Handling - Record (MappedRecord. IndexRecord or ResultSet),
RecordFactory
9 April 2016
- 38
-
Choosing between JMS,JCA and Webservice
Characteristics
JMS/MDB
JCA
Integration Style
Relies on Message oriented
middleware
Relies on Vendor provided Implemented as an adapter
resource adaptor
layer
Loose coupling
Tight coupling so mostly
used in business tier
integration
Asynchronous
Synchronous (Some
Async adapters available) Synchronous
Coupling between
components and
resources
Interaction Pattern
Distributed Transaction
Support
Security
MDB can use declarative
transaction features, and
initiate a distributed
transaction
Vendor-specific
Webservice
Loose coupling
Available depending on
the adapter
implementation
The implementation of the web
service endpoint can be
transactional. Additional
transaction features are vendorspecific using WS-Transaction
The resource adapter
implementation allows
transparent integration
Depends on vendor's
implementation of web service
security features for additional
security requirements. (WSSecurity)
9 April 2016
39
Q&A
9 April 2016