Labels

Friday, July 24, 2009

Huy Cận » Ngậm ngùi

Nắng chia nửa bãi; chiều rồi
Vườn hoa trinh nữ xếp đôi lá rầu
Trời buồn con nhện giăng mau
Em ơi hãy ngủ...anh hầu quạt đây

Lòng anh mơ với quạt này
Trăm con chim mộng về bay đầu giường
Ngủ đi em mộng bình thường
Ru em sẵn tiếng thùy dương mấy bờ

Cây dài bóng xế ngẩn ngơ...
Hồn em đã chín mấy mùa thương đau?
Tay anh em hãy tựa đầu
Cho anh nghe nặng trái sầu rụng rơi.

1938 Huy Cận
(Lửa Thiêng)

Thi Sỉ Già!

Mây bay hờ hửng trên trời
Giai nhân vui nhộn sống đời bình yên
Gặp em em nhoẻn miệng cười
Lòng ta vui nhộn cuối đời yêu đương
Em về có nhớ có thương
Có chàng thi sỉ vẩn thường nhớ mong

Tặng em,
T.A. Nguyen
July 24th, 2009

Thursday, July 23, 2009

Má Hồng Giai Nhân!

Đêm Nhớ Ngày Mong Một Má Hồng
Tóc Huyền Tô Điểm Giáng Vai Gầy
Hương Xưa Còn Đọng Nồng Dĩ Vãng
Quân Tử Say Sưa Một Má Hồng

Đã Bao Năm Dài Ta Vẩn Nhớ
Môi Em Cười Thắm Cả Đất Trời
Dáng Em Đi Trẻ Già Say Đắm
Mắt Em Nhìn Ấm Cả Nghìn Sau

   --- o o O o o ---

Ừ, Thì Mai Em Đến Nhé
Đêm Nay Là Đêm Dài Vô Tận
Để Mình Anh Suy Nghỉ Mung Lung
Gặp Em Rồi Biết Nói Gì Đây?

Em Đã Đến Như Lời Hẹn Ước
Hương Xưa Còn Đó Lòng Hoang Dại
Trái Tim Anh Ngở Đã Khô Cằn
Vẩn Còn Rung Động Bóng Giai Nhân

Tặng Em,
T.A. Nguyen
Tuyến Đường Cali (Trái Tim Còn Ở Lại)
July 23rd, 2009

Wednesday, July 22, 2009

Tuyến Đường Nhân Độ

Cám Ơn Em Tiếng Nói Dịu Hiền
Ánh Mắt Suy Tư Cùng Nhân Loại
Nụ Cười Ngây Thơ Sưởi Ấm Đời
Em Nhớ Nhé, Giử Hồn Trong Sáng
Mai Cần Em Chỉ Lối Soi Đường

---- o o O o o -----

Đêm Nay Nghìn Trùng Anh Vửng Bước (1)
Ánh Sao Mai Soi Đường Nhân Độ (2)
Cám Ơn Em Tiếng Nói Dịu Hiền
Văng Vẳng Nhắc Ta Mờ Pha Lê (3)
Tráng Lệ Huy Hoàng Chỉ Danh Vọng
Tâm Khẩu Nhất Thông Giải Muôn Sầu

T.A. Nguyen
Tặng em gái nhỏ,
7/22/2009 - Tuyến Đường Vegas - RDU

B.C.
(1) - Red-eye flight
(2) - Ngắm Sao Mai Trên Máy Bay
(3) - Vegas giờ toàn là giấy!

Tuesday, June 9, 2009

How to create a simple JMS application example using Netbeans and Glassfish

How to create a simple JMS application example using Netbeans and Glassfish

How to create a simple JMS application example using Netbeans 6.7 and GlassFish v2.1

Author: T.A. Nguyen
I am choosing the OLD FASHIONED example to illustrate the concept and also promote the fundamental understanding of JMS. Message Driven beans can easily be done in place of these examples.
Here are the steps:
  • Download and install Netbeans 6.5.1 or later (I use 6.7RC2 for fun)
  • Create an "Enterprise Application Client"
  • Write some codes for the MessageApplication
  • Start-up the GFv2.1
  • Use the GFv2.1 Admin Console to add a ConnectionFactory and a Destination (Queue).
  • Execute the application!

Download and Install Netbeans

Download the latest NetBeans from http://netbeans.org, make sure that you install GlassFish v2.1 as well. We will be using GFv2.1 for the JNDI and MQ services.

