Skip to main content

Step by Step toward a jms sample in NetBeans and yes GlassFish

Posted by kalali on May 5, 2006 at 6:40 AM PDT

Java EE 5 brings many ease of use in EJB development world and certainly it is one of biggest step ahead in java EE land.
NetBeans 5.5 is another big step toward making development on top Java EE some easier. NetBeans is a very easy to learn and use because it does not bring many stuff on the screen to "Occupy all the space" instead it provide maximum useability by means of limited number of views.
GlassFish as Reference implementation of JAVA EE 5 , provide you with all service that are named in java EE spec but it is not similar to older RI version of J2EE ,just remember J2EE 1.3 RI
it is much more better in term of functionality, performance, ease of use and ...
here I will tell you steps that you need to follow to build a simple MDB , a web based message producer and a remote message producer.

when you follow this entry you will be able to deal with basic aspect of JMS in Action and not only on your papers. but what do we need to have our JMS application running ?

  • A JMS implementation that is configured with our server , it can be done using embedded servers that are shipped with application servers or using remote / local MQ servers.
    GlassFish uses Sun message Queue , which is going to be available under the same license that GlassFish is provided. You can find more information about open source version at : http://mq.dev.java.net
  • You also need to setup a Queue and a connection factory in your application server.*
  • you should Create an MDB , and then implement the onMessage() method in way that you like.

*I should tell you that you can create your Queue and connection factory in many ways , yes more than two ways .

  • use GlassFish server web based administration console
  • use GlassFish command line console
  • using NetBeans 5.5 , yes NetBeans provide you some wizard thingy to make JMS / JDBC resources from withing NetBeans and then registering them to Application server.

I assume you know NetBeans and you registered GlassFish as an application server in NetBeans server manager
To create Queue and connection follow these steps :

  • Run The IDE and go to runtime tab , expand server node and start the GlassFish instance.
  • right click on GlassFish node and select view admin console
  • login to admin console ,In left side navigation panel , expand the resources and expand JMS resources
  • click on connection factories and from main frame click on new button , fill in the values as following ones
    • JNDI Name: jms/tConnectionFactory
    • Type: javax.jmsConnectionFactory **
    • Description: some description here
    • give it a name like : tConnectionFactory
    • Click OK button
  • ** in JMS 1.1 we can use same factory for both publish/subscribe and point-to-point messaging

  • now we need to create a queue to be our messages destination, click on destination resources from main frame click on new and fill in the values as following ones
    • JNDI Name: jms/tQueue
    • Type: javax.JMS.Queue
    • Description: some description here
    • give it a name like : tQueue
    • Click Save button

Now we have our JMS Configuration ready to serve some MDB and remote client. Create a new enterprise application with two kind of modules , one EJB module and one web module , name it whatever you want but I named this sample jms
go to project view , right click on EJB module and select NewMessage-Driven Bean...
a window will open and ask you for some attributes of this MDB fill in the names like :

  • EJB Name : TMDB
  • package : mdbs
  • Mapped Name : jms/tQueue***

click finish and you are done , your MDB skeleton is ready and you just need to implement the onMessage(...) method.
*** This is where our MDB is assigned to , whether it is a topic in publish/subscribe scenario or a queue in point-to-point scenario.
Now change the implementation of your onMessage(...) as following , we also add one private object to our class , make sure that you include it too.

  @Resource
    private MessageDrivenContext mdc;
    public void onMessage(Message message) {
    
        TextMessage msg = null;
        try {
            if (message instanceof TextMessage) {
                msg = (TextMessage) message;
System.out.println("A Message received in TMDB: " +
                        msg.getText());
            } else {
               System.out.println("Message of wrong type: " +
                        message.getClass().getName());
               
            }
        } catch (JMSException e) {
            e.printStackTrace();
            mdc.setRollbackOnly();
        } catch (Throwable te) {
            te.printStackTrace();
        }
    }

we just made one more change in class skeleton and that is our MessageDrivenContext variable , we usually use this to call setRollbackOnly(...) when we use an MDB in a transactional scenario for this sample you simpley can ignore it.
Now lets make our web application to send some messages to that Queue and let the MDB fetch and process them.
wxpand web application node , and double click on index.jsp after it opens , change its content like the following , sure you can use component platte to drag and drop items to jsp source file :-)

<%@page contentType="text/html"%>

<%@page pageEncoding="UTF-8"%>
-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Pagetitle>

    head>
    <body>
<center>       
<form action="sendMessage">
            <table  cellspacing="20" >

                <tbody>
                    <tr>
                        <td>Enter some message: td>
                        <td><input type="text" name="message" value="Enter your message here" width="30" />td>

                    tr>
                tbody>
            table>
           
                <input type="submit" value="Send The message" name="send" />

            center>
        form>
    body>
html>

Now we need to build a servlet , which will send messages to our Queue , for this task you need to do these steps :

  1. Right click on web application node and select New > Servlet...
  2. change its Name to sendMessage give it a package name and click finish
  3. change the processRequest(..) method body as following list
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //start the jms stuff

        try{
            Context ctx = new InitialContext();
            ConnectionFactory     connectionFactory = (ConnectionFactory)ctx.lookup("jms/tConnectionFactory");
            Queue     queue = (Queue)ctx.lookup("jms/tQueue");
            javax.jms.Connection  connection = connectionFactory.createConnection();
            javax.jms.Session        session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setText(request.getParameter("message"));
            System.out.println( "It come from Servlet:"+ message.getText());
            messageProducer.send(message);

//message sent , it was all
           
            //show what we have done in this servlet
            out.println("");
            out.println("");
            out.println("Servlet sendMessage");
            out.println("");
            out.println("");
            out.println("
");
            out.print("Servlet Send this message

"+request.getParameter("message") + "

  to this Queue :

"+queue.getQueueName()+"

"
);
            out.println("
"
);
            out.println("");
            out.println("");
           
        } catch(Exception ex){
            ex.printStackTrace();
        }
       
        out.close();
    }

It was all you should do to create a JMS point to point sample.
to view what you have Done , press F6 , if you did all the above as i said you will see a page like :

Now just give it a message and press the button , what you will see should looks like the following image , in case that your praise the NetBeans and GlassFish as i did ;-)

and if you look at Application server log file , you will see something similar to : (to view the application server log file go to runtime view , right click on glassfish node and select view log file)

You can download the project from here but make sure that you build the connection factory and queue because project will need them .
In next part i will show you how easily you can make a remote client to deal with your jms destinations.


Related Topics >>

Comments

Hello and thank you very much for your useful JMS tutorial. ...

Hello and thank you very much for your useful JMS tutorial.
I have a question.
Is it possible to create both MDB and Servlet on a JAVA WEB (Web application) project in netbeans?

Theoretically, it can be done, but when I want to send the jms message, it does not create send message method or message producer, session, etc.

But, when I do it as you did, it works properly.

Thank you in advance