Friday, May 16, 2014

How to append a query parameter to an API published from WSO2 API Manager

How to append a query parameter to an API published from WSO2 API Manager

There are some situations where you need to send some url query parameters with the request when publishing an API through the API Manager. But You do not need client to send those parameters with the request URL. In that case how do you append those parameters to the endpoint url. In this blog post see how to append a query parametr to endpoint url.

First you need to create an API and published the API. Please refer how to create an API to create an API in WSO2 API Manager.

Then the requirement is once you invoke the API with some query parameter, It will call the actual service endpoint with some other query parameter.

You can append query parameters to the endpoint url from API Manager. synapse property 'REST_URL_POSTFIX' can be used to manage the query parameter. Once you create an api, what you have to do is that, you need to update the synapse configuration of the api created with the relevant property. the property REST_URL_POSTFIX will give you the query string coming into the api from the client. Then you can change the query string as you need.

<property name="REST_URL_POSTFIX" expression="fn:concat(get-property('axis2','REST_URL_POSTFIX'), '&amp;exchange=xyz')" scope="axis2" type="STRING"/>

Once You create an API, You can add parameter by following bellow steps.
1) Login to AM(https://ipaddress:port/carbon/) and Click on main > Source View
Then you can see the synapse configuration

2) Find the api configuration you have created by the api name.

3) Then update the insequence of the api with bellow property.
<property name="REST_URL_POSTFIX" expression="fn:concat(get-property('axis2','REST_URL_POSTFIX'), '&amp;exchange=xyz')" scope="axis2" type="STRING"/>

4) Click on update button.

Then your api looks as bellow. 

 <api xmlns="http://ws.apache.org/ns/synapse" name="admin--testapi" context="/testapi" version="1.0.0" version-type="url">  
   <resource methods="GET" url-mapping="/*">  
     <inSequence>  
       <property name="POST_TO_URI" value="true" scope="axis2"/>  
       <property name="REST_URL_POSTFIX" expression="fn:concat(get-property('axis2','REST_URL_POSTFIX'), '&amp;exchange=xyz')" scope="axis2" type="STRING"/>  
       <filter source="$ctx:AM_KEY_TYPE" regex="PRODUCTION">  
         <then>  
           <send>  
             <endpoint name="admin--testapi_APIEndpoint_0">  
               <address uri="http://localhost:8080/stockquote/getQuote">  
                 <timeout>  
                   <duration>30000</duration>  
                   <responseAction>fault</responseAction>  
                 </timeout>  
                 <suspendOnFailure>  
                   <errorCodes>-1</errorCodes>  
                   <initialDuration>0</initialDuration>  
                   <progressionFactor>1.0</progressionFactor>  
                   <maximumDuration>0</maximumDuration>  
                 </suspendOnFailure>  
                 <markForSuspension>  
                   <errorCodes>-1</errorCodes>  
                 </markForSuspension>  
               </address>  
             </endpoint>  
           </send>  
         </then>  
         <else>  
           <sequence key="_sandbox_key_error_"/>  
         </else>  
       </filter>  
     </inSequence>  
     <outSequence>  
       <send/>  
     </outSequence>  
   </resource>  
   <handlers>  
     <handler class="org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler"/>  
     <handler class="org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler">  
       <property name="id" value="A"/>  
       <property name="policyKey" value="gov:/apimgt/applicationdata/tiers.xml"/>  
     </handler>  
     <handler class="org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageHandler"/>  
     <handler class="org.wso2.carbon.apimgt.usage.publisher.APIMgtGoogleAnalyticsTrackingHandler"/>  
     <handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler"/>  
   </handlers>  
 </api>


Ex: Client request  http://localhost:8280/testapi/1.0.0?symbol=abc
Actual request required for back end
http://localhost:8080/stockquote/getQuote?symbol=abc&exchange=xyz

Here you have added exchange parameter to the service call. As above you can modify the query string as you required.

Wednesday, March 26, 2014

How to secure your services with OAuth2 using WSO2 API Manager

Securing Your Service with OAuth2 Using WSO2 API Manager

If you host a service, You may need some access control on that service. Otherwise any one can access that service. In such case you can use WSO2 API Manager to achieve this easily. API Manager can secure your service with OAuth2.

I have a backend service host on apache tomcat server. It can be invoked both http GET and POST method.

if I send a bellow request, It will receive a response
http://localhost:8080/stockquote/getQuote?symbol=wso2

Response:
<getQuoteResponse>
       <symbol>wso2</symbol>
       <lastPrice>67.73111720684315</lastPrice>
       <company>wso2 Company</company>
       <timeStamp>Wed Mar 26 17:49:25 IST 2014</timeStamp></getQuoteResponse>

Then I am going to create an api on WSO API Manager (wso2am-1.6.0) and keep my actual backend service behind the API Manager.

Steps to create an api
1) First I start a wso2am-1.6.0
2) Login to Publisher using user credential admin
       https://localhost:9443/publisher/ 
3) Add a api with below parameters.

       Name    : stockQuoteApi
       Context : stockquote
       Version : 1.0.0
       Tier Availability : Gold
       Production Endpoint : http://localhost:8080/stockquote/getQuote

With the above parameters, We can create an api successfully.

4) Publish the created api
      Select the created api and change LifeCycle  to Publish

Then We have to subscribe for the created api.

5) Login to Store using user credential admin then you can see the api cretaed
       https://10.100.1.107:9443/store/
6) Then select the api. You can see the access URL of the created api "http://10.100.1.107:8280/stockQuote/1.0.0"
Then choose DefaultApplication in Applications drop down box lay on right corner.

7) Then Click On Subscribe button.

8) Then click On Generate button in Keys - Production. Then you can see the Access Token.

Now API Creation is completed.

Then Try to access the api. You can use any http client to access the service. Inv this case I am going to use curl.

Now I am trying to invoke the api with below command.

curl  http://localhost:8280/stockQuote/1.0.0?symbol=wso2

Then I will receive a below response.

<ams:fault xmlns:ams="http://wso2.org/apimanager/security">
     <ams:code>900902</ams:code>
     <ams:message>Missing Credentials</ams:message>
     <ams:description>Required OAuth credentials not provided</ams:description>
</ams:fault>

That means Your api is secured. So you need to provide the access token to invoke the service. You can find the access token in subscription page.

Then invoke the service with below command.

curl  -H "Authorization :Bearer gQsoJqhYv15f_JiEVg46y44olcUa" http://localhost:8280/stockQuote/1.0.0?symbol=wso2

Now I get the correct response which is provided by my actual backend service running on tomcat server.

<getQuoteResponse>
      <symbol>wso2</symbol>
      <lastPrice>147.95183566530514</lastPrice>
      <company>wso2 Company</company>
      <timeStamp>Wed Mar 26 18:32:30 IST 2014</timeStamp></getQuoteResponse>

As the below api, You can create any number of api to secure your services. It is very easy and useful.







Wednesday, March 12, 2014

How to add HTTP Basic Authentication header to the outgoing message of WSO2 ESB Proxy service


Here I am going to discuss how to access the web service secured by HTTP Basic Authentication via a proxy service deployed on WSO2 ESB.

The scenario is client invoke the proxy service without the Authorization header and WSO2 ESB proxy service add  the Authorization to out going message and call the actual backend service.


Here You need to set authorization header to HTTP request sent bu the ESB. You can achieve this by using property mediator  with the propert name Authorization.


<property xmlns:ns="http://org.apache.synapse/xsd"  
           name="Authorization"  
           expression="fn:concat('Basic ', base64Encode('username:password'))"  
           scope="transport"/>

Below is the header you need to send with the request.

authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=


You can set this header within the proxy service by configuring property mediator as below.


<proxy xmlns="http://ws.apache.org/ns/synapse"  
     name="stockQuote"  
     transports="https,http"  
     statistics="disable"  
     trace="disable"  
     startOnLoad="true">  
   <target>  
    <inSequence>  
      <property name="symbol1" value="2" scope="default" type="STRING"/>  
      <property xmlns:ns="http://org.apache.synapse/xsd"  
           name="Authorization"  
           expression="fn:concat('Basic ', base64Encode('username:password'))"  
           scope="transport"/>  
      <send>  
       <endpoint>  
         <address uri="http://localhost:8080/echo/echoheaders"/>  
       </endpoint>  
      </send>  
    </inSequence>  
   </target>  
   <description/>  
 </proxy>

Then the outgoing request from the ESB will contains the authorization header and backend service can be accessed.


How to conver http POST request to http GET request using WSO2 ESB proxy service


In this blog, I am going to discuss how to send a HTTP GET request using WSO2 ESB proxy service. Here is the sample scenario.





Client sends a post request with a SOAP message to the proxy service and proxy service retrieve a parameter form the payload and make a HTTP get request with a URI parameter to get the response form the actual backend. Back end service is a rest service. Then Proxy service get the rest response and convert it in to SOAP message and send back to the client.

Below proxy configuration make above scenario worked.

Prerequisite
WSO2 ESB 4.7.0
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="stockQuote"
       transports="https,http"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target>
      <inSequence>
         <property name="symbol1" value="2" scope="default" type="STRING"/>
         <property xmlns:m1="http://services.samples/xsd"
                   xmlns:m0="http://services.samples"
                   name="symbol"
                   expression="//m0:getQuote/m0:request/m1:symbol"
                   scope="default"
                   type="STRING"/>
         <property xmlns:ns="http://org.apache.synapse/xsd"
                   name="REST_URL_POSTFIX"
                   expression="fn:concat('?symbol=',get-property('symbol1'))"
                   scope="axis2"
                   type="STRING"/>
         <log level="custom">
            <property name="url" expression="get-property('axis2','REST_URL_POSTFIX')"/>
         </log>
         <property name="HTTP_METHOD" value="GET" scope="axis2" type="STRING"/>
         <send>
            <endpoint>
               <address uri="http://localhost:8080/stockquote/getQuote" format="rest"/>
            </endpoint>
         </send>
      </inSequence>
      <outSequence>
         <property name="messageType" value="text/xml" scope="axis2"/>
         <send/>
      </outSequence>
   </target>
   <description/>
</proxy>
                                

Once you send a request with below payload to the stockquote proxy

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.samples" xmlns:xsd="http://services.samples/xsd">  
   <soapenv:Header/>  
   <soapenv:Body>  
    <ser:getQuote>  
      <!--Optional:-->  
      <ser:request>  
       <!--Optional:-->  
       <xsd:symbol>wso2</xsd:symbol>  
      </ser:request>  
    </ser:getQuote>  
   </soapenv:Body>  
 </soapenv:Envelope>  

It will make a HTTP GET call to the URL and get back the response
http://localhost:8080/stockquote/getQuote?symbol=wso2

Then proxy service send response back to the client

Tuesday, March 11, 2014

How to enable WSO2 Carbon Management Console via HTTP Transport

WSO2 carbon product management console is only exposed in HTTPS by default due to the security aspects. Anyway if someone want to access the management console via HTTP, It also possible. You can just configure it and access.

To enable admin console via HTTP,

1) Go to the $WSO2_HOME/repository/conf and open carbon.xml
2) Uncomment the EnableHTTPAdminConsole property. 

 <EnableHTTPAdminConsole>true</EnableHTTPAdminConsole>

Then start the server. You can access the management console from http://127.0.0.1:9763/carbon/





Wednesday, March 5, 2014

How to increase the WSO2 carbon management console session timeout

In WSO2 carbon products, The default value of the management console session timeout is 15 minutes. if user is idle for more than 15 min, It expire the user session, Then user need to provide the credential again to  access the management console. if you need to increase the session time out you can just change it through the configuration

