DEVELOPING ENTERPRISE APPLICATIONS USING EJB JAVA MESSAGE SERVICE – JMS MESSAGE DRIVEN BEAN – MDB.

Slides:



Advertisements
Similar presentations
16 Copyright © 2005, Oracle. All rights reserved. Developing Message-Driven Beans.
Advertisements

11 Copyright © 2005, Oracle. All rights reserved. Creating the Business Tier: Enterprise JavaBeans.
Approaches to EJB Replication. Overview J2EE architecture –EJB, components, services Replication –Clustering, container, application Conclusions –Advantages.
An architecture for webb applications, J2EE
A Study in JMS (Java Messaging Service) Chad Beaudin CS 522 Fall Semester 2002.
Java Messaging Services CS-328. Messaging Systems A messaging System allows and promotes the loose coupling of components –allows components to post messages.
Enterprise Applications & Java/J2EE Technologies Dr. Douglas C. Schmidt Professor of EECS.
A Study in JMS (Java Messaging Service) Chad Beaudin CS 522 Fall Semester 2002.
Java Message Service API CSE 487/587 Feb 17, 2005 References: JRun Programmer’s Guide.
The Architecture of Transaction Processing Systems
JMS Java Message Service Instructor Professor: Charles Tappert By Student: Amr Fouda.
ECSE Software Engineering 1I HO 7 © HY 2012 Lecture 7 Publish/Subscribe.
EEC-681/781 Distributed Computing Systems Lecture 6 Wenbing Zhao Department of Electrical and Computer Engineering Cleveland State University
Service Broker Lesson 11. Skills Matrix Service Broker Service Broker, provides a solution to common problems with message delivery and consistency that.
Messaging Technologies Group: Yuzhou Xia Yi Tan Jianxiao Zhai.
Messaging in Java Rafał Witkowski Marek Kałużny.
Java Messaging Services PresentationBy Anurudh Gupta.
Enterprise Java Beans - (EJB)
Java Message Service - What and Why? Bill Kelly, Silvano Maffeis SoftWired AG, Zürich
Client Server Technologies Middleware Technologies Ganesh Panchanathan Alex Verstak.
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
Java Message Service Sangeetha Chavala. What is Messaging? Method of Communication between software components/applications peer-to-peer facility Not.
Enterprise Java Bean Matt. 2 J2EE 3 J2EE Overview.
Introduction to J2EE Architecture Portions by Kunal Mehta.
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
Message-Driven Beans and EJB Security Lesson 4B / Slide 1 of 37 J2EE Server Components Objectives In this lesson, you will learn about: Identify features.
Java Transaction API Sean C. Sullivan
第十四章 J2EE 入门 Introduction What is J2EE ?
J2EE Structure & Definitions Catie Welsh CSE 432
(Business) Process Centric Exchanges
OCT 1 Master of Information System Management Organizational Communications and Distributed Object Technologies Lecture 5: JMS.
Java Messaging Service. An Abstraction for using Messaging Oriented Middleware Purpose is to provide a sophisticated, yet straightforward way to exchange.
1 Java Message Service Манин П Enterprise messaging Key concept: 1. Messages are delivered asynchronously 2. Sender is not required to wait for.
Databases JDBC (Java Database Connectivity) –Thin clients – servlet,JavaServer Pages (JSP) –Thick clients – RMI to remote databases –most recommended way.
Collaborate Lesson 4C / Slide 1 of 22 Collaborate Knowledge Byte In this section, you will learn about: The EJB timer service Message linking in EJB 2.1.
JMS (Java Messaging Service)
Session 7: JMS, JCA, JSF Dr. Nipat Jongsawat.
Assignment of JAVA id : BSSE-F10-M-10-JAVA1 Overview of J2EE/Session 2/Slide 1 of 38.
EJB Overview: Constraint Types and Enforcement in JBoss Elissa Newman Fluid Meeting 6/3/04.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
AMQP, Message Broker Babu Ram Dawadi. overview Why MOM architecture? Messaging broker like RabbitMQ in brief RabbitMQ AMQP – What is it ?
Java Message Service (JMS) Web Apps and Services.
Lecture 4 Mechanisms & Kernel for NOSs. Mechanisms for Network Operating Systems  Network operating systems provide three basic mechanisms that support.
Introduction to EJB. What is an EJB ?  An enterprise java bean is a server-side component that encapsulates the business logic of an application. By.
DEVELOPING ENTERPRISE APPLICATIONS USING EJB
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
Enterprise Java Beans N.V.RAJASEKHAR REDDY. Definition of EJB EJBs are the components that are the set of classes and interfaces deployed within a container.
©NIIT Introducing Enterprise JavaBeans (EJB) Lesson 1A / Slide 1 of 43J2EE Server Components Objectives In this lesson, you will learn about: The features.
EJB Enterprise Java Beans JAVA Enterprise Edition
Java Message Service Introduction to JMS API. JMS provides a common way for Java programs to create, send, receive and read an enterprise messaging system’s.
Module 5: Managing Content. Overview Publishing Content Executing Reports Creating Cached Instances Creating Snapshots and Report History Creating Subscriptions.
September 28, 2010COMS W41561 COMS W4156: Advanced Software Engineering Prof. Gail Kaiser
EJB. Introduction Enterprise Java Beans is a specification for creating server- side scalable, transactional, multi-user secure enterprise-level applications.
Interstage BPM v11.2 1Copyright © 2010 FUJITSU LIMITED INTERSTAGE BPM ARCHITECTURE BPMS.
Slide No. 1 of 111 JMS ( J AVA M ESSAGE S ERVICE ) -Dhananjay Singh.
Enterprise Java Beans. Contents  Understanding EJBs  Practice Section.
Introduction to J2EE Architecture
Java Messaging Service (JMS)
Java Messaging Service (JMS)
Java Messaging Service (JMS)
Understanding and Designing with EJB
Harjutus 3: Aünkroonne hajussüsteemi päring
Inventory of Distributed Computing Concepts
Objectives In this lesson, you will learn to:
Understanding and Designing with EJB
J2EE Lecture 13: JMS and WebSocket
Enterprise Java Beans.
Knowledge Byte In this section, you will learn about:
Objectives In this lesson, you will learn about:
Presentation transcript:

DEVELOPING ENTERPRISE APPLICATIONS USING EJB JAVA MESSAGE SERVICE – JMS MESSAGE DRIVEN BEAN – MDB

CONTENTS JMS Messaging Domain Models JMS API Programming Models/ JMS Object Model Session Beans and JMS Entity Bean and JMS MDB and JMS MDB JMS Development process with NetBeans MDB Development process with NetBeans Workshops Exercises

Enterprise Message System – EMS Message (such as SMS or ) is a data, which is used for communication. Message is used through a middle object (such as MOM or MQ) for sending and receiving the events and data between software component/ application. Provide facilities (synchronous/ asynchronous) for creating, sending, and receiving message. Application A communication Application B by sending a message via the MOM’s application programming interface. Sender Receiver MOM Messages Message Oriented Middleware Or Message Queue

MESSAGE ORIENTED MIDDLEWARE – MOM Apply to a distributed system for sending and receiving message between software components on network. Provide facilities for fault tolerance, load balancing, scalability, and transaction. Use formating message and network protocol in processing.

JMS Its most important purpose was to allow Java applications to access existing message oriented middleware Is a Java-based messaging system that provides the facility of creating, sending, receiving, and reading messages to Java enterprise applications. The JMS API defines a common set of interfaces and associated semantics that allow creation of applications that use JMS to communicate with other applications. Is an object in application server and uses message The JMS API enables communication that is: –Asynchronous JMS service can deliver messages to a client as they arrive. A client does not have to request for messages in order to receive them. –Reliable Ensure that there is no duplicate delivery of messages and no message is missed Ensures one-time delivery, which means that the message will be delivered only once to the recipient

JMS ARCHITECTURE Messages Administered Objects JMS Clients JMS Provider JMS Application Vendor who provides an implementation for JMS specification These are Java applications which are responsible for producing or consuming messages from the JMS Provider Messages are objects that contain the required data for communication between two JMS Clients. These are pre-configured JMS Objects created by an administrator for the use of clients

JMS CLIENT CONNECTS JMS PROVIDER THROUGH JMS API JMS Client (Java Application) JMS API SonicMQ IBM MQSeries IBM MQSeries JBossMQ Messaging Server JMS provider Client tier Messages

JMS PARTICIPANTS The administrative objects are bound to JNDI namespaces using the administration tool provided by the application server. The different parts of JMS interact to form a connection so that messages can be passed between the clients. A JMS client looks up the administered objects in the JNDI namespace and then establishes a logical connection to the same objects using the JMS provider lookup bind logical connection Messaging System / JMS Provider / MOM JNDI Namespace Application Server Administrative Tool Application Client Connection Factory Destination

JMS DOMAIN The ways in which messages could be delivered to recipients (application, components, and users...) There are 2 ways –Point to Point (P2P) –Publish / Subscribe (Pub/Sub)

P2P Is build around the concept of –Message queue: destination – use queues to receive messages from senders and̀ deliver message to receiver or destroy expired message (time out). –Senders: send message to destination –Receivers: receive the message from the queue and processes it (destination deliver messages to receivers) 1:1 Model. FIFO is applied. Acknowledge. Disadvantages: receiver is blocked until the message arrives. Advantages: –High security. –Receiver is not active when sender send message.

P2P (con’t) Client1 Consumer Queue sends acknowledges consumes Message Sender send m1 consumes acknowledges Receiver Destination (Queue) FIFO m1 m2 m3 m4

PUB/ SUB Is build around the concept of –Topic: publish messages to destination. Destination retains message for only as long as it takes to distribute them to current (deliver message copies to) subscribers. –Publisher: send message to Topic. –Subscriber: object to which destination deliver message. 1:n Model (Acknowledge is optional) Topic is virtual channel for consumer receiving message. Message is received depend on the priority of message. There are 2 subscribers: –Durable: receive messages even thought client is not active. The authentication is required. –Non durable: Subscriber must be active in sending message process, otherwise message is lost. Disadvantages: low security Advantages: use in distributed system, multi-users

PUB/SUB (con’t) Client1 Client 2 Topic publishes Delivers Subscribes Message Client 3 Delivers Subscribes Message Destination (Topic) m4 m1 Sender publishes delivers subscribes Receiver delivers subscribes Receiver m2 m1 m3

Messaging Server 2 JMS IN ACTION Coordinate between P2P and Pub/Sub System is constructed into Message Channel Messaging Server 1 Message Channel App # msg App 1 msg

MESSAGE DELIVERY The messaging models support –Synchronous message delivery A subscriber or a receiver explicitly retrieves the message by calling the receive method. The receive method can keep the application in the waiting model until a message arrives or can time out if a message does not arrive within a specified period of time. –Asynchronous message delivery A client can register a message listener with a consumer. A message listener is like an event listener which detects message delivery events. Whenever a message arrives, the JMS provider calls the listener’s onMessage() method which helps in delivering the message.

JMS PROGRAMMING MODEL JNDI Namespace Destination (Queue/Topic) Destination (Queue/Topic) ConnectionFactory Destination (Queue/Topic) Destination (Queue/Topic) lookup create Administered object Administered object Connection create Session create Message MessageConsumer receive / subscribe create MessageProducer send / publish create Client bind connect

DESTINATIONS A client who wishes to send or receive a message needs to be aware of the destination which has been configured by the administrator. The naming convention won’t be the same as in addresses. Ex: The name of the destination could be Are implemented as queue or topic in JBoss. Ex: Destinations are deployed on JBoss with JNDI “queue/testQueue” and “topic/testTopic” Context ctx = new InitialContext();... Queue queue = null; queue = (Queue) ctx.lookup(“queue/testQueue”); Context ctx = new InitialContext();... Topic topic = null; topic = (Topic) ctx.lookup(“topic/testTopic”);

