19 october 2015 integration and messaging -jagadeesh
TRANSCRIPT
April 21, 2023
Integration and Messaging
-Jagadeesh
April 21, 2023
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
2
April 21, 2023 3
Web Services
Web service Introduction JAX-WS Introduction Creating Webservice Consuming Webservice Message Handlers JAXB Web Service Bindings WS-* Specification Stax and SAAJ
April 21, 2023
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
4
April 21, 2023
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
April 21, 2023
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.
6
April 21, 2023
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 + ".";
}
}
7
April 21, 2023
Deploying Webservices – IDE and App Server dependencies
8
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
April 21, 2023
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 21, 2023
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();
}
10
April 21, 2023
Dynamic Proxy Client• Dynamic Proxy APIs
– Dynamic Proxy client is similar to the stub client in the Java API for XML-based RPC (JAX-RPC) 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();
11
April 21, 2023
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.
12
April 21, 2023
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
13
April 21, 2023
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
14
RPC/encoded RPC/Literal Document/encoded Document/Literal Document/Literal Wrapped
Example
<soap:envelope> <soap:body> <myMethod> <x xsi:type="xsd:int">5</x> <y xsi:type="xsd:float">5.0</y> </myMethod> </soap:body></soap:envelope>
<soap:envelope> <soap:body> <myMethod> <x>5</x> <y>5.0</y> </myMethod> </soap:body></soap:envelope>
<soap:envelope> <soap:body><xElement>5</xElement> <yElement>5.0</yElement> </soap:body></soap:envelope>
<soap:envelope> <soap:body> <myMethod> <x>5</x> <y>5.0</y> </myMethod> </soap:body></soap:envelope>
Operation Name Present in XML Present in XML Not present Present in XML
PerformanceOverheads due to xsi:type, Xsi:int etc Better Preformance Better Performance Better Performance
WS-I Complaint No Yes Partial YesWSDL Complexity Simple Simple Average Complex
Validation against Schema
Difficult. Since method names are not defined in schema
Difficult. Since method names are not defined in schema
Can Validate. Everything in soap:body is defined in schema
Can Validate. Everything in soap:body is defined in schema
No one follows this style
April 21, 2023
WS-* Specifications
15
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 toenable transacted operations as part of Web service message exchanges
WS-Addressing describes how to specify identification and addressing information for messages
WS-* specifications describes how to attach additional capabilities to the SOAP messages
April 21, 2023
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.16
Image Source: JAX-WS Tutorial
April 21, 2023
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
17
Image Source: JAX-WS Website
April 21, 2023
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
18
April 21, 2023
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
• .
19
April 21, 2023
StAX Vs SAX and DOM• StAX offers a simpler programming model than SAX and more efficient memory
management than DOM.
20
Image Source: JAX-WS Tutorial
April 21, 2023
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.
21
Image Source: JAX-WS Tutorial
April 21, 2023
Q&A
April 21, 2023
JAVA MESSAGE SERVICE (JMS) API
23
April 21, 2023 - 24
-
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.
April 21, 2023 - 25
-
Messaging – Key Concepts
Concept Description
Guaranteed MessagingThe 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
Store and Forward MessagingThe MOM need not to be active. The producer spools the message and 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 MessagingNon-Durable subscriber need to be online. The message will NOT be stored and delivered
Message Delivery Mode - PERSISTENT
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.
Message Delivery Mode – NON-PERSISTENT
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.
April 21, 2023 - 26
-
Messaging – Key Concepts (Contd..)
Concept Description
Transaction
In JMS the transaction is only between Sender and MOM or MOM and Receiver.
The JMS session can be run in transaction mode.
Message acknowledgment
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 messageCLIENT_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.
Duplicate messages 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
April 21, 2023 27
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.
April 21, 2023 - 28
-
JMS API Architecture
• 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.
A JMS application is composed of the following parts.
JMS API Architecture
April 21, 2023 - 29
-
Message Consumption
• 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)
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:
April 21, 2023 - 30
-
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.
April 21, 2023
JMS API - Example
31
April 21, 2023 - 32
-
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.
April 21, 2023 - 33
-
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);
April 21, 2023 - 34
-
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()); }
April 21, 2023
JAVA CONNECTOR ARCHITECTURE (JCA)
35
April 21, 2023 - 36
-
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).
April 21, 2023
JCA - Contracts
37
Contract Description
Lifecycle ManagementHandles the lifecycle of the JCA component
Workload Management (Thread)
Threads are managed by App Server. The thread are then allocated to Resource Adapters on request
Outbound Contract
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
Inbound 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
April 21, 2023 - 38
-
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
April 21, 2023
Choosing between JMS,JCA and Webservice
39
April 21, 2023
Q&A