1) Go to repository/conf/tomcat/carbon/WEB-INF
2) Change the session-timeout value in web.xml file

     <session-config>
        <session-timeout>15</session-timeout>
    </session-config>

Please note that timeout is defined in minutes.

3) Restart the server

Then, Once you log into the web console, It keeps the user session as you configured.

Wednesday, May 1, 2013

How to write WSO2 ESB and JMS Integration Test

In the previous blogs post JMS Proxy Service using WSO2 ESB  we discussed about WSO2 ESB JMS transport and JMS proxy service. And the post How to  write a ESB Product Integration test we discussed about writing product integration test using WSO2 test Automation Framework.

In this blog post I am going to demonstrate How to write a WSO2 ESB integration test with JMS Broker. so I am going to write a test class to test the functionality of the JMS proxy service behavior.

In this scenario we have to do following steps to test the functionality.
1) Starting a JMS broker(ActiveMQ)
2) Changing the axis2.xml to enable JMS transport in ESB
3) Copy activemq-core-5.7.0.jar, geronimo-j2ee-management_1.1_spec-1.0.1.jar to $WSO2_ESB_HOME/repository/components/lib.
4) Starting ESB Server
5) Deploying the proxy service
6) Sending messages to the destination queue for proxy service to consume.

First you have to find the place to put your test class. so go to the "platform/branches/x.x.x/products/esb/x.x.x/modules/integration/tests"  as your ESB product version. tests module is the place where we write the integration tests.

then find the package named "org.wso2.carbon.esb.jms.transport.test". This is the best place to put your JMS related test classes. Because there is a class named "JMSBrokerStartupTestCase" which reduced above 1, 2 , 3 and 4 steps from your test class. Otherwise you have to write the codes for above 3 steps also your test class itself.

Since JMSBrokerStartupTestCase will look after the 1, 2 , 3 and 4 steps, you need to focus on your test scenario only and It will save your time.

JMSBrokerStartupTestCase has two methods running under @BeforeTest() annotation. So those methods execute before and after the all other test executions of the test classes in jms.transport package.so It will reduce the time takes to execute all test classes. because no need to repeat the JMS broker startup and ESB configuration within your test classes when writing and running.

