Skip to content
Related Articles

Related Articles

Improve Article

Implementing Message Queuing Technique in Netbeans Through Enterprise Java Beans

  • Last Updated : 17 Jun, 2021

A Message Queues, allow one or more processes to write a message to be read by other processes. A message queue is implemented as a linked list of messages and is stored within the Kernel. Each message queue is identified by a message queue identifier. The Kernel keeps track of all the message queues created in a system.

Procedure steps for Implementing Message Queuing Technique in Netbeans through Enterprise Java Beans are listed in sequential order. Simply follow these steps in order to implement message-driven bean in Netbeans as listed below:

  1. Open Netbeans and select Java EE –> Enterprise Application
  2. Enter Project Name in the corresponding textbox
  3. Select Glashfish server
  4. Click on Finish.
  5. Create a Message Driven Bean in the EJB component.
  6. Right-click on EJB and select the Message Driven Beans option and enter the EJB name and Package name and click on Add-in project Destination and create a destination resource.
  7. Enter Name and select Queue and click on OK and next.
  8. Now create a queue.Edit index.html file to create interaction with bean.
  9. Create a servlet for communicating bean
  10. Right-click on Application and select Clean and Build option.

Step 1: Open Netbeans and select Java EE->Enterprise Application

Choose Project as Java EE->Enterprise Application

Step 2: Enter Project Name in the corresponding textbox

Enter Project Name

Step 3: Select Glassfish server



Select Glashfish Server

Step 4: Click on Finish. Three Files will be created. 1. Application, 2. EJB and 3. War files are created

Step 5: Create a Message Driven Bean in the EJB component.

Step 6: Right-click on EJB and select the Message Driven Beans option and enter the EJB name and Package name and click on Add-in project Destination and create a destination resource.

Step 7: Enter Name and select Queue and click on OK and next.



Note: here we are implementing Queuing Technique, so the Destination Type should be Queue.

Step 8: Creating a queue

Implementation:

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • And open the template in the editor.

Example 

package amar;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSDestinationDefinition;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;



@JMSDestinationDefinition(name = "java:app/studentDemo", interfaceName = "javax.jms.Queue", 
                                resourceAdapter = "jmsra", destinationName = "studentDemo")

@MessageDriven(activationConfig = {

    @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:app/studentDemo")

    ,

    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")

})

// Class implementing MessageListener interface
public class Student implements MessageListener {

    // Constructor
    public Student() {}

    // Method 1
    // @Override
    public void onMessage(Message message) {

        // Try block to check foe exceptions
        try {

            TextMessage msg = (TextMessage) message;

            System.out.println("This is the message retrieved from Queue:" + msg.getText());

            if (msg.getText() == "Abhin")

            {

                System.out.println("OK");

            } else {

                System.out.println("No");
            }
        }

        // Catch block to handle the exceptions
        catch (Exception e) {

            System.out.println("Error Message:" + e.getMessage());
        }
    }
}

Step 10: Edit index.html file to create interaction with bean.

Implementation: To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor.

Example

<!DOCTYPE html>
<html>
   <head>
       <title>TODO supply a title</title>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
   </head>
   <body>
       <div>Message Driven Bean Project</div>
       <form action="Student_Demo" method="POST">
           <input type="text" name="msg"><br><!-- comment -->
           <input type="submit" value="Add"/>
       </form>
   </body>
</html>

Step 11: Create a servlet for communicating bean



Implementation:

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • And open the template in the editor.

Example

package amar;

import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



@WebServlet(name = "Student_Demo", urlPatterns = {"/Student_Demo"})

public class Student_Demo extends HttpServlet {

    @Resource(mappedName = "jms/__defaultConnectionFactory")

    ConnectionFactory cf;

    @Resource(mappedName = "java:app/studentDemo")

    Queue dest;

  
     // Processes requests for both
     // HTTP <code>GET</code> and <code>POST</code> methods

      // Servlet request
      //@param request
      // Servlet response
      //@param response

     // If a servlet-specific error occurs
     // @throws ServletException
     // If an I/O error occurs
     // @throws IOException

     

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        try (PrintWriter out = response.getWriter()) {

            // TODO output your page here
            // Sample code to be used here

            String msg = request.getParameter("msg");

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Student_Demo</title>");
            out.println("</head>");
            out.println("<body>");

            send(msg);

            out.println("<h1>Message Queued</h1>");
            out.println("</body>");
            out.println("</html>");

        }

    }

    // Method
    private void send(String message) {


        try {

            // Creating object of Connection class
            Connection con = cf.createConnection();
            // Creating object of Session class
            Session ses = con.createSession();
            // Creating object of MessageProducer class
            MessageProducer mp = ses.createProducer(dest);
            // Creating object of TextMessage class
            TextMessage tm = ses.createTextMessage();

            tm.setText(message);

            mp.send(tm);

        }

        // Catch block to handle the exception
        catch (Exception e) {

            System.out.println("Error" + e.getMessage());

        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. 
    // Click on the + sign on the left to edit the code.">

    /**

     * Handles the HTTP <code>GET</code> method.

     *

     * @param request servlet request

     * @param response servlet response

     * @throws ServletException if a servlet-specific error occurs

     * @throws IOException if an I/O error occurs

     */

    @Override

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

        processRequest(request, response);

    }

    /**

     * Handles the HTTP <code>POST</code> method.

     *

     * @param request servlet request

     * @param response servlet response

     * @throws ServletException if a servlet-specific error occurs

     * @throws IOException if an I/O error occurs

     */

    @Override

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

        processRequest(request, response);

    }

    /**

     * Returns a short description of the servlet.

     *

     * @return a String containing servlet description

     */

    @Override

    public String getServletInfo() {

        return "Short description";

    }// </editor-fold>

}

Step 12: Right-click on Application and select Clean and Build option. It will clean the project and Built successfully. After Building successfully select Deploy. If any error in deploy it shows all those errors. Once Deploy is successful to hit the run button for the execution process.

Output:

 

User interface

Message is Queued to Glashfish Server

   

Message Queued Information

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :