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


Showing posts with label messaging. Show all posts
Showing posts with label messaging. Show all posts

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

Friday, 12 July 2013

Implementing JMS with Spring: Message Driven POJO

The previous post described how to implement a JMS messaging client using Spring JMS. This post will describe how to implement the Message listener as a spring Message driven POJO. Follow these steps to implement the Message driven POJO
  1. Create the Message Driven POJO: The only requirement for the Message Driven POJO is to implement the MessageListener interface. The following listing shows the code for the MDP
    public class SpringMDP implements MessageListener {
    public void onMessage(Message message) {
    try {
    System.out.println(((TextMessage) message).getText());
    } catch (JMSException ex) {
    throw new RuntimeException(ex);
    }
    }
    }
    SpringMDP.java

  2. Create the bean definition in applicationContext.xml file.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
    <!-- this is the Message Driven POJO (MDP) -->
    <bean id="messageListener" class="jms.SpringMDP" />

    <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
    <props>
    <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
    <prop key="java.naming.provider.url">t3://localhost:20001</prop>
    </props>
    </property>
    </bean>
    <bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate">
    <ref bean="jndiTemplate" />
    </property>
    <property name="jndiName">
    <value>jms/connectionFactory</value>
    </property>
    </bean>

    <bean id="queue" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate">
    <ref bean="jndiTemplate" />
    </property>
    <property name="jndiName">
    <value>jms/testQueue</value>
    </property>
    </bean>


    <bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="concurrentConsumers" value="5" />
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="queue" />
    <property name="messageListener" ref="messageListener" />
    </bean>
    </beans>
    WEB-INF/applicationContext.xml

    The Message listener container handles all the required functions for making the Simple POJO a Message Driven POJO.

  3. Update Web.xml to include a listener for spring.
    <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

Message Driven Bean in Java EE 5 : Part 2