package org.wso2.carbon.esb.jms.transport.test;  
   
 import org.testng.Assert;  
 import org.testng.annotations.AfterTest;  
 import org.testng.annotations.BeforeTest;  
 import org.wso2.carbon.automation.core.ProductConstant;  
 import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder;  
 import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables;  
 import org.wso2.carbon.automation.core.utils.jmsbrokerutils.controller.JMSBrokerController;  
 import org.wso2.carbon.automation.core.utils.jmsbrokerutils.controller.config.JMSBrokerConfiguration;  
 import org.wso2.carbon.automation.core.utils.jmsbrokerutils.controller.config.JMSBrokerConfigurationProvider;  
 import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager;  
   
 import java.io.File;  
   
 public class JMSBrokerStartupTestCase {  
   private EnvironmentBuilder builder = null;  
   private JMSBrokerController activeMqBroker;  
   private ServerConfigurationManager serverManager = null;  
   
   private final String ACTIVEMQ_CORE = "activemq-core-5.2.0.jar";  
   private final String GERONIMO_J2EE_MANAGEMENT = "geronimo-j2ee-management_1.1_spec-1.0.1.jar";  
   private final String GERONIMO_JMS = "geronimo-jms_1.1_spec-1.1.1.jar";  
   
   @BeforeTest(alwaysRun = true)  
   public void startJMSBroker() throws Exception {  
   
     builder = new EnvironmentBuilder().esb(ProductConstant.ADMIN_USER_ID);  
     EnvironmentVariables esbServer = builder.build().getEsb();  
     serverManager = new ServerConfigurationManager(esbServer.getBackEndUrl());  
   
     if (builder.getFrameworkSettings().getEnvironmentSettings()  
         .is_builderEnabled()) {  
       //starting jms broker  
       activeMqBroker = new JMSBrokerController("localhost", getJMSBrokerConfiguration());  
       if (!JMSBrokerController.isBrokerStarted()) {  
         Assert.assertTrue(activeMqBroker.start(), "JMS Broker(ActiveMQ) stating failed");  
       }  
   
       //copping dependency jms jar files to component/lib  
       serverManager.copyToComponentLib(new File(ProductConstant.getResourceLocations(ProductConstant.ESB_SERVER_NAME)  
                            + File.separator + "jar" + File.separator + ACTIVEMQ_CORE));  
   
       serverManager.copyToComponentLib(new File(ProductConstant.getResourceLocations(ProductConstant.ESB_SERVER_NAME)  
                            + File.separator + "jar" + File.separator + GERONIMO_J2EE_MANAGEMENT));  
   
       serverManager.copyToComponentLib(new File(ProductConstant.getResourceLocations(ProductConstant.ESB_SERVER_NAME)  
                            + File.separator + "jar" + File.separator + GERONIMO_JMS));  
   
       //enabling jms transport with ActiveMQ by copping axis2.xml in resource directory and restarting ESB server 
       serverManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.ESB_SERVER_NAME)  
                            + File.separator + "jms" + File.separator + "transport"  
                            + File.separator + "axis2config" + File.separator  
                            + "activemq" + File.separator + "axis2.xml"));  
   
     }  
   }  
   
   @AfterTest(alwaysRun = true)  
   public void stopJMSBroker() throws Exception {  
     if (builder.getFrameworkSettings().getEnvironmentSettings().is_builderEnabled()) {  
       try {  
         //reverting the changes done to esb sever  
         if (serverManager != null) {  
           serverManager.removeFromComponentLib(ACTIVEMQ_CORE);  
           serverManager.removeFromComponentLib(GERONIMO_J2EE_MANAGEMENT);  
           serverManager.removeFromComponentLib(GERONIMO_JMS);  
           serverManager.restoreToLastConfiguration();  
         }  
   
       } finally {  
         if (activeMqBroker != null) {  
           Assert.assertTrue(activeMqBroker.stop(), "JMS Broker(ActiveMQ) Stopping failed");  
         }  
       }  
   
   
     }  
   }  
   
   private JMSBrokerConfiguration getJMSBrokerConfiguration() {  
     return JMSBrokerConfigurationProvider.getInstance().getBrokerConfiguration();  
   }  
 }  

For Integration test, Automation framework start a Embedded ActiveMQ Broker and do the necessary ESB server configuration.

Now we have JMS transport enabled ESB server and ActiveMQ JMS broker up and running in our machine.

Then we see how to automate our test scenario. only need to do the steps 5 and 6.

as steps 5 , I am going to deploy the bellow proxy service.
<?xml version="1.0" encoding="UTF-8"?>  
 <definitions xmlns="http://ws.apache.org/ns/synapse">  
   <proxy name="JmsProxy" transports="jms" startOnLoad="true" trace="disable">  
     <target>  
       <inSequence>  
         <property action="set" name="OUT_ONLY" value="true"/>  
         <property name="FORCE_SC_ACCEPTED" value="true" scope="axis2"/>  
       </inSequence>  
       <endpoint>  
         <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>  
       </endpoint>  
       <outSequence>  
   
         <send/>  
       </outSequence>  
       <parameter name="transport.jms.ContentType">  
         <rules>  
           <jmsProperty>contentType</jmsProperty>  
           <default>application/xml</default>  
         </rules>  
       </parameter>  
     </target>  
   </proxy>  
   
   
 </definitions>  

So I save above file as jms_transport_proxy_service.xml in the directory /artifacts/ESB/jms/transport under test resource directory.

Then add a test class as mentioned bellow.

