Due to a known issue do not use JDK1.8.0_151 with WSO2 products. Use JDK 1.8.0_144 until JDK 1.8.0_162-ea is released.
This documentation is for WSO2 Message Broker version 3.2.0. For the latest documentation, see the documentation for WSO2 Enterprise Integrator.
Skip to end of metadata
Go to start of metadata

In the sections that follow, we will look at how web applications deployed in WSO2 Application Server (WSO2 AS) can communicate with WSO2 Message Broker (WSO2 MB) as JMS subscribers and JMS publishers.

Setting up WSO2 Message Broker

Follow the steps given below to start WSO2 MB.

  1. Download and install WSO2 MB.  

  2. Start WSO2 MB by executing one of the following startup scripts:
    • In Linux: <MB_HOME>/bin/wso2server.sh
    • In Windows: <MB_HOME>/bin/wso2server.bat 

Note that WSO2 MB must be up and running before starting the application server.

Setting up WSO2 AS

Follow the steps given below to set up and start the application server.

  1. Download and install WSO2 AS.

  2. To avoid a port conflict with WSO2 MB, apply a port offset for WSO2 AS in the carbon.xml file (stored in the <MB_HOME>/repository/conf folder). See the following example:

    <Offset>1</Offset>

    Since all WSO2 products use the same port (9443) in the default configuration, it is not possible to start multiple WSO2 products using the default configurations in the same environment, at the same time. Therefore, using the port offset, you are making sure that each product is started on a different port.

  3. Open the axis2.xml file  stored in the <AS_HOME>/repository/conf/axis2 folder and enable the JMS transport receiver for WSO2 MB by uncommenting the following:

    <!--Configure for JMS transport support with WSO2 MB 2.x.x -->
        <transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener">
            <parameter name="myTopicConnectionFactory" locked="false">
               <parameter name="java.naming.factory.initial" locked="false">org.wso2.andes.jndi.PropertiesFileInitialContextFactory</parameter>
                <parameter name="java.naming.provider.url" locked="false">repository/conf/jndi.properties</parameter>
                <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">TopicConnectionFactory</parameter>
                <parameter name="transport.jms.ConnectionFactoryType" locked="false">topic</parameter>
            </parameter>
            <parameter name="myQueueConnectionFactory" locked="false">
                <parameter name="java.naming.factory.initial" locked="false">org.wso2.andes.jndi.PropertiesFileInitialContextFactory</parameter>
                <parameter name="java.naming.provider.url" locked="false">repository/conf/jndi.properties</parameter>
                <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">QueueConnectionFactory</parameter>
               <parameter name="transport.jms.ConnectionFactoryType" locked="false">queue</parameter>
            </parameter>
            <parameter name="default" locked="false">
                <parameter name="java.naming.factory.initial" locked="false">org.wso2.andes.jndi.PropertiesFileInitialContextFactory</parameter>
                <parameter name="java.naming.provider.url" locked="false">repository/conf/jndi.properties</parameter>
                <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">QueueConnectionFactory</parameter>
                <parameter name="transport.jms.ConnectionFactoryType" locked="false">queue</parameter>
            </parameter>
        </transportReceiver>
  4. Uncomment the <transport sender> block for JMS in the same file as follows:

    <!-- uncomment this and configure to use connection pools for sending messages>
    <transportSender name="jms" class="org.apache.axis2.transport.jms.JMSSender"/>
  5. Add the following jndi.properties file to the <AS_HOME>/repository/conf directory to make sure that WSO2 AS is pointing to the running message broker.

    # register some connection factories
    # connectionfactory.[jndiname] = [ConnectionURL]
    connectionfactory.QueueConnectionFactory = amqp://admin:[email protected]/carbon?brokerlist='tcp://localhost:5672'
    connectionfactory.TopicConnectionFactory = amqp://admin:[email protected]/carbon?brokerlist='tcp://localhost:5672'
  6. Copy the following JAR files from the <MB_HOME>/client-lib folder to the <AS_HOME>/repository/components/lib folder. 
    • andes-client-3.1.1
    • geronimo-jms_1.1_spec-1.1.0.wso2v1 
    • log4j-1.2.13
    • org.wso2.carbon.logging-4.4.1
    • org.wso2.securevault-1.0.0-wso2v2
    • slf4j-1.5.10.wso2v1
  7. Download the axis2-transport-all-1.0.0.jar from here and add it to the <AS_HOME>/repository/components/lib directory.

  8. Save all the files.

  9. Now, start WSO2 AS by executing the startup script:
    • In Linux: <AS_HOME>/bin/wso2server.sh
    • In Windows: <AS_HOME>/bin/wso2server.bat 