Create a "Enterprise Application Client"

  • File -> New Project -> Java EE -> Enterprise Application Client
  • and click [ next > ] button.
  • Project Name: MyFirstJMSQueue
  • Project Location: C:\Projects
  • and click [ next > ] button.
  • Server: GlassFish v2.1
  • Java EE Version: Java EE 5
  • Main Class: org.cnci.jms.first.MessageApp
  • click [ Finish ] button.
   

Write some codes

MessageConnection.java

In practice, I like to encapsulate the Connection, Session and other control to a single class called: MessageConnection. MessageConnection will allow us to: connect(), disconnect(), send() and receive(). Other methods such as getConnection(), getDestination(), getSession(), getConsumer(), getProducer() are extra methods that can use to give developer a finer control.
MessageConnection.ava
//**********************************************************************
//
// MessageConnection
//
//**********************************************************************
//***************************************//
// package //
//***************************************//
package org.cnci.jms.first;

//***************************************//
// imports //
//***************************************//
import javax.jms.*;
import javax.naming.*;

/***********************************************************************
* A simple facade common JMS Connection that will encapsulate and handle
* all the jms connection, session, and message transportation.
*
* @author T.A. Nguyen
* @version 1.0, Jan 1, 2005
***********************************************************************/
public class MessageConnection {

private String destinationName = "jms/myDestination";
private String factoryName = "jms/myConnectionFactory";
private Context context;
private ConnectionFactory connectionFactory;
private Connection connection;
private Session session;
private Destination destination;
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private boolean connected = false;

/********************************************************************
* Constructor
********************************************************************/
public MessageConnection() {
}

/********************************************************************
* Attempts to connect to the JMS messaging system.
*
* @throws MessageException If a connect failure occurs.
********************************************************************/
public Context getContext() throws MessageException {
  if (context == null) {
    try {
      //-------------------------------------
      // Initialize JNDI.
      //-------------------------------------
      context = new InitialContext();
    } catch (NamingException e) {
      disconnect();
      e.printStackTrace();
      throw new MessageException("Naming Exception: " + e);
    }
  }
  return context;
}

/********************************************************************
* Attempts to connect to the JMS messaging system.
*
* @throws MessageException If a connect failure occurs.
********************************************************************/
public MessageConsumer getConsumer() throws MessageException {
  if (messageConsumer == null) {
    try {
    //-------------------------------------
    // Create a message sender.
    //-------------------------------------
      messageConsumer = getSession().createConsumer(getDestination());
      if (!connected) {
        getConnection().start();
        connected = true;
      }
    } catch (JMSException e) {
      disconnect();
      e.printStackTrace();
      throw new MessageException("JMS Create Receiver Exception: " + e);
    }
   }
   return messageConsumer;
}

/********************************************************************
* Attempts to connect to the JMS messaging system.
*
* @throws MessageException If a connect failure occurs.
********************************************************************/
public MessageProducer getProducer() throws MessageException {
  if (messageProducer == null) {
    try {
      //-------------------------------------
      // Create a message sender.
      //-------------------------------------
      messageProducer = getSession().createProducer(getDestination());
      if (!connected) {
        getConnection().start();
        connected = true;
      }
    } catch (JMSException e) {
      disconnect();
      e.printStackTrace();
      throw new MessageException("JMS Create Sender Exception: " + e);
    }
  }
  return messageProducer;
}

/********************************************************************
* Attempts to connect to the JMS messaging system.
*
* @throws MessageException If a connect failure occurs.
********************************************************************/
public ConnectionFactory getConnectionFactory() throws MessageException {
  if (connectionFactory == null) {
    try {
      //------------------------------------------
      // Lookup the connection factory using JNDI.
      //------------------------------------------
      connectionFactory = (ConnectionFactory) getContext().lookup(factoryName);
    } catch (NamingException e) {
      disconnect();
      e.printStackTrace();
      throw new MessageException("Naming Lookup Factory Exception: " + e);
    }
  }
  return connectionFactory;
}

/********************************************************************
* Attempts to connect to the JMS messaging system.
*
* @throws MessageException If a connect failure occurs.
********************************************************************/
public Connection getConnection() throws MessageException {
  if (connection == null) {
    try {
      //-------------------------------------
      // Use the connection factory to create
      // a JMS connection.
      //-------------------------------------
      connection = getConnectionFactory().createConnection();
    } catch (JMSException e) {
      disconnect();
      e.printStackTrace();
      throw new MessageException("JMS Create Queue Connection Exception: " + e);
    }
   }
   return connection;
}

/********************************************************************
* Attempts to connect to the JMS messaging system.
*
* @throws MessageException If a connect failure occurs.
********************************************************************/
public Session getSession() throws MessageException {
  if (session == null) {
    try {
      //-------------------------------------
      // Use the connection to create a
      // session.
      //-------------------------------------
      session = getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);
    } catch (JMSException e) {
      disconnect();
      e.printStackTrace();
      throw new MessageException("JMS Create Session Exception: " + e);
    }
  }
  return session;
}