package org.wso2.carbon.esb.jms.transport.test;  
   
 import org.apache.axiom.om.OMElement;  
 import org.testng.Assert;  
 import org.testng.annotations.AfterClass;  
 import org.testng.annotations.BeforeClass;  
 import org.testng.annotations.Test;  
 import org.wso2.carbon.automation.core.utils.jmsbrokerutils.client.JMSQueueMessageConsumer;  
 import org.wso2.carbon.automation.core.utils.jmsbrokerutils.client.JMSQueueMessageProducer;  
 import org.wso2.carbon.automation.core.utils.jmsbrokerutils.controller.config.JMSBrokerConfigurationProvider;  
 import org.wso2.carbon.esb.ESBIntegrationTest;  
 import org.wso2.carbon.esb.util.JMSEndpointManager;  
   
 public class JMSTransportProxyTestCase extends ESBIntegrationTest {  
   @BeforeClass(alwaysRun = true)  
   public void deployeService() throws Exception {  
     super.init();  
     OMElement synapse = esbUtils.loadClasspathResource("/artifacts/ESB/jms/transport/jms_transport_proxy_service.xml");  
     updateESBConfiguration(JMSEndpointManager.setConfigurations(synapse));  
   }  
   
   @Test(groups = {"wso2.esb"}, description = "Test proxy service with jms transport")  
   public void testJMSProxy() throws Exception {  
   
     JMSQueueMessageProducer sender = new JMSQueueMessageProducer(JMSBrokerConfigurationProvider.getInstance().getBrokerConfiguration());  
     String queueName = "JmsProxy";  
     try {  
       sender.connect(queueName);  
       for (int i = 0; i < 3; i++) {  
         sender.pushMessage("<?xml version='1.0' encoding='UTF-8'?>" +  
                   "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"" +  
                   " xmlns:ser=\"http://services.samples\" xmlns:xsd=\"http://services.samples/xsd\">" +  
                   "  <soapenv:Header/>" +  
                   "  <soapenv:Body>" +  
                   "   <ser:placeOrder>" +  
                   "     <ser:order>" +  
                   "      <xsd:price>100</xsd:price>" +  
                   "      <xsd:quantity>2000</xsd:quantity>" +  
                   "      <xsd:symbol>JMSTransport</xsd:symbol>" +  
                   "     </ser:order>" +  
                   "   </ser:placeOrder>" +  
                   "  </soapenv:Body>" +  
                   "</soapenv:Envelope>");  
       }  
     } finally {  
       sender.disconnect();  
     }  
   
     Thread.sleep(10000);  
     JMSQueueMessageConsumer consumer = new JMSQueueMessageConsumer(JMSBrokerConfigurationProvider.getInstance().getBrokerConfiguration());  
     try {  
       consumer.connect(queueName);  
       for (int i = 0; i < 3; i++) {  
         if (consumer.popMessage() != null) {  
           Assert.fail("JMS Proxy service failed to pick the messages from Queue");  
         }  
       }  
     } finally {  
       consumer.disconnect();  
     }  
   }  
   
   
   @AfterClass(alwaysRun = true)  
   public void UndeployeService() throws Exception {  
     super.cleanup();  
   }  
 }  

In this test class you can see 3 methods
1) deployeService() under @BeforeClass Annotation
This will set JMS endpoint(if needed) and deploy the your proxy service
 
2) testJMSProxy() under @Test Annotation
This will send a message to the destination queue and wait for proxy service to consume the message. then check the message is available in the destination queue. if it is not available, proxy service is working fine. it dequeue the message from the queue.

3) UndeployeService() under @AfterClass Annotation
This will undeploy the proxy service deployed

An important method you can see in  deployeService() method  
JMSEndpointManager.setConfigurations(synapse);

What does JMSEndpointManager does ?

As above step 1, I mentioned ActiveMQ broker is used as the JMS Broker. ActiveMQ Broker is used only when running test under integration environment. (Product building time by maven.). when we moved to platform test that means servers are supposed to up and running with proper configuration(you can set test to run in platform environment by setting properties in automation.properties file under resource directory)