Developing a web application (JMS Subscriber/Publisher)

To create a web application that can subscribe/publish to a queue or topic in WSO2 MB, you will need to write a JMS client (subscriber/publisher) and build it as a web application (WAR file), which can be deployed in the application server.

Follow the steps given below to build a web application that can subscribe and publish to a queue in WSO2 MB.

Step 1: Writing the JMS client

First, we will write a JMS client that subscribes to a queue in WSO2 MB: Create a java project using the source files given below and compile it.

The following class is used to create the sample client that creates a queue named testQueue in WSO2 MB and sends messages to that queue:

package org.sample.jms;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
public class SampleQueueSender {
    public static final String QPID_ICF = "org.wso2.andes.jndi.PropertiesFileInitialContextFactory";
    private static final String CF_NAME_PREFIX = "connectionfactory.";
    private static final String QUEUE_NAME_PREFIX = "queue.";
    private static final String CF_NAME = "qpidConnectionfactory";
    String userName = "admin";
    String password = "admin";
    private static String CARBON_CLIENT_ID = "carbon";
    private static String CARBON_VIRTUAL_HOST_NAME = "carbon";
    private static String CARBON_DEFAULT_HOSTNAME = "localhost";
    private static String CARBON_DEFAULT_PORT = "5672";
    String queueName = "testQueue";
    private QueueConnection queueConnection;
    private QueueSession queueSession;
    public void sendMessages() throws NamingException, JMSException {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
        properties.put(QUEUE_NAME_PREFIX + queueName, queueName);
        InitialContext ctx = new InitialContext(properties);
        // Lookup connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        queueConnection.start();
        queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        // Send message
        Queue queue = (Queue)ctx.lookup(queueName);
        // create the message to send
        TextMessage textMessage = queueSession.createTextMessage("Test Message Content");
        javax.jms.QueueSender queueSender = queueSession.createSender(queue);
        queueSender.send(textMessage);
        queueSender.close();
        queueSession.close();
        queueConnection.close();
    }
    private String getTCPConnectionURL(String username, String password) {
        // amqp://{username}:{password}@carbon/carbon?brokerlist='tcp://{hostname}:{port}'
        return new StringBuffer()
                .append("amqp://").append(username).append(":").append(password)
                .append("@").append(CARBON_CLIENT_ID)
                .append("/").append(CARBON_VIRTUAL_HOST_NAME)
                .append("?brokerlist='tcp://").append(CARBON_DEFAULT_HOSTNAME).append(":").append(CARBON_DEFAULT_PORT).append("'")
                .toString();
    }
 
}

The following class is used to create the sample client that receives the messages published to the testqueue queue in WSO2 MB:

package org.sample.jms;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.jms.MessageConsumer;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
public class SampleQueueReceiver {
    public static final String QPID_ICF = "org.wso2.andes.jndi.PropertiesFileInitialContextFactory";
    private static final String CF_NAME_PREFIX = "connectionfactory.";
    private static final String CF_NAME = "qpidConnectionfactory";
    String userName = "admin";
    String password = "admin";
    private static String CARBON_CLIENT_ID = "carbon";
    private static String CARBON_VIRTUAL_HOST_NAME = "carbon";
    private static String CARBON_DEFAULT_HOSTNAME = "localhost";
    private static String CARBON_DEFAULT_PORT = "5672";
    String queueName = "testQueue";
    private QueueConnection queueConnection;
    private QueueSession queueSession;
    public MessageConsumer registerSubscriber() throws NamingException, JMSException{
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
        properties.put("queue."+ queueName,queueName);
        InitialContext ctx = new InitialContext(properties);
        // Lookup connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        queueConnection.start();
        queueSession =
                queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        //Receive message
        Queue queue =  (Queue) ctx.lookup(queueName);
        MessageConsumer consumer = queueSession.createConsumer(queue);
        return consumer;
    }
    public void receiveMessages(MessageConsumer consumer) throws NamingException, JMSException {
        TextMessage message = (TextMessage) consumer.receive();
        System.out.println("Got message from queue receiver==>" + message.getText());
        // Housekeeping
        consumer.close();
        queueSession.close();
        queueConnection.stop();
        queueConnection.close();
    }
    private String getTCPConnectionURL(String username, String password) {
        // amqp://{username}:{password}@carbon/carbon?brokerlist='tcp://{hostname}:{port}'
        return new StringBuffer()
                .append("amqp://").append(username).append(":").append(password)
                .append("@").append(CARBON_CLIENT_ID)
                .append("/").append(CARBON_VIRTUAL_HOST_NAME)
                .append("?brokerlist='tcp://").append(CARBON_DEFAULT_HOSTNAME).append(":").append(CARBON_DEFAULT_PORT).append("'")
                .toString();
    }
 
}

The Main.java class defines the main method for calling both the subscriber and publisher clients. The code of this class is as follows:

package org.sample.jms;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.naming.NamingException;

public class Main {
	public static void main(String[] args) throws NamingException, JMSException {
        SampleQueueReceiver queueReceiver = new SampleQueueReceiver();
        MessageConsumer consumer = queueReceiver.registerSubscriber();
        SampleQueueSender queueSender = new SampleQueueSender();
        queueSender.sendMessages();
        queueReceiver.receiveMessages(consumer);
    }
}

Once you build the above client, you will have the following class files:

  • JmsQueue.class
  • SampleQueueReceiver.class
  • SampleQueueSender.class

Step 2: Building the web application

Now, let's build a web application using the source files (JMS client) given above. This web application will also have an interface for invoking the JMS client. Follow the steps given below.

  1. Create a folder structure in your local machine by following the steps given below.

    1. Create the following folder structure in your local machine:

      -WebApp/
       	-WEB-INF/
       		-lib/
       		-classes/
      		 	-MyPackage/
              -web.xml
       	Index.html
    2. And the class files you developed in step1 to the WEB-INF/lib/classes/MyPackage directory. You can download these class files from here.

    3. Update the web.xml file with the following content:

      <?xml version="1.0" encoding="ISO-8859-1"?>
      <web-app 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"
          version="2.4">
          <display-name>JMS Queue Sample Web Application</display-name>
          <description>
      	This is a sample web application which sends and receives queue message using wso2 message broker.
          </description>
          <servlet>
              <servlet-name>JMSQueueServlet</servlet-name>
              <servlet-class>mypackage.JmsQueue</servlet-class>
          </servlet>
          <servlet-mapping>
              <servlet-name>JMSQueueServlet</servlet-name>
              <url-pattern>/jmsqueue</url-pattern>
          </servlet-mapping>
      </web-app>
    4. Copy the JARs in the <MB_HOME>/client-lib directory to the WEB-INF/lib directory.
    5. Update the index.html file with the following content:

      <html>
      	<head>
      		<title>JMS Queue Sample Web Application</title>
      	</head>
      	<body bgcolor=white>
      		<table border="0">
      			<tr>
      				<td>
      					<h1>Sample Queue Web Application</h1>
      				</td>
      			</tr>
      			<tr>
      				<td>
      					<p>This is the home page for a sample web application which sends and receives queue messages using wso2 message broker.</p>
      				</td>
      			</tr>
      		</table>
      			<p>Please click on following link to run the sample :
      			<ul>
      				<li><a href="jmsqueue">Queue send receive sample servlet</a></li>
      			</ul>
      	</body>
      </html>

    Your <WEBAPP_HOME> directory should now have the following content:

    -WebApp/
     	-WEB-INF/
     		-lib/
     			- andes-client-3.0.1.jar
    			- log4j-1.2.13.jar
    			- org.wso2.securevault-1.0.0-wso2v2.jar
    			- geronimo-jms_1.1_spec-1.1.0.wso2v1.jar
    			- org.wso2.carbon.logging-4.4.1.jar
    			- slf4j-1.5.10.wso2v1.jar
     		-classes/
    		 	-MyPackage/
     				- JmsQueue.java
    				- SampleQueueReceiver.java
    				- SampleQueueSender.java
            -web.xml
     	Index.html
  2. Open a terminal and navigate to the <WEBAPP_HOME> folder. 

  3. Execute the following command from the terminal in order to create the .war file: Jar -cvf jmsQueue.war *

This will create the jmsQueue.war file in the WebApp folder.

Deploying the web application in WSO2 AS

You can now deploy the jmsQueue WAR file in WSO2 AS using one of the following options:

  • Log in to the management console of WSO2 AS and click Web Applications under Applications in the navigator to open the Upload Web Applications screen. Now you can upload the jmsQueue.war file to the server.

  • Alternatively, you can simply add the WAR file to the <AS_HOME>/repository/deployment/server/webapps directory.
     

Now you have successfully deployed a web application (containing a JMS subscriber and JMS publisher) in WSO2 AS.

Testing the web application with WSO2 MB

Follow the steps given below to test how these JMS clients communicate with WSO2 MB. 

  1. Be sure that the WSO2 MB server is started.
  2. Log in to the management console of WSO2 AS and invoke the jmsQueue web application.
  3. Click Queue send receive sample servlet in the web application to execute the JMS queue send-receive sample operation.
  4. You can verify this from the console logs of the broker as well: A subscription has been added and deleted for the queue named "testQueue".
  • No labels