/********************************************************************
* Attempts to connect to the JMS messaging system.
*
* @throws MessageException If a connect failure occurs.
********************************************************************/
public Destination getDestination() throws MessageException {
  if (destination == null) {
    try {
      //-------------------------------------
      // Lookup the destination (queue) using
      // JNDI. Note that the designated
      // destination (destinationName) must be
      // administered within the JMS service
      // environment.
      //-------------------------------------
      destination = (Destination) getContext().lookup(destinationName);
     } catch (NamingException e) {
       disconnect();
       e.printStackTrace();
       throw new MessageException("Naming Lookup Queue Exception: " + e);
     }
   }
   return destination;
}

/********************************************************************
* Attempts to disconnect from the JMS messaging system.
*
* @throws MessageException If a disconnect failure occurs.
********************************************************************/
public void connect() throws MessageException {
  // make sure a connection and a session established.
  getSession();
  if (!connected) {
    try {
      getConnection().start();
      connected = true;
    } catch (JMSException e) {
      e.printStackTrace();
      connected = false;
      disconnect();
      throw new MessageException("JMS Connection Exception: " + e);
    }
  }
}

/********************************************************************
* Attempts to disconnect from the JMS messaging system.
*
* @throws MessageException If a disconnect failure occurs.
********************************************************************/
public void disconnect() throws MessageException {
  if (connection != null) {
    try {
      connection.close();
   } catch (JMSException e) {
      e.printStackTrace();
      throw new MessageException("JMS Exception: " + e);
   }
  }

  connection = null;
  session = null;
  messageProducer = null;
  messageConsumer = null;

  connected = false;
}

/********************************************************************
* Returns true if a connection is currently established.
********************************************************************/
public boolean isConnected() {
   return connected;
}

/********************************************************************
* Returns true if a connection is currently established.
********************************************************************/
public void send(Message message) throws MessageException {
  try {
    getProducer().send(message);
  } catch (JMSException e) {
    e.printStackTrace();
    throw new MessageException("JMS Send Exception: " + e);
  }
}

/********************************************************************
* Attempts to receive a message.
*
* @throws MessageException If the receive fails.
********************************************************************/
public Message receive(int n) throws MessageException {
  Message message = null;

  try {
    message = getConsumer().receive(n);
  } catch (JMSException e) {
    e.printStackTrace();
    throw new MessageException("JMS Receive Exception: " + e);
  }
  return message;
}
}

MessageException.java

A simple Exception class representing a failure in JMS Message processing.
MessageException.ava
//**********************************************************************
//
// MessageException
//
//**********************************************************************
//***************************************//
// package //
//***************************************//
package org.cnci.jms.first;

//***************************************//
// imports //
//***************************************//
/***********************************************************************
* This class implements an exception representing a failure in
* message processing.
*
* @author T.A. Nguyen
* @version 1.0, Jan 1, 2005
***********************************************************************/
public class MessageException extends Exception {

/********************************************************************
* Constructor.
********************************************************************/
public MessageException() {
  super();
}

/********************************************************************
* Constructor.
*
* @param info Information to be sent along with the exception.
********************************************************************/
public MessageException(String info) {
  super(info);
}
}

MessageSender.java

A simple create and send message class
MessageSender.ava
//**********************************************************************
//
// MessageSender
//
//**********************************************************************
//***************************************//
// package //
//***************************************//
package org.cnci.jms.first;

//***************************************//
// imports //
//***************************************//
import javax.jms.*;