Then your test classes run with WSO2 MB as the JMS Broker instead of AcitveMQ Embedded broker started by framework. (You have to start a MB server as well). JMSEndpointManager will replace the endpoint details in your synapse configuration as for the WSO2 MB broker.

It will replace bellow in synapse configuration if only execution.environment is defined as platform.
org.apache.activemq.jndi.ActiveMQInitialContextFactory >>> org.wso2.andes.jndi.PropertiesFileInitialContextFactory

tcp://127.0.0.1:61616 >>> repository/conf/jndi.properties

In above synapse configuration, above replacement not happened because of no JMS endpoint defined in synapse configuration

Other important this is that, if your test class to run with WSO2 MB, Proxy service destination queue uri also changed. If WSO2 ESB to work with WSO2 MB you need to defined any queue or topic you defined in your synapse configuration or queue of JMS in proxy jndi.properties file in $WSO2_ESB_HOME/repository/conf directory.

Refer http://docs.wso2.org/wiki/display/MB201/Integrating+WSO2+ESB for more details for ESB and MB Integartion

So we have already added a resource file in artifacts/ESB/jms/transport/jndi.properties under test resource directory. you must add the queue or topic you used into jndi.properties. When we run a test in platform environment, we can easily copy that file into ESB and run our test without any issue. That also keep in mind when writing JMS related test.

# register some connection factories  
 # connectionfactory.[jndiname] = [ConnectionURL]  
 connectionfactory.QueueConnectionFactory = amqp://admin:admin@clientID/carbon?brokerlist='tcp://localhost:5676'  
 connectionfactory.TopicConnectionFactory = amqp://admin:admin@clientID/carbon?brokerlist='tcp://localhost:5676'  
   
 # register some queues in JNDI using the form  
 # queue.[jndiName] = [physicalName]     
 queue.JmsProxy = JmsProxy  
  
 # register some topics in JNDI using the form  
 # topic.[jndiName] = [physicalName]  
 topic.TestTopic = TestTopic  


Now we have finished writing the scenario. Then we need to verify the test class can be executed and the test scenario is working fine without any failure.

To enable test classes to run , you need to add entry in testng.xml(can be found in resource directory) as well.

To Run all the classes in org.wso2.carbon.esb.jms.transport.test package
<test name="jms-transport" preserve-order="true" verbose="2">  
     <packages>  
       <package name="org.wso2.carbon.esb.jms.transport.test.*"/>  
     </packages>  
   </test>  

To Run single class. You need to defined JMSBrokerStartupTestCase as well. Because it is the class which start the JMS broker and configure ESB Server in Integration environment.
<test name="jms-transport" preserve-order="true" verbose="2">  
     <classes>  
       <class name="org.wso2.carbon.esb.jms.transport.test.JMSBrokerStartupTestCase"/>  
       <class name="org.wso2.carbon.esb.jms.transport.test.JMSQueueAsProxyEndpointTestCase"/>  
     </classes>  
   </test> 

Then issuing mvn clean install will run the test classes as the testng.xml.
If the test configuration as bellow, test class is executed with ActiveMQ broker
  execution.environment=integration    
  builder.enable=true  

or test class is executed with WSO2 MB Broker if you set it to bellow
 execution.environment=platform  
 builder.enable=false  

Now I think you have got a idea how to write a JMS related ESB integration test.
Like above, You can add lots of test classes to test the JMS related test scenario.

Note:  Useful JMS client classes provided by Automation Framework to ease your work.

1)org.wso2.carbon.automation.core.utils.jmsbrokerutils.client.JMSQueueMessageConsumer
          To Consume messages from a Queue
2)org.wso2.carbon.automation.core.utils.jmsbrokerutils.client.JMSQueueMessageProducer
          To send messages to a Queue
3)org.wso2.carbon.automation.core.utils.jmsbrokerutils.client.JMSTopicMessageConsumer
          To Consume messages from a Topic
4)org.wso2.carbon.automation.core.utils.jmsbrokerutils.client.JMSTopicMessagePublisher
          To publish messages to a Topic