Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Sunday, 21 July 2013

Message Driven Bean in Java EE 5

In the past, I posted a few examples of implementing Messaging using J2EE and Spring. In this post, I will give an example of how to implement Message Driven beans using Java EE 5. I used Eclipse 3.2 and Glassfish for this example. Follow these steps to run the example:
  1. Download and Install Glassfish: You can download the latest build of Glassfish from the Glassfish Download site. To install follow these steps
    1. In the download directory, run the following command
      java -Xmx256m -jar glassfish-installer-version-build.jar
    2. The previous command will create a directory by the name glassfish. Go to the glassfish directory and run this command
      ant -f setup-cluster.xml
    3. The admin console for the default installation will be at http://localhost:4848/asadmin, and the default username and password are "admin" and "adminadmin" respectively.
  2. Download and Install the Glassfish Plugin for Eclipse from here.
  3. Create a Glassfish Server in Eclipse: (For some reason, Eclipse did not detect the Server Runtime without creating a Server, we'll worry about that later)
  4. Creating the EJB 3 Message Driven Bean:
    1. Create a "Java project" in Eclipse.
    2. Add the Glassfish runtime library as a dependency for the project.
    3. The following is the code for the Message Driven Bean that I used for the Example. This is in the jms package of the Java project.
      package jms;

      import javax.annotation.Resource;
      import javax.ejb.MessageDriven;
      import javax.ejb.MessageDrivenContext;
      import javax.jms.JMSException;
      import javax.jms.Message;
      import javax.jms.MessageListener;
      import javax.jms.TextMessage;

      @MessageDriven(mappedName = "jms/testQueue")
      public class Messaging3Mdb implements MessageListener {

      @Resource
      private MessageDrivenContext mdc;

      public Messaging3Mdb() {
      }
      public void onMessage(Message inMessage) {
      TextMessage msg = null;
      try {
      msg = (TextMessage) inMessage;
      System.out.println("Message received : " + msg.getText());
      } catch (JMSException e) {
      e.printStackTrace();
      mdc.setRollbackOnly();
      }
      }
      }
      Messaging3Mdb.java
  5. Creating the Client: I used a Servlet for the client, so that I could also use JMS resource injection. To create the Client
    1. Create a "Dynamic Web Project" in Eclipse.
    2. Change the Web.xml file to Reflect Java EE 5 descriptor, as shown below
      <?xml version="1.0" encoding="UTF-8"?>
      <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <display-name>Messaging3Web</display-name>
      <servlet>
      <description></description>
      <display-name>MessagingClient</display-name>
      <servlet-name>MessagingClient</servlet-name>
      <servlet-class>servlets.MessagingClient</servlet-class>
      </servlet>
      <servlet-mapping>
      <servlet-name>MessagingClient</servlet-name>
      <url-pattern>/MessagingClient</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>default.html</welcome-file>
      <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      </web-app>
      web.xml
    3. This is the code for the Servlet that acts as a client to the MDB created above
      package servlets;

      import java.io.IOException;

      import javax.annotation.Resource;
      import javax.jms.Connection;
      import javax.jms.ConnectionFactory;
      import javax.jms.Destination;
      import javax.jms.JMSException;
      import javax.jms.MessageProducer;
      import javax.jms.Queue;
      import javax.jms.Session;
      import javax.jms.TextMessage;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      public class MessagingClient extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

      @Resource(mappedName = "jms/testQueue")
      private Queue queue;

      @Resource(mappedName = "jms/connectionFactory")
      private ConnectionFactory jmsConnectionFactory;

      public MessagingClient() {
      super();
      }

      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      }

      public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      Connection connection = null;
      Destination dest = (Destination) queue;
      try {
      connection = jmsConnectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer producer = session.createProducer(dest);
      TextMessage message = session.createTextMessage();

      message.setText("Hello");
      response.getOutputStream().println("Sending message: " + message.getText());
      System.out.println("Sending message: " + message.getText());
      producer.send(message);

      producer.send(session.createMessage());
      } catch (JMSException e) {
      e.printStackTrace();
      } finally {
      if (connection != null) {
      try {
      connection.close();
      } catch (JMSException e) {
      }
      }
      }
      }
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
      }
      }
      MessagingClient.java
  6. Create the JMS Connection Factory and Queue: The connection factory and the queue can be created using the admin console or from the command line. The admin console is quite easy, you just have to go to the Resources->JMS Resources->Connection Factories and Resources->JMS Resources->Destination Resources. From the command line you have to use the following two commands from the GLASSFIS_HOME/bin directory.
    asadmin create-jms-resource --user admin --restype javax.jms.Queue --property imqDestinationName=testQueue jms/testQueue
    asadmin create-jms-resource --user admin --restype javax.jms.ConnectionFactory --property imqDestinationName=connectionFactory jms/connectionFactory
  7. Deploy the MDB: Since we created a Java Project, eclipse does not allow you to install from the IDE, so you have to export the Java jar file and use the admin console to deploy. Deploy it as an "EJB Module".
  8. Deploy the Client as a Web application

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...