/***********************************************************************
* A simple facade for sending messages in a Point-to-Point domain.
*
* @author T.A. Nguyen
* @version 1.0, Jan 1, 2005
***********************************************************************/
public class MessageSender {
private MessageConnection messageConnection;

/********************************************************************
* Constructor
********************************************************************/
public MessageSender() {
}

/********************************************************************
* Create a MessageConnection
*
* @throws MessageException If the send fails.
********************************************************************/
private MessageConnection getMessageConnection() throws MessageException {
  if (messageConnection == null) {
    messageConnection = new MessageConnection();
  }
  return messageConnection;
}

/********************************************************************
* Attempt to get a QueueSession from the MessageConnection object.
*
* @throws MessageException If the send fails.
********************************************************************/
private Session getSession() throws MessageException {
  if (getMessageConnection() != null) {
    return getMessageConnection().getSession();
  }
  return null;
}

/********************************************************************
* Attempts to send the passed message.
*
* @throws MessageException If the send fails.
********************************************************************/
public void send(Message message) throws MessageException {
  if (message != null) {
    getMessageConnection().send(message);
  }
}

/********************************************************************
* Attempts to establish the connection.
*
* @throws MessageException If the send fails.
********************************************************************/
public void connect() throws MessageException {
  getMessageConnection().getProducer();
}

/********************************************************************
* Attempts to disconnection.
*
* @throws MessageException If the send fails.
********************************************************************/
public void disconnect() throws MessageException {
  if (messageConnection != null) {
    try {
      messageConnection.disconnect();
      messageConnection = null;
    } catch (MessageException e) {
      messageConnection = null;
      e.printStackTrace();
      throw e;
    }
  }
}

/********************************************************************
* Attempts to return a newly constructed TextMessage.
*
* @throws MessageException If the construction fails.
********************************************************************/
public TextMessage createTextMessage() throws MessageException {
  TextMessage message = null;

  try {
    message = getSession().createTextMessage();
  } catch (JMSException e) {
    throw new MessageException("JMS Create Text Message Exception: " + e);
  }
  return message;
}

/********************************************************************
* Attempts to return a newly constructed BytesMessage.
*
* @throws MessageException If the construction fails.
********************************************************************/
public BytesMessage createBytesMessage() throws MessageException {
  BytesMessage message = null;

  try {
    message = getSession().createBytesMessage();
  } catch (JMSException e) {
    throw new MessageException("JMS Create Bytes Exception: " + e);
  }
  return message;
}

/********************************************************************
* Attempts to return a newly constructed ObjectMessage.
*
* @throws MessageException If the construction fails.
********************************************************************/
public ObjectMessage createObjectMessage() throws MessageException {
  ObjectMessage message = null;

  try {
    message = getSession().createObjectMessage();
  } catch (JMSException e) {
    throw new MessageException("JMS Create Object Message Exception: " + e);
  }

  return message;
}

/********************************************************************
* Attempts to return a newly constructed MapMessage.
*
* @throws MessageException If the construction fails.
********************************************************************/
public MapMessage createMapMessage() throws MessageException {
  MapMessage message = null;

  try {
    message = getSession().createMapMessage();
  } catch (JMSException e) {
    throw new MessageException("JMS Create Map Message Exception: " + e);
  }

  return message;
}

/********************************************************************
* Attempts to return a newly constructed StreamMessage.
*
* @throws MessageException If the construction fails.
********************************************************************/
public StreamMessage createStreamMessage() throws MessageException {
  StreamMessage message = null;

  try {
    message = getSession().createStreamMessage();
  } catch (JMSException e) {
    throw new MessageException("JMS Create Stream Message Exception: " + e);
  }

  return message;
}
}

MessageReceiver.java

A simple receive and consume message class
MessageReceiver.ava
//**********************************************************************
//
// MessageReceiver
//
//**********************************************************************
//***************************************//
// package //
//***************************************//
package org.cnci.jms.first;

//***************************************//
// imports //
//***************************************//
import javax.jms.*;

/***********************************************************************
* A simple facade for receiving messages from a PTP domain.
*
* @author T.A. Nguyen
* @version 1.0, Jan 1, 2005
***********************************************************************/
public class MessageReceiver {

private MessageConnection messageConnection;

/********************************************************************
* Constructor
********************************************************************/
public MessageReceiver() {
}

private MessageConnection getMessageConnection() throws MessageException {
  if (messageConnection == null) {
    messageConnection = new MessageConnection();
  }
  return messageConnection;
}

/********************************************************************
* Attempts to receive a message.
*
* @throws MessageException If the receive fails.
********************************************************************/
public Message receive() throws MessageException {
  return getMessageConnection().receive(1);
}

public void connect() throws MessageException {
  getMessageConnection().getConsumer();
}

public void disconnect() throws MessageException {
  if (messageConnection != null) {
    try {
      messageConnection.disconnect();
      messageConnection = null;
    } catch (MessageException e) {
      messageConnection = null;
      e.printStackTrace();
      throw e;
    }
  }
}
}

MessageApp.java

A simple test application for the MessageSender and MessageReceiver classes.

MessageApp.ava
//**********************************************************************
//
// MessageApp
//
//**********************************************************************
//***************************************//
// package //
//***************************************//
package org.cnci.jms.first;

//***************************************//
// imports //
//***************************************//
import javax.jms.*;