CONNECTION FACTORIES Similar to the concept of DataSource in JDBC In JMS also, an administrator would configure the Connection Factory on the server, so that any application which needs to send or receive message from the MOM can obtain a ready connection from the Connection Factory. 02 interface ConnectionFactory is supported –QueueConnectionFactory –TopicConnectionFactory InitialContext jndiContext=new InitialContext(); QueueConnectionFactory queueConnectionFactory = null; queueConnectionFactory=(QueueConnectionFactory)jndiContext. lookup("QueueConnectionFactory"); hay queueConnectionFactory=(QueueConnectionFactory)jndiContext. lookup("ConnectionFactory"); InitialContext jndiContext=new InitialContext(); TopicConnectionFactory topicConnectionFactory = null; topicConnectionFactory=(TopicConnectionFactory)jndiContext. lookup(“TopicConnectionFactory"); hay topicConnectionFactory=(TopicConnectionFactory)jndiContext. lookup("ConnectionFactory");

CONNECTIONS Is used to represent a virtual connection with JMS Provider Could be an open TCP/IP connection between the client and the provider. Is created from Connection Factory If connection has to be established for sending or receiving message from a queue, then QueueConnection interface is used. Otherwise, TopicConnection interface is used. Whenever an application completes, the close() method is called. QueueConnection queueConnection=null;... queueConnection=queueConnectionFactory.createQueueConnection();... queueConnection.close(); TopicConnection topicConnection=null;... topicConnection=topicConnectionFactory.createTopicConnection();... topicConnection.close();

SESSIONS A Session represents a single-threaded context for sending and receiving messages. Is created from Connections Provide a transactional context in which multiple message sent and received can be treated as a single atomic unit. The session automatically acknowledges message when the destinations have been received successfully There are QueueSession and TopicSession interfaces for queues and topics respectively. QueueSession queueSession=null;... queueSession=queueConnection.createQueueSession(false, queueSession.AUTO_ACKNOWLEDGE); TopicSession topicSession=null;... topicSession=topicConnection.createTopicSession(false, topicSession.AUTO_ACKNOWLEDGE);

MESSAGE PRODUCERS Is created using the session object and is used for sending a message to the destination. If queues are used as destination, then QueueSender interface is used and if topics are being used, then TopicPublisher interface is used. The methods are used send(message) and publish(message) Queue queue=null; QueueSender queueSender=null;... queue=(Queue)jndiContext.lookup("queue/testQueue"); queueSender=queueSession.createSender(queue);... queueSender.send(message); Topic topic=null; TopicPublisher topicPublisher=null;... topic=(Topic)jndiContext.lookup(“topic/testTopic"); topicPublisher=topicSession.createPublisher(topic);... topicPublisher.publish(message);

MESSAGE CONSUMERS Is created using the session object and is used for receiving messages from the destination. There is a QueueReceiver and a TopicSubscriber interface for receiving messages from a queue or a topic respectively. Use receive() method. Queue queue=null; QueueReceiver queueReceiver=null;... queue=(Queue)jndiContext.lookup("queue/testQueue"); queueReceiver=queueSession.createReceiver(queue);... Message msg=queueReceiver.receive(); Topic topic=null; TopicSubscriber topicSubscriber=null;... topic=(Topic)jndiContext.lookup(“topic/testTopic"); topicSubscriber=topicSession.createSubscriber(topic);... Message msg=topicSubscriber.receive();

MESSAGE LISTENERS Provide an asynchronous way for handling incoming messages. Using the poll and the push mechanism which means that the listener automatically receive a notification for an incoming message setMessageListener() method is used to register a listener with the consumer classes. Define onMessage() method in interface MessageListener to receive asynchronous messages QueueReceiver receiver = null; receiver = session.createReceiver(queue);... MyMessageListener listener = new MyMessageListener(); receiver.setMessageListener(listener); … TopicSubscriber subscriber = null; subsriber = session.createSubscriber(topic);... MyMessageListener listener = new MyMessageListener(); subscriber.setMessageListener(listener); …

MESSAGE SELECTORS Provide an expression which can be specified for filtering the messages received by the JMS provider. Disadvantages: A message selector cannot filter messages based on the content of the message body Use Where clause in SQL 92 commands. Ex: String messageSelector="itemName LIKE '%Book' and price='45.0'";

MESSAGE Data type is used to communication between software components/ applications. JMS messages have a specific format and have 3 parts: –Header –Properties (optional) –Body (optional)

MESSAGE HEADER Contains a number of fields that both the JMS clients and providers can use to identify and to route messages A JMS message has a set of predefined keys and value pair data, which the client as well as the provider can use to identify and to relay message. The usage of SMTP as a protocol involves headers, as is also true for HTTP The value for the commonly known headers like TO, From, CC, BCC, Subject, is specified along with the actual message body. Every message sent has a unique identifier which is known as JMSMessageID header field. Header FieldsDescription JMS DestinationDetermine a destination store messages JMSDeliveryModeDetermine a mode delivered message to consumers JMSExpirationThe life cycle of message on destination JMSPriorityPriority of message in deliver process. JMSMessageIDA unique identifier of Message JMSTimestampThe sending time of message JMSCorrelationID A identifier message correlate with current message (Ex: message A is replied from message B) JMSReplyToA responsing mode JMSTypeA message structure. JMSRedeliveredDetermine message delivered over once times

MESSAGE PROPERTIES Optional The parameters required by a message are specified using message properties Provide compatibility with other messaging systems and also creating message selectors All message properties are pre-fixed with JMS Message properties include Name & Value Some predefined properties are included in the JMS API. All the header fields such as JMSMessageID and JMSDestination are instances of message properties can use either predefined properties or user-defined properties in your JMS application Developer can define message properties using methods like setStringProperty(), setDoubleProperty(), and setShortProperty() of javax.jms.Message interface

MESSAGE BODY Optional Contain the actual content of the message The contents of the message in different formats TypesDescriptions TextMessage For sending data in form of a text. Ex TextMessage message = session.createTextMessage(); message.setText("Hello"); MapMessage Sending data in the form of key, value pairs. Storage Data is similar to ResultSet. Ex MapMessage msg=null; msg=topicSession.createMapMessage(); msg.setString("studentId", "987"); BytesMessageSending binary data StreamMessageSending Java primitives as a stream of values ObjectMessageSending a Serializable Java Object as a message Message Sending a message with only JMS headers and properties with no body associated with it.

EXCEPTION HANDLING The root class for JMS exceptions is javax.jms.JMSException ExceptionsDescriptions InvalidSelectorException Is thrown when a JMS al attempts use a message selector with invalid syntax. JMSSecurityException Is thrown when a JMS provider does not recognize the client’s name/password or security restrictions prevent a method from completing. ResourceAllocationException Is thrown when a provider is unable to allocate the resources required by a method. MessageEOFException Is thrown when an unexpected end of stream is reached when a message of type StreamMessage or BytesMessage is being read. MessageFormatException Is thrown when a JMS client attempts to use a data type not supported by a message or attempts to read data of wrong type in a message. MessageNotReadableException Is thrown when a JMS client attempts to read a write-only message. MessageNotWriteableException Is thrown when a JMS client attempts to write a read-only message. TransactionInProgressException Is thrown when an operation is invalid because a transaction is in progress. TransactionRolledBackExceptionIs thrown when the current transaction rolls back.

DURABLE SUBSCRIPTIONS Whenever a topic is configured on a JMS server, all the messages published to the topic would be retained only for the duration of availability of the subscriber. A durable subscription can have only active subscriber at a time The createDurableSubcriber() method in TopicSession interface is used to created a durable subscriber A JMS provider may provide a capability to configure a durable subscription as an administered object.

TRANSACTION In JMS transaction, if a single messages process fails, there can be a need to abort the complete process. The interface javax.jms.Session defines commit() and rollback() method to control transaction boundaries. The createQueueSession() or createTopicSession() method check whether all the messages which will be sent or received will be transacted or not. QueueSession queueSession=null;... queueSession=queueConnection.createQueueSession(false, queueSession.AUTO_ACKNOWLEDGE); A boolean value of true means that all the messages will be sent only if the commit() method will be called.

TRANSACTION (cont) Sender –Till the commit() method is not called, all the messages are not immediately sent to destination, but are buffered in an internal memory buffer. (means that the message is sent to destination when session invokes commit() method.) –JMS supports multi – transaction. –As soon as the commit() or rollback() invocation completes, it signifies the end of one transaction. Receiver: –The commit method is set default in delivering message. –If the receiver needs to rollback the transaction, then all the messages that were received within the current transaction will be thrown back into the destination and JMSRedelivered property is set for processing message. The grouping of sending and receiving multiple messages within a JMS Session using the methods provided by JMS API is called local transactions. Whenever a JMS session is a part of an existing transaction which already has been started, the parameter value is passed as false.

TRANSACTION (cont) Client RDBMS Application Server API Trans- action Java Mainframe / ERP MOM / MQ JMS JDBC JCA Servlets / JSP EJB J2EE includes support for JTA which allows developers control on the transaction boundaries within the code. javax.transaction.UserTransaction interface is used to manage transaction

MESSAGE ACKNOWLEDGED Until a JMS message has been acknowledged, it is not considered to be successfully consumed. For the successful comsumption of a message, a client need to ……………… In transacted session, acknowledge happen automatically when a transaction is commited. In non-transacted session, message acknowledge depend on the value of the second parameter pass to the createQueueSession() or createTopicSession() method.

MESSAGE ACKNOWLEDGE MODES AUTO_ACKNOWLEDGE –JMS session is responsible for automatically acknowledging the message received –Acknowledge synchronous after the receive() method call or asynchronous after the onMessagẹ() callback method call. CLIENT_ACKNOWLEDGE –JMS Client is responsible for manually acknowledging the message using the acknowledge() method after sucessfully consuming the message. –Acknowleding even a single message in the session causes all the messages to be acknowledged automatically. DUPS_OK_ACKNOWLEDGE: –The JMS session can lazily acknowledge for message after they are consumed. (The consumer can tolerate duplicate message)

SESSION BEANS & JMS Session Beans as Message Producer –A session bean can send messages using an object of javax.jms.MessageProducer interface, which is the parent interface for all message producers javax.jms.TopicPublisher objects javax.jms.QueueSender objects. Session Beans as Message Receiver –A session can also receive messages or acts as a message consumer. –However, a session bean cannot directly receive a message on its own. To receive a message, the message receiving code is added to a business method, which is called by a client to start receiving the message. –To create a session bean message consumer, needing to create a business method that declares an object of QueueReceiver or TopicSubscriber interfaces. –Then, call the receive() method on either of these objects. Limitations –The session bean consumer can only work in synchronous mode –The bean reaches the message receiving stage, it stops execution and starts waiting for a message to arrive –Avoid using a session bean in a production environment, where a bottleneck like this would have an adverse effect on the overall working of the application

ENTITY BEANS & JMS Messaging capabilities of an entity bean is very similar to session beans. Entity beans can work as both message consumer and synchronous message producer. Entity beans can send messages using javax.jms.MessageProducer, javax.jms.TopicPublisher, or javax.jms.QueueSender objects. Entity beans can receives messages using the synchronous receive() method of the javax.jms.MessageConsumer interface. The receive() method can be specified the timeout value or use receiveNoWait() method that receives the available message and does not wait. Limitations –The entity bean consumers are not recommended in a J2EE application because of its blocking nature –Should instead opt for a message-driven bean if wanting a bean consumes a message

MDB & JMS MDB are designed to be message consumers in a J2EE application. To receive messages, a MDB must implement a Message Listener with the onMessage() method (callback method) contains the code that are executed when a message arrives. The MDB can send messages. Even though its strength lies in being a consumer, it can also send messages to other messaging components. Messages can be sent from a MDB by declaring objects of javax.jms.MessageProducer, javax.jms.TopicPublisher, or javax.jms.QueueSender interfaces, and then calling the send() method Limitations –MDB works only in asynchronous mode –MDB cannot be invoked without a JMS message, they are more suited as message consumers than as message producers –MDB can send messages, but only after being invoked by an incoming message –MDB are currently designed to map to only a single queue or topic. –MDB can only listen for messages on that destination only

MDB Introduced in EJB 2.0 An enterprise bean that allows to process messages asynchronously. Normally acts as a JMS message listener, which is similar to an event listener except that it receives JMS messages instead of events. The messages can be sent by any J2EE component such as an application client, another enterprise bean, or a web component, or by a JMS application or system that does not use J2EE technology. MDB can process either JMS messages or other kinds of messages. Similar to other enterprise beans, which deployed on an EJB container before they can be used. All the container services such as resource handling, transaction management, and security are also available to the MDB.

JMS & MDB JMS has been part of J2EE since 1999, MDB were introduced in 2001 with EJB 2.0. Before MDB, the JMS message consumers were built as simple java program. MDB allows JMS applications to receive messages asynchronously (the sender is independent of the receiver receiving and processing the messages). Building these message consumers was difficult task. These message consumers had to include code for handling issues, such as scalability, resource management, transactions, and security in a multithreaded environments. If the message load grew, multiple consumers had to be created so that the messages were not lost. Then, an additional program had to be written to manage multiple consumers.

CHARACTERISTICS of MDB Execute upon receipt of a single client message. Invoked asynchronously. Relatively short-lived. Don’t represent directly shared data in the database, but they can access and update data. Can be transaction-aware. Do not have a home interface or a component. Are similar to the stateless session bean

IMPLEMENT of MDB MDB Components –MDB bean class It must mainly implements two interfaces –The javax.ejb.MessageDrivenBean interface –The javax.jms.MessageListener interface. Must implement the callback methods –ejbCreate, ejbRemove, setMessageDrivenBeanContext (the javax.ejb.MessageDrivenContext is used) –onMessage(javax.jms.Message): implement the main business-logic and bean executes upon receipt of a message Must declare a constructor Must not be declared as final or abstract Must not implement the finalize method –Deployment Descriptor Decribe the connection between JMS Destination and MDB Processing the Messages Inform the container about the bean class. MDB connects JMS destination, which is middle object, to store Message

LIFE CYCLE Network EJB Container/Server Msg Listener Message Driven Bean Handler Logic Start Pooled onMessage() ejbRemove() ejbCreate() Init instance setMessageDrivenContext() Timeout Client pass msg Client Msg Producer Msg API Messaging Service Message Queue EJB Pool

MDB DEVELOPMENT PROCESS Step 1: create Message Driven Bean –implements javax.jms.MessageListener, javax.ejb.MessageDrivenBean –Constructor without parameters –Implement the Callback methods –The classes and methods must declare public Step 2: create Deployment Descriptor –jboss.xml ejb name destination name

MDB DEVELOPMENT PROCESS (cont) Step 2: create Deployment Descriptor (con’t) –ejb-jar.xml ejb name MDB class Container SQL statement – Where clause msg datatype NonDurable Auto-acknowledge

MDB DEVELOPMENT PROCESS (cont) Step 3: make jar file & deploy Step 4: create Client object using MDB –Set enviroments, JNDI & Naming –Lookup JMS Destination –Send message to Destination (Destination delivery to MDB) –close JMS connection.

JMS DEVELOPMENT PROCESS in NETBEANS Requirement: JBoss GA Application Server must be running Step 1: Creating Application using JMS API to send/publish or receive/subscriber message from/to JMS Destination Step 2: Creating references to Application Server. Step 3: Running the client to test the JMS client Supporting library: concurrent.jar, jbossmq- client.jar, jboss-common-client.jar, jboss-system- client.jar, jnp-client.jar (located at the JBOSS_HOME/client directory)

Step 1: create Application and JMS Client P2P – Sender

Step 1: create Application and JMS Client P2P – Receiver

P2P EXECUTING Case 1 –Run Sender to send message to Queue. –Then, run Receiver to receive message (→receive sent message) –Then, run Receiver again. Pay attention the receiver in this running (→ receiver waiting to receive because the Destination has no message) Case 2 –Run Receiver –Then run Sender (→ receiver receive message immediately)

Step 1: create Application and JMS Client PubSub – Publisher

Step 1: create Application and JMS Client PubSub – Subscriber

Step 1: create Application and JMS Client PubSub – Subscriber (cont)

PubSub EXECUTING Case 1 –Run Publisher to send message to Topic. –Then, run Subscriber (→ cannot receive message because the listener is not activated) Case 2 –Run Subscriber –Then run Publisher (→ receive sent message)

Step 1: create Application and JMS Client PubSub – Durable Subscriber

PubSub Durable EXECUTING Run Publisher to send message to Topic. Then, run Durable Subscriber (→ Receive message from destination because the Durable Subscriber with authentication allows to do this without the Listener not to be activated)

Step 1: create Application and JMS Client Sender Transaction – Sender

Step 1: create Application and JMS Client Sender Transaction – Receiver

Sender Transaction EXECUTING Case 1 –Run sender with the commit() statement in the last –Run receiver (→ get two message from the destination) Case 2 –Run sender without both the rollback() and the commit() statement –Run receiver (→ not get message because the transaction is not commit, the message is on the buffer) –Run new sender with the commit() statement (new transaction) in the last (→ get the message, means that the transaction can be created new one without the current transaction has been finished yet) Case 3 –Run sender with the rollback() statement at the first message and the commit in the second message –Run receiver (→ receive only message 2)

Step 1: create Application and JMS Client Receiver Transaction – Sender

Step 1: create Application and JMS Client Receiver Transaction – Receiver

Receiver Transaction EXECUTING Case 1 –Run sender –Run receiver without the commit() and the rollback() statement (→ get two message from the destination because the default of destination is always commit) Case 2 –Run sender –Run receiver with the rollback() statement at the receive first message and without if(!message.getJMSRedelivered()) statement (→ get the message in order 1 st – 1 st – 2 nd, the 1 st message redeliver to destination at the its position before delivering) Case 3 –Run sender –Run receiver with the rollback() statement at the receive first message and if(!message.getJMSRedelivered()) statement (→ get the message in order 1 st – 2 nd because the JMSRedelivered supports to reject the message receive twice)

MDB DEVELOPMENT PROCESS in NETBEANS Requirement: JBoss GA Application Server Step 1: Creating a new EJB Module project Step 2: Creating the new MDB, then building/ Modifying the business/callback methods on Beans. Step 3: Mapping the JNDI to beans and Modifying Deployment Descriptor Step 4: Building the project to jar file Step 5: Deploying the project on Application server Step 6: Creating the client application to consume Step 7: Running the client to test the MDB

Step 2: Creating a MDB Choose the Enterprise in the Categories Choose the “Message-Driven Bean” in “File Types” Click Next Button

Step 2: Creating a MDB (cont) Fill your bean name Choose the appropriate destination Click Finish Button

Step 2: Create MDB Bean (con’t) Client Public Message Topic deliver Message MDB onMessage()

Step 3: Mapping JNDI and Modifying DD Delete all the activation config property exception the configure to acknowledgeMode

Step 3: Creating client to consume

Step 5, 6, 7: Building, Deploying, and Testing Building the jar file and deploying to Application Server → Application Server do not present the binding with the MDB Bean because we mapped to the destination JNDI Running the application client, the message is consumed on the Application Server

Combination the Session Bean and MDB Client Public Message Topic deliver Message MDB onMessage() input Stateless doWork()

Step 3: Creating Bean Create Stateless Session Bean Create business method doWorks as following

Step 2: Create Bean MDB

Step 3: Mapping the JNDI and Modifying DD

Step 5, 6, 7: Building, Deploying, and Testing Building the jar file and deploying to Application Server Running the application client, the message is consumed on the Application Server

WORKSHOP ACTIVITIES Building the JMS to send/publish and receive/ consume message on Java Sun Application Server Using Queue (P2P) Using Topic (Pub/Sub) Combine MDB, SessionBean with JMS

WORKSHOP ACTIVITIES (cont) Building the EJB with MDB on Java Sun Application Server Using Queue Using Topic

EXERCISES Do it again all of demos, workshops, and the following exercises on JBoss Server Do it MDB, Stateless Session Bean use Web Application with passing username & password parameter on message and check validation on Session Bean (use DB) (Java Application & web)