In a previous post, I described how to implement Messaging in Java EE 5 using annotation. This post is an extension of that post to describe how to implement Messaging in Java EE 5 using a deployment descriptor. To implement this, you can use the same client that was described in the other post. The only change needed is in the MDB part. Here's how to implement a Message Driven bean using the deployment descriptor.
  1. Create the Message driven bean: The message driven bean here is a simple Java class that implements the MessageListener interface. All the configuration will be done in the deployment descriptors.
    package jms;

    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageListener;
    import javax.jms.TextMessage;

    import org.apache.log4j.Level;
    import org.apache.log4j.Logger;

    public class Messaging3Mdb implements MessageListener {

    static final Logger logger = Logger.getLogger("MDB");

    public Messaging3Mdb() {
    }

    public void onMessage(Message inMessage) {
    TextMessage msg = null;
    logger.setLevel(Level.ALL);

    try {
    if (inMessage instanceof TextMessage) {
    msg = (TextMessage) inMessage;
    logger.info("MESSAGE BEAN: Message received: " + msg.getText());
    } else {
    logger.warn("Message of wrong type: " + inMessage.getClass().getName());
    }
    } catch (JMSException e) {
    logger.error("MessageBean.onMessage: JMSException: " + e.toString());
    } catch (Throwable te) {
    logger.error("MessageBean.onMessage: Exception: " + te.toString());
    }
    }
    }
    Messaging3Mdb.java
  2. The sun-ejb-jar.xml file: This file contains the mapping of the JMS resources.
    <?xml version="1.0" encoding="UTF-8"?>
    <sun-ejb-jar>
    <enterprise-beans>
    <name>Ejb3DD</name>
    <ejb>
    <ejb-name>Messaging3Mdb</ejb-name>
    <jndi-name>jms/testQueue</jndi-name>
    <mdb-connection-factory>
    <jndi-name>jms/connectionFactory</jndi-name>
    </mdb-connection-factory>
    </ejb>
    </enterprise-beans>
    </sun-ejb-jar>
    META-INF/sun-ejb-jar.xml
  • The EJB deployment descriptor:
    <?xml version="1.0" encoding="UTF-8" ?>
    <ejb-jar>
    <enterprise-beans>
    <message-driven>
    <ejb-name>Messaging3Mdb</ejb-name>
    <ejb-class>jms.Messaging3Mdb</ejb-class>
    <messaging-type>javax.jms.MessageListener</messaging-type>
    <message-destination-type>javax.jms.Queue</message-destination-type>

    </message-driven>
    </enterprise-beans>
    </ejb-jar>
    META-INF/ejb-jar.xml

  • Environment: This example was implemented on Glassfish v1, Milestone 7
  • Implementing JMS with Spring: Messaging Client

    Last week, I described how to implement JMS, using a stand-alone client and a Message Driven Bean. In this post and the next, I will describe how to implement JMS using Spring and Message Driven POJOs. This post will describe how to create a Messaging client using Spring. The next post will describe how to implement a Message driven POJO. For this I used a simple servlet that, when invoked will send a text message "hello", to a destination queue. The Message driven pojo, listening on the queue will then receive and print the message. Follow these steps to run the example
    1. Setup the JMS environment as described in the "Configuring Weblogic JMS" post
    2. Create the Messaging client: This is a simple Java class which uses the spring JmsTemplate to send a message to the queue. The JmsTemplate can be used for message production and synchronous message reception. For asynchronous reception, Spring provides a number of message listener containers that are used to create Message-Driven POJOs (MDPs).
      public class QueueSender {
      private JmsTemplate jmsTemplate;
      public void setJmsTemplate(JmsTemplate jmsTemplate) {
      this.jmsTemplate = jmsTemplate;
      }
      public void sendMesage() {
      jmsTemplate.send("jms/testQueue", new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
      return session.createTextMessage("Hello");
      }
      });
      }
      }
      QueueSender.java
    3. Configure the Bean in the applicationContext.xml file: The following is alisting of the applicationContext.xml file.
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
      "http://www.springframework.org/dtd/spring-beans.dtd">
      <beans>
      <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
      <property name="environment">
      <props>
      <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
      <prop key="java.naming.provider.url">t3://localhost:20001</prop>
      </props>
      </property>
      </bean>

      <bean id="queueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiTemplate">
      <ref bean="jndiTemplate" />
      </property>
      <property name="jndiName">
      <value>jms/connectionFactory</value>
      </property>
      </bean>

      <bean id="jmsDestinationResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver">
      <property name="jndiTemplate">
      <ref bean="jndiTemplate" />
      </property>
      <property name="cache">
      <value>true</value>
      </property>
      </bean>

      <bean id="queueTemplate" class="org.springframework.jms.core.JmsTemplate">
      <property name="connectionFactory">
      <ref bean="queueConnectionFactory" />
      </property>
      <property name="destinationResolver">
      <ref bean="jmsDestinationResolver" />
      </property>
      </bean>

      <bean id="jmsSender" class="jms.QueueSender">
      <property name="jmsTemplate">
      <ref bean="queueTemplate" />
      </property>

      </bean>
      </beans>
      WEB-INF/applicationContext.xml

      The JndiDestinationResolver class can be used to obtain the Queue destinations using the JNDI Name. The send method in JmsTemplate (see QueueSender), uses the JNDI name, which is used by the JndiDestinationResolver to obtain the appropriate destination.

    4. Create a servlet to invoke the Message Sender: The following servlet is used to invoke the QueueSender:
       public class QueueSenderServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
      protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
      QueueSender sender = (QueueSender)ctx.getBean("jmsSender");
      sender.sendMesage();
      }
      }
      QueueSenderServlet.java
    5. Update the web.xml file to add the servlet and spring application context:
      <?xml version="1.0" encoding="UTF-8"?>
      <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
      <display-name>SpringJMSClientWeb</display-name>
      <servlet>
      <description></description>
      <display-name>QueueSenderServlet</display-name>
      <servlet-name>QueueSenderServlet</servlet-name>
      <servlet-class>jms.QueueSenderServlet</servlet-class>
      </servlet>
      <servlet-mapping>
      <servlet-name>QueueSenderServlet</servlet-name>
      <url-pattern>/QueueSenderServlet</url-pattern>
      </servlet-mapping>
      <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      </web-app>
      web.xml

      The listener defined web.xml (ContextLoaderListener) by default loads the applicationContext.xml file in WEB-INF directory of the web application.
    In the next post, we will see how implement the Message Driven POJO to consume the message sent from here.

    Saturday, 6 July 2013

    Messaging Quickstart: Sample Code

    The previous post described how to setup a Queue in Weblogic Server. This post shows the code necessary to run a Simple Messaging example using a servlet and Message Driven Bean. You can always implement an message listener instead of using a Message Driven Bean, but using MDBs is much cleaner and easier. Follow these steps to run the example
    1. Setup XDoclet
      1. Download XDoclet from here, and extract it.
      2. In Eclipse->Window->preferences, select xdoclet and set the Xdoclet home to the appropriate directory.
    2. Create the Message Driven Bean
      1. Create an EJB project in Eclipse.
      2. In the J2EE perspective, right-click on the Deployment descriptor and create a new Message Driven Bean. Eclipse generates the required classes and the ejb-jar.xml file with the new MDB definition in it. Modify the Bean to look like this
        public class MessagingExampleBean implements javax.ejb.MessageDrivenBean, javax.jms.MessageListener {
        private javax.ejb.MessageDrivenContext messageContext = null;
        public void setMessageDrivenContext(javax.ejb.MessageDrivenContext messageContext) throws javax.ejb.EJBException {
        this.messageContext = messageContext;
        }
        public void ejbCreate() {
        }
        public void ejbRemove() {
        messageContext = null;
        }
        public MessagingExampleBean() {
        }
        public void onMessage(javax.jms.Message message) {
        System.out.println("Message Driven Bean got message " + message);
        }
        }
        Add the following definitions to the ejb-jar.xml
        <?xml version="1.0" encoding="UTF-8"?>
        <ejb-jar version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">
        <display-name>MessagingExample</display-name>
        <enterprise-beans>
        <message-driven>
        <display-name>MessagingExampleMDB</display-name>
        <ejb-name>MessagingExampleMDB</ejb-name>
        <ejb-class>jms.MessagingExampleMdb</ejb-class>
        <transaction-type>Bean</transaction-type>
        <message-destination-type>javax.jms.Queue</message-destination-type>
        </message-driven>
        </enterprise-beans>
        <assembly-descriptor>
        <container-transaction>
        <method>
        <ejb-name>MessagingExampleMDB</ejb-name>
        <method-name>*</method-name>
        </method>
        <trans-attribute>Required</trans-attribute>
        </container-transaction>
        </assembly-descriptor>
        </ejb-jar>
      3. Create a new file weblogic-ejb-jar.xml. This is required for Weblogic bindings.
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE weblogic-ejb-jar PUBLIC "-//BEA Systems, Inc.//DTD WebLogic 8.1.0 EJB//EN" "http://www.bea.com/servers/wls810/dtd/weblogic-ejb-jar.dtd">
        <weblogic-ejb-jar>
        <weblogic-enterprise-bean>
        <ejb-name>MessagingExampleMDB</ejb-name>
        <message-driven-descriptor>
        <pool>
        <max-beans-in-free-pool>5</max-beans-in-free-pool>
        <initial-beans-in-free-pool>5</initial-beans-in-free-pool>
        </pool>
        <destination-jndi-name>jms/testQueue</destination-jndi-name>
        <initial-context-factory>weblogic.jndi.WLInitialContextFactory</initial-context-factory>
        <connection-factory-jndi-name>jms/connectionFactory</connection-factory-jndi-name>
        <jms-polling-interval-seconds>20</jms-polling-interval-seconds>
        </message-driven-descriptor>
        <transaction-descriptor>
        <trans-timeout-seconds>3600</trans-timeout-seconds>
        </transaction-descriptor>

        </weblogic-enterprise-bean>
        </weblogic-ejb-jar>
    3. Create the Client. For this example, I used a servlet that simply sends a "Hello" message to the MDB through the Queue. Here is the code for it
      public class MessaginClientServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
      public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
      public final static String JMS_FACTORY = "weblogic.examples.jms.QueueConnectionFactory";
      public final static String QUEUE = "weblogic.examples.jms.exampleQueue";
      public MessaginClientServlet() {
      super();
      }
      protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      try {
      Context ctx = getInitialContext("t3://localhost:20001");
      QueueConnectionFactory qconFactory;
      QueueConnection connection;
      QueueSession session;
      QueueSender sender;
      Queue queue;
      TextMessage msg;

      qconFactory = (QueueConnectionFactory) ctx.lookup("jms/connectionFactory");
      connection = qconFactory.createQueueConnection();
      session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      queue = (Queue) ctx.lookup("jms/testQueue");
      msg = session.createTextMessage();
      sender = session.createSender(queue);
      msg.setText("Hello World");
      connection.start();
      sender.send(msg);
      session.close();
      connection.close();
      } catch (Exception e) {
      e.printStackTrace();
      }
      }

      private InitialContext getInitialContext(String url) throws NamingException {
      Hashtable<String, String> env = new Hashtable<String, String>();
      env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
      env.put(Context.PROVIDER_URL, url);
      return new InitialContext(env);
      }
      }

    Messaging Quickstart: Configuring Weblogic JMS

    This is a basic example of how to implement Messaging in Java using JMS and Message driven beans. The example is implemented using Weblogic JMS implementation. This part describes how to configure a queue on weblogic, the next part will describe the programming involved to run the example.Follow these steps to configure a queue in Weblogic:
    1. Create a JMS Server
      1. In the admin console go to Home > Summary of Services: JMS > Summary of JMS Servers and click on Lock & Edit and then click on New.
      2. In the next screen choose a name and create a new File Store and click next.
      3. Select the deployment target and finish.
    2. Create a JMS Module: Go to JMS Modules in the Admin console and create a new module, accept defaults.
    3. Create a Connection Factory: Go to Home > JMS Modules > jmsModule. Select new and create a new connection factory. Set the JNDI name to jms/connectionFactory
    4. Create a Destination: Go to Home > JMS Modules > jmsModule and Create a new Queue and set the JNDI name to jms/testQueue. When creating a queue, select "create a new Sub deployment" and create a new sub-deployment.
    Go to part 2.

    Wednesday, 3 July 2013

    Making Simple POJO to Message Driven POJO with Spring

    In the past, I posted a few examples of implementing Messaging using J2EE and Spring. This post will describe how to use the Spring MessageListenerAdapter to enable any Java class to act as a Message Driven POJO. This can be used to enable existing applications to use Asynchronous Messaging. Follow these steps to run the example:

    The Message Driven POJO
    1. The following is the code for the Simple Java class that will be used as a Message Driven POJO
      public class MsgListener {
      public void receive(String message) {
      System.out.println("The message was : " + message);
      }
      }
      MsgListener.java
    2. The Spring Configuration used for this is shown below
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
      "http://www.springframework.org/dtd/spring-beans.dtd">
      <beans>
      <bean id="messageListener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
      <constructor-arg>
      <bean class="jms.MsgListener" />
      </constructor-arg>
      <property name="defaultListenerMethod" value="receive" />
      <!-- we don't want automatic message context extraction -->
      <property name="messageConverter">
      <bean class="org.springframework.jms.support.converter.SimpleMessageConverter"></bean>
      </property>
      </bean>

      <!-- and this is the message listener container... -->
      <bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
      <property name="concurrentConsumers" value="5" />
      <property name="connectionFactory" ref="connectionFactory" />
      <property name="destination" ref="queue" />
      <property name="messageListener" ref="messageListener" />
      </bean>

      <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
      <property name="environment">
      <props>
      <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
      <prop key="java.naming.provider.url">t3://localhost:20001</prop>
      </props>
      </property>
      </bean>
      <bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiTemplate">
      <ref bean="jndiTemplate" />
      </property>
      <property name="jndiName">
      <value>jms/connectionFactory</value>
      </property>
      </bean>

      <bean id="queue" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiTemplate">
      <ref bean="jndiTemplate" />
      </property>
      <property name="jndiName">
      <value>jms/testQueue</value>
      </property>
      </bean>
      </beans>
      WEB-INF/applicationContext.xml

      Note: The MessageListenerAdapter used here (bean-messageListener) is acts as an adapter to enable the MsgListener class to receive messages.
    3. The Web Deployment descriptor
      <?xml version="1.0" encoding="UTF-8"?>
      <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
      <display-name>SpringJMSWeb</display-name>
      <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      </web-app>
      web.xml

    The Client
    1. Create a Simple Servlet that will be used to start the application. The code for the Servlet is shown below.
      public class QueueSenderServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
      protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
      QueueSender sender = (QueueSender)ctx.getBean("jmsSender");
      sender.sendMesage();
      }
      }
      QueueSenderServlet.java
    2. The following code shows Queue Sender. The Queue sender uses the JMSTemplate to send message to the queue.
      public class QueueSender {
      private JmsTemplate jmsTemplate;
      public void setJmsTemplate(JmsTemplate jmsTemplate) {
      this.jmsTemplate = jmsTemplate;
      }
      public void sendMesage() {
      jmsTemplate.send("jms/testQueue", new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
      return session.createTextMessage("Hello");
      }
      });
      }
      }
      QueueSender.java
    3. Spring Configuration: The Spring configuration file is shown below
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
      "http://www.springframework.org/dtd/spring-beans.dtd">
      <beans>
      <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
      <property name="environment">
      <props>
      <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
      <prop key="java.naming.provider.url">t3://localhost:20001</prop>
      </props>
      </property>
      </bean>

      <bean id="queueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiTemplate">
      <ref bean="jndiTemplate" />
      </property>
      <property name="jndiName">
      <value>jms/connectionFactory</value>
      </property>
      </bean>

      <bean id="jmsDestinationResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver">
      <property name="jndiTemplate">
      <ref bean="jndiTemplate" />
      </property>
      <property name="cache">
      <value>true</value>
      </property>
      </bean>

      <bean id="queueTemplate" class="org.springframework.jms.core.JmsTemplate">
      <property name="connectionFactory">
      <ref bean="queueConnectionFactory" />
      </property>
      <property name="destinationResolver">
      <ref bean="jmsDestinationResolver" />
      </property>
      </bean>

      <bean id="jmsSender" class="jms.QueueSender">
      <property name="jmsTemplate">
      <ref bean="queueTemplate" />
      </property>

      </bean>
      </beans>
      WEB-INF/applicationContext.xml
    4. The Web Deployment descriptor
      <?xml version="1.0" encoding="UTF-8"?>
      <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
      <display-name>SpringJMSWeb</display-name>
      <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      </web-app>
      web.xml

    LinkWithin

    Related Posts Plugin for WordPress, Blogger...