Handwritten Text Recognition for manuscripts and early printed texts
Java message service
1. Java Message Service – Quick learn (hopefully)
Veeramani S
vee.sam@live.com
Messaging ?
Messaging is one of the well known methods to integrate (communicate) two software components
(applications).
Major Benefits?
Asynchronous : Either of the parties (sender or receiver) need not be available at the same time. I.e.
sender can send a message as if the receiver is ready and waiting for the message even though actual
receiver is not active at the time of message sending. (Please note synchronous also possible)
Reliable : Possible to make sure that one message is delivered once and only once. (E.g. A refund
request to the customer should not processed more than one time)
How ?
Every message sent using JMS will be first received by the JMS Queue or Topic and will be available till
the appropriate client consumes the message.
JMS -API?
JMS is JAVA API helps JAVA developers quickly build application with a capable of create, send or
receive message from/to any other application.
Let us have some closer look:
Terminologies :
JMS Provider : Any vendor who is implementing the JMS API specification
JMS Client : Any Java application that creates, sends or receives messages using JMS implementation.
Message : is object from JMS family used to communicate between JMS clients.
Administered objects: Before stating our actual game there should be some infrastructure and
commonly agreed terms for the involved parties. (Destinations and connection factories)
1
2. A small story now:
Figure 1 fictional scenario to depict asynchronous messaging and application integration using messaging
Some discussion and clarification from hamazzzon.com story
1. Should the message server need not to be a standalone always?
a. No it can be a part of hamazzzon.com application server or Fulfillment vendor
application server also.
2. How long a message can wait in the message server?
a. Administrator of the server can configure, default is 0 which means never expires till the
message is consumed by a client
3. Can the same message be available after delivery to the Fulfillment vendor application?
a. No, Strictly no dupes. Once and only once message will be delivered to the client.
4. How long a message can wait in the message server?
a. Queues retain all messages sent to them until the messages are consumed or until the
messages expire
b. Administrator of the server can configure the expiry time, default is 0 which means
never expires till the message is consumed by a client.
5. What happens if there is an exception?
a. When an exception occurs while the message consumption
message it will be marked as unread in the message server
and will be ready to send for the next message lookup
request.
b. Also please note that it is possible to configure after certain
number of attempts delivery failed message can be moved
2
3. to another message (so that hamazzzon can take a look on to it to fix and resend) or
deleted permanently (in our story it is not wise)
6. How the message server determines that the message is consumed successfully by the client?
a. Using the message acknowledge status. We will more about with sample code some
time later.
7. Is it possible to include other operation in the same consume call and make it as a single
transaction (For example vendor wants to update a database)?
a. YES it is possible transaction support can be extended for this scenario
8. Is it possible to make the message sender to wait until a message consuming client pick up the
message?
a. YES it is possible through ACKNOWLWDGE_MODE setting (then it would turn as
synchronous* call)
LITTLE more concepts before we start our ROCKING code!
In ancient days most of the MOM(Message Oriented Middleware) or messaging providers support one
of the following category but after the period JMS birth, most(all !) of the messaging providers started
supporting both in single product
Point-to-Point
In this approach single message can be consumed by a single client. Consider our fulfillment story which
is really a point-to-point example, even if our hamazzzon.com has more than one fulfillment vendor only
one of the vendor can/should do the fulfillment.
In JMS call this approached message destination as Queue
Figure 2 Point-to-Point (Queue)
Publisher Subscriber
In this approach single message can be consumed by more than one client. Consider RBI (central bank)
wants to send new rate of interest tariff to all the participant banks the same message has to be
processed by all the banks subscribed.
In JMS call this approached message destination as Topic
3
4. Figure 3 Publisher Subscriber (Topic)
Some discussion from these concepts:
1. If there is more than one message consumption clients in what order message delivered to
client?
a. Whoever first calls the receive message method will the chance to consume
b. However ordering can be defined in the message level so that server can decide which
message should be delivered first.
2. Will all the consumer clients in the topic always get the message published in the Topic?
a. NO. Only the clients online at the time of message publish will the chance to consume
it.
b. YES. By marking as durable consumer we can provide the capability to receive messages
published while the consumer was not active. However this messages are limited from
the time since durable consumer of a topic created
3. Is it guarantee that message every will be consumed at least once by its
client in topic?
a. No, for example if a topic has all non durable consumers and none
of them active at the time of message publish then the message
will not be processed by any client
4. Now it might sound little late question nevertheless, what actually I can
send using JMS?
a. TextMessage, MapMessage, BytesMessage, StreamMessage and
ObjectMessage
If you are not familiar with Administered objects configuration steps, you
can get familiar using Weblogic server sample explained in this link.
4
5. Where is my code!
Figure 4 JMS programming model
5
6. Message producer/sender client
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* @author sv
*
*/
public class TestJmsMessageSender {
public static void main(String[] args) {
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination dest = null;
/*
* Setting environment property, this should be ideally come form
* properties files and should be set through HashMap, But it is
* OK for our test run
*/
System.setProperty("java.naming.factory.initial",
"weblogic.jndi.WLInitialContextFactory");
System.setProperty("java.naming.provider.url",
"t3://localhost:7001");
try {
jndiContext = new InitialContext();
connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/TestJmsConnectionFactory");
dest = (Destination)
jndiContext.lookup("jms/TestJmsQueue");
/*
* Create connection. Create session from connection; false
means
* session is not transacted.
*/
connection = connectionFactory.createConnection();
6
8. public static void main(String[] args) {
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination dest = null;
/*
* Setting environment property
*/
System.setProperty("java.naming.factory.initial",
"weblogic.jndi.WLInitialContextFactory");
System.setProperty("java.naming.provider.url",
"t3://localhost:7001");
try {
jndiContext = new InitialContext();
connectionFactory = (QueueConnectionFactory)
jndiContext.lookup("jms/TestJmsConnectionFactory");
dest = (Queue) jndiContext.lookup("jms/TestJmsQueue");
/*
* Create connection. Create session from connection; false
means
* session is not transacted. Create sender and text
message. Send
* messages, varying text slightly. Finally, close
connection.
*/
connection = connectionFactory.createConnection();
session =
connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
connection.start();
MessageConsumer consumer = session.createConsumer(dest);
TextMessage message = (TextMessage)
consumer.receive(1000);
System.out.println(message.getText());
message = (TextMessage) consumer.receive(1000);
System.out.println(message.getText());
message.acknowledge();
//queueSession.commit();
} catch (NamingException e) {
e.printStackTrace();
System.exit(1);
}
catch (JMSException e) {
8
9. System.out.println("Exception occurred: " + e.toString());
}
catch(Exception e){
e.printStackTrace();
}
finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}
/! Trap zone :
1. Any acknowledge mode will be ignored if the transaction is enable in a session
For example in the following code transaction flag is set as “true” hence whatever
acknowledgement mode provided here will be ignored and set as “AUTO_ACKNOWLEDGE”,
if the transaction succeeds then message will get automatically acknowledge ( using which
means server will determine whether to remove the message or to redeliver).
QueueSession queueSession createQueueSession(true,Session.
CLIENT_ACKNOWLEDGE);
2. UserTransaction handling is allowed only for the MDBs configured as Bean-managed
transactions
a. For example messageDrivenContext.getUserTransaction().begin() will throw an
exception if it called from a MDB which is configured as Container transitioned
3. MessageDrivenContext’s setRollbackOnly() would cause the server to re-deliver the message
again. However this is legal only if the provider(connection factory) is XA transaction enabled
4. MDB acknowledge mode can either “Auto-Acknowledge” or “DUPS_OK_ACKNOWLEDGE” any
other mode is not allowed
5. Throwing an exception in the onMessage() method of MDB make the server to re-deliver the
message again
6. Security is depends on the provider and it’s a architectural decision.
Exercise :
Set a Topic in your application server and try a similar program
Try to set up MDB and consume message send from a producer.
In case of any clarification please contact me though my email, I will try to resolve.
9