/***********************************************************************
* This class provides a test application for the MessageSender and
* MessageReceiver classes.
*
* @author T.A. Nguyen
* @version 1.0, Jan 1, 2005
***********************************************************************/
public class MessageApp {

/********************************************************************
* Application main entry point.
********************************************************************/
public static void main(String[] args) {
  try {
    //--------------------------------
    // Establish sender and receiver
    //--------------------------------
    MessageSender sender = new MessageSender();
    sender.connect();

    MessageReceiver receiver = new MessageReceiver();
    receiver.connect();

    //--------------------------------
    // Create a text message
    //--------------------------------
    TextMessage message = sender.createTextMessage();
    message.setText("This is a test text message");

    //--------------------------------
    // Send the message
    //--------------------------------
    System.out.println("Sending message: " + message.getText());
    sender.send(message);

    //--------------------------------
    // Sleep for a few seconds
    //--------------------------------
    try {
      Thread.sleep(3 * 1000);
    } catch (InterruptedException ex) {
    }

    //--------------------------------
    // Retrieve the message
    //--------------------------------
    TextMessage receivedMessage = (TextMessage) receiver.receive();
    System.out.println("Message received: " + receivedMessage.getText());

    //--------------------------------
    // Terminate connections
    //--------------------------------
    sender.disconnect();
    receiver.disconnect();
  } catch (JMSException jmsEx) {
    System.out.println("JMS Exception: " + jmsEx);
  } catch (MessageException msgEx) {
    System.out.println("Message Exception: " + msgEx);
  }
}
}

Startup GlassFish v2.1

  • From the "Services" tab, right button on the Servers -> "GlassFish v2.1" and "Start" the server.
  • Right button again on "GlassFish v2.1" and click "View Admin Console"
  • Login to the console (admin/adminadmin is the defaul userid/password), If this is on the network, change it.
  • Choose Resources -> JMS Resources -> Connection Factories
  • Click [ New... ] to create a new JMS Connection Factory
  • JNDI Name: jms/myConnectionFactory
  • Resource Type: javax.jms.QueueConnectionFactory
  • Description: My First JMS Queue Connection Test
  • Status: Enabled (checked)
  • Click [ OK ] button
  • ----
  • Choose Resources -> JMS Resources ->Destination Resources
  • Click [ New... ] to create a new JMS Destination Resource
  • JNDI Name: jms/myDestination
  • Physical Destination Name: myDestination
  • Resource Type: javax.jms.Queue
  • Description: My First JMS Queue Test
  • Status: Enabled (checked)
  • Click [ OK ] button.
    

Execute the application:

  • Go back to the project and right button on the MessageApp.java file, then select Run File.

Thursday, May 28, 2009

Java Messaging Services Overview

Java Messaging Services Overview

JMS Overview

Overview:

The Evolution of Software is in the ever changing state.  It is the process of initial development of a software product, followed by its Software maintenance phase.  Fred Brooks, in his key book The Mythical Man-Month, states that over 90% of the costs of a typical system arise in the maintenance phase and that any successful piece of software will inevitably be maintained.  In fact, Agile methods stem from maintenance like activities in and around web-based technologies, where the bulk of the capability comes from frameworks and standards.  Software maintenance address bug fixes and minor enhancements and software evolution focus on adoption and migration. Now, imagine systems where you only have to focus on the business logic and forget about the networking, delivery, and framework...

Distributed Component Era:
Distributed component software make sense when services span across the xxx  we are at the dawn of the age of Distributed Component Software and Messaging Service is one of the building blocks for this new age. 
What attracts developers to JMS?

JMS simply rewrote in Java to arguably much more than message-oriented middleware. As defined in the Sun specification, JMS has different takes on messaging than most message-oriented middleware servers. Instead of requiring either queue-based, point-to-point messaging or topic-based, publish-and-subscribe messaging among application, JMS provides similar but separate APIs for both. One of the main advantages for independent software vendors is that they can drop a set of JMS interfaces onto their existing messaging products without having to alter them drastically. Some of the JMS products will provide both models.

The point-to-point(p2p) domain is analogous to a typical E-mail in-box. The message sender delivers a message to a specified queue, which is accessed at some later time by a message recipient. With publish-and-subscribe, you can create message "topics" to which clients can "subscribe." Take, a trading application that lets an investor track selected stocks, the investor chooses a stock to monitor by subscribing to it. The message broker then adds that investor to a list of recipients it will notify if the price changes.


Then, Sun announced JMS

ChanneLinx.com agreed to take part in the SonicMQ alpha and beta tests on an existing relationship with Progress Software. It had a proof-of-concept application in place, Within a day. "Very quickly, JMS began to change our entire outlook as to what was possible in terms of integration".

"The significance of using Java-based technologies has been far less time spent programming". "Prior to Java, these type of project would have been possible, but not feasible." About 40% of its 1.3 million lines of code was dedicated to managing the infrastructure now handled by Enterprise JavaBeans, JMS, and Workflow, and the platform was not as capable as the ones he is now working on. "Now we can concentrate our talents on doing analysis, not infrastructure."



Java Message Service's(JMS) specification:

    * Java Message Service(JMS) specification v1.0.1 was released in October 1998, by JavaSoft. The JMS is an API for accessing enterprise messaging systems from Java.

    * For sending messages between two or more clients the Java Message Service(JMS) API uses a Java Message Oriented Middleware(MOM) API. JMS is a specification developed by the Java Community.

    * Message Oriented Middleware(MOM) provides a mechanism for integrating applications in a flexible, loosely coupled manner by providing asynchronous data delivery between applications in an indirect way through an intermediary.



What is an Enterprise messaging service?

    *A method for transmitting data from one enterprise application to another "Enterprise messaging" is used. Enterprise messaging eliminates the need to synchronize applications from multiple vendors running on different platforms, this is one of the main advantages. Products such as program-to-program messaging will become increasingly important as corporate IT groups build electronic commerce systems, which typically consist of a loose federation of applications that communicate over the Internet.

    *The Object Management Group(OMG), Microsoft, and Sun's JavaSoft are all working to make Enterprise messaging mechanisms which handle the transmission of messages between systems at different times, through store-and-forward mechanisms, or message queues.

    *The “message” is the common building block of a message. Messages are events, requests, and replies that are created by and delivered to enterprise applications. With specific business meaning messages contain well-formatted data.

    *Compared to the other distributed computing technologies such as Common Object Request Broker Architecture(CORBA) and Component Object Model(COM), Enterprise messaging is not relatively well known. Remote Procedure Call(RPC) architecture are the main background of these models. RPC allows one application to request a service from another application running on another platform. Which means the requesting application must cease running until the data from the other application is received, it is known as "synchronous" operation.

    *According to Ian Brackenbury, an IBM engineer and chief scientist in the company's Hursley Laboratory in Hursley, England. Enterprise messaging, on the other hand, is "asynchronous,". "A messaging infrastructure puts up a queue between an application on Machine One and an application on Machine Two," he says. "It provides the buffer between the different protocols and architectures on either side."

    *That's where the Java Messaging Service(JMS) comes in. JMS describes how to create reliable message queues. Reliable message queues are used to store packages that contain transaction or other information and the procedures used by the queues to exchange these packages.



What is a Java Messaging Service?

    *Java Messaging Service(JMS) is a set of interfaces and associated semantics that define how a JMS client accesses the facilities of an enterprise messaging product. Enterprise messaging is an essential tool for building enterprise applications and E-commerce systems, and JMS provides a common way for Java programs to create, send, receive, and read an enterprise messaging system's messages.

    *The components in an application based on a message service send messages to a message server, rather than communicate directly with each other. The message server, in turn, delivers the messages to the specified recipients.

    *This might seem like an extra, unnecessary layer of software, but the advantages a message service providers often outweigh the disadvantages. The model behind the postal service is much similar to the message service model.

    *We could directly deliver our own mail, but letting someone else do it greatly simplifies our life. But it greatly simplifies the design of both the clients and the servers(they are no longer responsible for handling communications issues), and it greatly enhances scalability by the addition of the messaging service adds another layer to the application.



Goals of the JMS API:

    *A key goal of the JMS API is to minimize the set of concepts a Java programmer must learn in order to use messaging products and to unify the packaging of these capabilities.

    *Supports the development of the heterogeneous applications that span operating systems, platforms, architectures, and the computer languages.

    *Messages that contain XML pages are supported.

    *Supports messages that contain serialized Java objects

    *Provides an API that is suitable for the creation of messages that match the format used by existing, non-JMS applications.



The advantages of Java Message Service:

    *The quality of service issues such as reliable delivery are messaging service's responsibility. This frees the components (which may be custom built) of the application from having to deal with these fairly generic issues.

    *Most of the Enterprise applications reside in multiple platforms. These heterogeneous platforms may receive or submits different types of messages. JMS is purely written in Java. As long the different components could understand the JMS message architecture, the platform which they reside and the programming language they are written is irrelevant.

    *JMS is responsible for delivering and queuing of the messages to the clients. This will free up the servers to process more information.

    *JMS component architecture will let the programmers built software products which are independent of messaging mechanisms. The coupling between the resources of the application will be minimal. This will enhance the reusability of the components and minimize development time for the application.

    *Most of the IT systems undergo heavy modifications and upgrade processes in a very short amount of time. This may result in changes at both the client and the server architectures. This problem of scalability is well addressed by Java Message Service(JMS). Since the messaging mechanism is independent of the application JMS will handle the alterations in the system.



