Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. Launch Eclipse. Select File->New->Project.





  2. Select Web->Dynamic Web Project. Select Next.





  3. Name the project as WebMDB. Select Next.





  4. Next window displays the various project facets. Keep the default values and select Next.





  5. Keep the default values for the next window. Select Next->Finish.








  6. Right click on WebMDB project and create a new servlet.





  7. Name the servlet as UserServlet and package as webmdb. This is the producer in the application.





  8. Select Next and later Finish.





  9. Add the following code to UserServlet.java
    Code Block
    titleUserServlet.java
    borderStylesolid
    package webmdb;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    import java.util.Properties;
    
    import javax.annotation.Resource;
    import javax.jms.Connection;
    import javax.jms.ConnectionFactory;
    import javax.jms.JMSException;
    import javax.jms.MessageListener;
    import javax.jms.MessageProducer;
    import javax.jms.Queue;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class for Servlet: UserServlet
     *
     */
     public class UserServlet extends import mdb.AdminMDB;
    
     public class UserServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    	 @Resource(name="jms/TestConnectionFactoryDefaultActiveMQConnectionFactory")
    	 private ConnectionFactory connectionFactory;
    	 @Resource(name="jms/TestQueueSendReceiveQueue")
    	 private Queue queue;
    	 
    	 static final long serialVersionUID = 1L;
       
       
        /* (non-Java-doc)
    	 * @see javax.servlet.http.HttpServlet#HttpServlet()
    	 */
    	public UserServlet() {
    		super();
    	}   	
    	
    	/* (non-Java-doc)
    	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		PrintWriter out = response.getWriter();
    		if(connectionFactory == null) {
    			out.println("Connection Factory lookup has failed");
    			return;
    		}
    		
    		if(queue == null) {
    			out.println("Queue lookup has failed");
    			return;
    		}
    		
    		
    		
    		Connection connection = null;
    		try {
    			connection = connectionFactory.createConnection();
    			connection.start();
    			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    			MessageProducer producer = session.createProducer(queue);
    			TextMessage message = session.createTextMessage();
    			Enumeration arr=request.getParameterNames();
    			while(arr.hasMoreElements())
    			{
    				String fields= (String)arr.nextElement();
    				String paramname[]=request.getParameterValues(fields);
    				for (int String s=null;
    			int i;
    			for (i=0; i<paramname.length;i++)
    				{	
    				String s=null;
    				s=fields+":" + paramname[i];
    				message.setText(s);
    				producer.send(message);
    			}
    			}
    			}
    		catch(Exception e)
    			}{
    				oute.println("Your request has been sent to administrator.");
                //Send a non-text control message indicating end of messages.
                producer.send(session.createMessage());
    		} catch (JMSException e) {
    			e.printStackTrace();
    		} finally {
    			if(connection != null) {
    				try {
    					connection.close();
    				} catch (JMSException e1) { }
    			}
    		}
    	}
    	
    	/* (non-Java-doc)
    	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doGet(request, response);
    	}   	  	    
    }
    
    Right Click on WebContent and create a jsp.
    Image Removed
    Name the jsp as index.jsp. Select Next.
    Image Removed
    Select Finish.
    Image Removed
    Add the following code to index.jsp
    Code Block
    titleindex.jsp
    borderStylesolid
    
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//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=ISO-8859-1">
    <title>Sample Web Application accessing JMS Resources</title>
    </head>
    <body>
    <form action="/WebJMS/UserServlet">
    <h1>Please enter the updated information</h1>
    <table>
    <tr>
    <td>UserName:</td>
    <td><input type="text" name="username" size="30"></td>
    </tr>
    <tr>
    <td>UserID:</td>
    <td><input type="text" name="userid" size="30"></td>
    </tr>
    <tr>
    <td>Old Address:</td>
    <td><input type="text" name="oldaddress" size="30"></td>
    </tr>
    <tr>
    <td>New Address:</td>
    <td><input type="text" name="newaddress" size="30"></td>
    <tr>
    </table>
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    
    This will create the producer and user interface required by the application.

Creating Connection Factory and Destination

In simple terms a Connection Factory is an object which is used by a client to connect to the Service provider. In our case we will be using Active MQ as the provider.
Destination is an object which is used by client to provide the target to messages produced and source of the messages to be consumed. In our case the target is going to be a queue.

Let us see how we can use the administrative console to create a Connection Factory and Message Destination.

...

  1. printStackTrace();
    			}
    	}
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doGet(request, response);
    	}   	  	    
    }
    

  2. Right Click on WebContent and create a jsp.


    Image Added


  3. Name the jsp as index.jsp. Select Next.


    Image Added


  4. Select Finish.


    Image Added


    Add the following code to index.jsp
    Code Block
    titleindex.jsp
    borderStylesolid
    
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//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=ISO-8859-1">
    <title>Sample Web Application accessing JMS Resources</title>
    </head>
    <body>
    <form action="UserServlet">
    <h1>Please enter the updated information</h1>
    <table>
    <tr>
    <td>UserName:</td>
    <td><input type="text" name="username" size="30"></td>
    </tr>
    <tr>
    <td>UserID:</td>
    <td><input type="text" name="userid" size="30"></td>
    </tr>
    <tr>
    <td>Old Address:</td>
    <td><input type="text" name="oldaddress" size="30"></td>
    </tr>
    <tr>
    <td>New Address:</td>
    <td><input type="text" name="newaddress" size="30"></td>
    <tr>
    </table>
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    
    This will create the producer and user interface required by the application.

Creating Connection Factory and Destination

In simple terms a Connection Factory is an object which is used by a client to connect to the Service provider. In our case we will be using Active MQ as the provider.
Destination is an object which is used by client to provide the target to messages produced and source of the messages to be consumed. In our case the target is going to be a queue.
We will use the default connection factory and queue which is already available with Apache Geronimo.

Creating a EJB Project

  1. Right click under project explorer and Select New-> Project-> EJB Project.


    Image Added


  2. Name the project as MessageDrivenBean and Select Next.


    Image Added


  3. On the next screen keep defaults and select Next.


    Image Added


  4. On the next screen uncheck Generate Deployment Descriptor and select Next.


    Image Added


  5. Next screen suggests to configure Geronimo Deployment Plan. For current tutorial we are keeping the default values.


    Image Added


    This creates the skeleton of the EJB project. Next step is to add a pojo to our project and annotate it.
  6. Right click on EJB project and select New->class.


    Image Added


  7. Name the class as AdminMDB and package as mdb. Select Finish.


    Image Added


  8. Add the following code to AdminMDB.java.
    Code Block
    titleAdminMDB.java
    borderStylesolid
    
    package mdb;
    
    //import java.sql.SQLException;
    
    import javax.annotation.PostConstruct;
    import javax.annotation.PreDestroy;
    import javax.ejb.ActivationConfigProperty;
    import javax.ejb.MessageDriven;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageListener;
    import javax.jms.TextMessage;
    
    @MessageDriven(name="AdminMDB", activationConfig = {
    	    @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),
    	    @ActivationConfigProperty(propertyName="destination", propertyValue="SendReceiveQueue")
    	})
    public class AdminMDB implements MessageListener{
    	
    	public AdminMDB()
    	{
    		super();
    	}
    	@PostConstruct
    	public void initialize() {
    	}
    	@PreDestroy
    	public void cleanup()
    	{
    		
    	}
    
    	 public void onMessage(Message message) {
    	        TextMessage textMessage = (TextMessage) message;
    	        try {
    	            System.out.println(textMessage.getText()+ "\n");
    	       
    	        } catch (JMSException e) {
    	            e.printStackTrace();
    	        }
    	    }
    	
    }
    

Modifying Deployment plan

  1. In WebMDB project select WebContent/WEB-INF/geronimo-web.xml and modify the content with the one shown below.
    Code Block
    titlegeronimo-web.xml
    borderStylesolid
    
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <ns8:web-app xmlns="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ns2="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:ns3="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:ns4="http://geronimo.apache.org/xml/ns/j2ee/ejb/openejb-2.0" xmlns:ns5="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:ns6="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:ns7="http://java.sun.com/xml/ns/persistence" xmlns:ns8="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1" xmlns:ns9="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0">
        <environment>
            <moduleId>
                <groupId>default</groupId>
                <artifactId>WebMDB</artifactId>
                <version>1.0</version>
                <type>car</type>
            </moduleId>
            <dependencies>
                <dependency>
                    <groupId>default</groupId>
                    <artifactId>MessageDrivenBean</artifactId>
                    <version>1.0</version>
                    <type>car</type>
                </dependency>
            <dependency>
                    <groupId>org.apache.geronimo.configs</groupId>
                    <artifactId>activemq-ra</artifactId>
                    <version>2.1.1</version>
                    <type>car</type>
                </dependency> 
            </dependencies>
        </environment>
        <ns8:context-root>/WebMDB</ns8:context-root>
        <ns3:resource-ref>
            <ns3:ref-name>testfactory</ns3:ref-name>
            <ns3:resource-link>DefaultActiveMQConnectionFactory</ns3:resource-link>
       		</ns3:resource-ref>
    </ns8:web-app>
    
  2. In MessageDrivenBean project select META-INF/openejb-jar.xml and modify it as follows
    Code Block
    titleopenejb-jar.xml
    borderStylesolid
    
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <openejb-jar xmlns="http://www.openejb.org/xml/ns/openejb-jar-2.2" xmlns:nam

...

Creating a EJB Project

...

Code Block
titleAdminMDB.java
borderStylesolid

package mdb;

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

@MessageDriven(
name="Admin",
activationConfig = {
@ActivationConfigProperty(
propertyName="destinationType",
propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(
propertyName="destinationName",
propertyValue="jms/TestQueue")
}
)
public class AdminMDB implements MessageListener {

public void onMessage(Message msg) {
	
	if (msg instanceof TextMessage) {
		   TextMessage tm = (TextMessage) msg;
		   try {
		    System.out.println("Received new message");
		    System.out.println("CustomerId : " +tm.getStringProperty("username"));
		    System.out.println("CustomerName : " +tm.getStringProperty("userid"));
		    System.out.println("Old Address : " +tm.getStringProperty("oldaddress"));
		    System.out.println("New Address : " +tm.getStringProperty("newaddress") );
		   } catch (JMSException e) {
		      e.printStackTrace();
		   }
	
	 
}
}
}

Modifying Deployment plan

  1. In WebMDB project select WebContent/WEB-INF/geronimo-web.xml and modify the content with the one shown below.
    Code Block
    titlegeronimo-web.xml
    borderStylesolid
    
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-1.2" 
             xmlns:nam="http://geronimo.apache.org/xml/ns/naming-1.2" 
             xmlns:sec="http://geronimo.apache.org/xml/ns/security-1.1" 
             xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.2">
        <sys:environment>
            <sys:moduleId>
                <sys:groupId>default</sys:groupId>
                <sys:artifactId>WebMDB</sys:artifactId>
                <sys:version>1.0</sys:version>
                <sys:type>car</sys:type>
            </sys:moduleId>
            <sys:dependencies>
       naming-1.2" 
    xmlns:pkgen="http://www.openejb.org/xml/ns/pkgen-2.0" 
    xmlns:sec="http://geronimo.apache.org/xml/ns/security-1.2" xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.2">
        <sys:environment>
             <sys:dependency>moduleId>
                    <sys:groupId>default</sys:groupId>
                    <sys:artifactId>MessageDrivenBean</sys:artifactId>
                    <sys:version>1.0</sys:version>
                <sys:type>car</sys:type>
            <sys:type>car<</sys:type>
    moduleId>
            <sys:dependencies>
            </sys<sys:dependency>
                <sys:dependency>groupId>org.apache.geronimo.configs</sys:groupId>
            <sys:artifactId>activemq-ra</sys:artifactId>
            <sys:groupId>orgversion>2.apache1.geronimo.configs<1</sys:groupId>version>
            <sys:type>car</sys:type>
            <sys:artifactId>activemq-ra<</sys:artifactId>dependency>
            </sys:dependencies>
            <sys:version>2.1<</sys:version>environment>
            <enterprise-beans>
              <sys:type>car</sys:type><message-driven>
                </sys:dependency>
      <ejb-name>AdminMDB</ejb-name>
        		<nam:resource-adapter>
          </sys:dependencies>		<nam:resource-link>ActiveMQ RA</nam:resource-link>
        		</sysnam:environment>resource-adapter>
        <context-root>/WebMDB</context-root>		
        <nam:resource-ref>		<activation-config>
    
            <nam:ref-name>jms/TestConnectionFactory</nam:ref-name><activation-config-property>
            <nam:pattern>
    <activation-config-property-name>
           destination
          <nam:groupId>org.apache.geronimo.configs</nam:groupId></activation-config-property-name>
          <activation-config-property-value>
          <nam:artifactId>activemq-ra</nam:artifactId>SendReceiveQueue
          </activation-config-property-value>
          <nam:version>2.1</nam:version>
    </activation-config-property>
          <activation-config-property>
           <nam:name>DefaultActiveMQConnectionFactory</nam:<activation-config-property-name>
            </nam:pattern>destinationType
           </nam:resource-ref>
        <nam:resource-env-ref>activation-config-property-name>
            <nam:ref-name>jms/TestQueue</nam:ref-name><activation-config-property-value>
            <nam:pattern>javax.jms.Queue</activation-config-property-value>
           </activation-config-property>
    
          <nam:groupId>org.apache.geronimo.configs</nam:groupId></activation-config>
       			</message-driven>
                <nam:artifactId>activemq-ra</nam:artifactId>
                <nam:version>2.1</nam:version>
                <nam:name>SendReceiveQueue</nam:name>
            </nam:pattern>
        </nam:resource-env-ref>
    </web-app>
    </enterprise-beans>
    </openejb-jar>
    



    Deploy and Run

  2. Export MessageDrivenBean.jar and WebMDB.war from eclipse as shown in the figure below


    Image Added


    Image Added


  3. Launch Administrative console and deploy the EJB and Web Application using Deploy New.
  4. Once done launch the web application with http://localhost:8080/WebMDB/.\\Image Added

    Image Added
  5. Fill the form as suggested in the figure and Select Submit.


    Image Added


  6. Once done check out the command prompt. Message Driven Bean has triggered and it displays the message currently on the queue.


    Image Added