System requirements for Java Message Service:

    *You need an editing environment. In a development context, many people use an integrated development environment(IDE) because it possesses debuggers and other features designed specifically for writing and testing code. This can also be as basic as an operating system editor.

    *You'll need the Java compiler(javac.exe), to compile the programs. You will also need the JMS classes in the package javax.jms and the Java Naming and Directory Interface(JNDI) classes in the package javax.naming. You can download these from Sun's website.

    *You will need access to a vendor implementation of JMS, to execute and test the programs. Most Java 2 Enterprise Edition(J2EE) vendors provide an implementation of JMS. See your vendor documentation for setting up the JMS runtime and executing programs.


Overview to JMS:

        *A method of communication between software components or applications is done by "Messaging".
        *A messaging system is a peer-to-peer facility: A messaging client can send messages to, and receive messages from, any other client known as the server. Each client will have connections to all messaging agents that provide facilities for creating, sending, and receiving messages.

Elements of JMS:

JMS consists of several elements, some of them are listed below with their functionality.

    *JMS provider: An implementation of the JMS interface to a Message Oriented Middleware (MOM). Providers are implemented as either a Java JMS implementation or an adapter to a non-Java MOM.

    *JMS client: A Java-based application or object that produces and/or consumes the messages.

    *JMS consumer: A JMS client that receives messages.

    *JMS message: An object that contains the data being transferred between JMS clients.

    *JMS queue: A staging area that contains messages that have been sent and are waiting to be read. As the named queue suggests, the messages are delivered in the order sent. A message is removed from the queue once it has been read.

    *JMS topic: A distribution mechanism for publishing messages that are delivered to multiple subscribers.



JMS models:

The two models which are supported by JMS API are: point-to-point or queuing model and publish and subscribe model. In the point-to-point or queuing model, the producer posts messages to a particular queue and the consumer read messages from the queue which are posted by a producer. Here, the producer knows the destination of the message(the consumer) and posts the message directly to the consumer's queue.

And the publish/subscribe model supports publishing messages to a particular message topic. In this model, neither the publisher nor the subscriber knows about each other. Zero or more subscribers may register the interest in receiving messages on a particular message topic. A good example for it is "anonymous bulletin board".


Different API's used in JMS are:

The JMS API is provided in the Java package javax.jms package. The different types of interfaces which are used in JMS and their descriptions are listed as below:

    *ConnectionFactory interface: The administered object that a client uses to create a connection to the JMS provider. The code does not need to be changed if the underlying implementation changes, the JMS clients access the connection factory through portable interfaces. Administrators configure the connection factory in the Java Naming and Directory Interface(JNDI) namespace so that JMS clients can look them up. Users will use either a queue connection factory or topic connection factory, depending on the type of message.

    *Connection interface: Once a connection factory is obtained, the connection to a JMS provider can be created. The connection represents a communication link between the application and the messaging server. Connections allow users to create sessions for sending and receiving messages from a queue or topic, depending on the connection type.

    *Destination interface: The administered object that encapsulates the identity of a message destination, which is where the messages are delivered and consumed. It is either a topic or a queue. The users discover them using JNDI, and while JMS administrator creates these objects. Like the connection factory, the administrator can create two types of destinations: queues for Point-to-Point and topics for Publish/Subscribe.

    *MessageConsumer interface: A session creates the object. It receives messages sent to a destination. The consumer can receive messages blocking(synchronously) or non-blocking(asynchronously) for both queue and topic-type messaging.

    *MessageProducer interface: The object created by a session that sends messages to a destination. The user can create a sender to a specific destination or create a generic sender that specifies the destination at the time the message is sent.

    *Message interface: An object that is sent between consumers and producers that are, from one application to another. The message has three main parts: First, a message header (required): Contains operational settings to identify and route messages. Second, a set of message properties (optional): Contains additional properties to support compatibility with other providers or users. It can be used to create custom fields or filters (selectors). Third, A message body (optional): Allows users to create five types of messages (text message, map message, bytes message, stream message, and object message).

    *Session interface: Represents a single-threaded context for sending and receiving messages. A session is single-threaded so that messages are serialized, meaning that messages are received one-by-one in the order sent. The main advantage of a session is that it supports transactions. If the user selects transaction support, the session context holds a group of messages until the transaction is committed, then delivers the messages. Before committing the transaction, the user can cancel the messages using a rollback operation. A session allows users to create message producers to send messages, and message consumers to receive messages.
    
    
HeartBeat with JMS

Heartbeats, a common software construct, are used to verify the continual operation of a specific component or service. With the help of heartbeats, a targeted service continually broadcasts a signal across its environment.
You can assume that your system works normally when your client services can detect a targeted service's heartbeat signals. Meanwhile, if the critical heartbeat signal ceases, each component knows how to react to the critical section.

As a heartbeat example, consider a backend market-price publisher. The publisher publishes real-time prices to other services on the network, as shown in the Figure below. Because a pause in price publishing could indicate either a legitimate market pause or a system problem resulting in stale price information, it's critical that other services receive proper system status information.

To avoid the stales price information, the publisher periodically issues the heartbeat signal to the client's services, keeping them informed of its status. If the heartbeat signal ends, the system customer inquiry module might warn the customer of the stale price information will resume shortly. Until the publisher resumes publishing current prices, meanwhile the application's risk management system would suspend other transactions.


Background of the JMS Heartbeats:

I recently used a similar setup with a series of interdependent components such that, if one failed, the others received notification. I used JMS messaging as a way to transmit heartbeats between components, because the system is employed with JMS (Java Message Service) as a core component. However, i didn't realize the critical nature of the interdependencies, so a proprietary heartbeat, implemented differently each time, supported each relationship at the project's start. Figure below shows the result.

In many systems, developers implement heartbeats using multicast suitable for broadcasting an "I'm still here!" signal, but not necessarily for targeting a specific process or consumer, particularly in high-availability operating systems. However, a JMS-based heartbeat system proves ideal for periodically determining whether the overall system, the network, the JMS server, the JVM, and so on remains in operation.


Resources:

Download the JMS heartbeat framework from here: heartbeat framework 



Developing a Simple Example

Now that you are ready to write your first JMS application because you now know the Message-Oriented Middleware and some JMS concepts. Here we provide a gentle introduction to JMS using the publish-and-subscribe messaging model. You will get your feet wet with JMS and learn some of the basic classes and interfaces.


The JMS Chat Application

    *Internet chat provides an interesting application for learning about the JMS pub/sub messaging model. This is used mostly for entertainment, web-based chat applications can be found on thousands of web sites(Yahoo's Messenger, Google's GTalk and so on).

    *In a chat application, people join virtual chat rooms where they can "chat" with a group of other rooms people.

    *The requirements of Internet chat map neatly onto the publish-and-subscribe messaging model. To illustrate how JMS chat works, we will use the JMS pub/sub API to build a simple chat application.

    *In this model, a producer can send a message to many consumers by delivering the message to a single topic. A message producer is also called a publisher and a message consumer is also called a subscriber

The source code and description for a JMS-based chat application can be found here: The Chat Application



 Java Message Service API

The JMS API is an integral part of the Java 2 Platform, Enterprise Edition. Developed by Sun Microsystems in close cooperation with enterprise
messaging partners, asynchronous communication between components in a distributed computing environment, JMS works together with other technologies to provide reliable. It delivers new, powerful tool for enterprise messaging the cornerstone of today's enterprise applications.


You will find in-depth coverage on how to:

    * Create and run JMS client program.
    * Uses the JMS API with the J2EE platform.
    * Consumes messages asynchronously with a message-driven bean.
    * Produce messages from an application client and from a session bean.
    * Access an entity bean from a message-driven bean.
    * Create applications for the J2EE platform that use the JMS API to Consume messages Produce messages Access an entity bean.


The JMS API Programming Model

The basic building blocks of a JMS application consist of the following elements:

    * Administered objects: connection factories and destinations
    * Connections
    * Sessions
    * Message producers
    * Message consumers
    * Messages.

Wednesday, April 15, 2009

Tiffany Kieu Nhi Nguyen


Tiffany Kieu Nhi Nguyen
For my daughter with love! 

The good Lord blessed us with a baby girl
Inspired by your beauty and smiles
Father, I shall forever be
From the moment I see your face
And day by day, you bring us joy and grace
You are the angel sent to our live

Kieu Nhi is your Vietnamese name
Imprinted in your feature, a proud race
Enriched us with your love and smiley face
Unique, yes, you are one in a million
Nothing can stop or changing your dream
Happiness you should seek and you shall get
I am here right beside you every step of the way

Now that you are turning eleven
Growing up in the technology age
Unravel the myth of yesterday
Your inquiring mind will lead the way
Embrace and learn from our path, your parents
Now and forever, I pray the Lord for thee.

T.A. Nguyen
April 2009