Forum Discussion

sonya_m's avatar
sonya_m
SmartBear Alumni (Retired)
4 years ago

[TechCorner Challenge #10] Connecting to JMS using Groovy script

Hi Community!

 

The TechCorner Challenge continues. You can put your skills to the test and learn something new about the tool, as well as bring more valuable content to the ReadyAPI Community! And, those who complete tasks, will get into the Leaderboard.

This week's task:

 

Sometimes, the JMS test step doesn’t suit you since you might have custom JMS settings, or you need to add additional logic before or after sending/receiving a JMS message. In this case, you can use Groovy scripts. So, try writing a sample script to connect to JMS that can be used as a basis for further customization.

 

Task: write a script for the Groovy Script test step which creates a connection to a JMS provider (ActiveMQ, WebSphere or another), sends a JMS message to the “Test“ queue, and shows all messages in this queue.

 

Difficulty

 

Notes: use the manual connection, not the HermesJMS session.

 

Check out the TechCorner Leaderboard and detailed participation rules here.

Good luck, as always!

 

  • Task: write a script for the Groovy Script test step which creates a connection to a JMS provider (ActiveMQ, WebSphere or another), sends a JMS message to the “Test“ queue, and shows all messages in this queue.

     

    This is a solution created for [TechCorner Challenge #10]

     

     

    Okay, that's what I thought too nmrao. I am just not certain how to actually tie in to the JMS server connection as entered into the "JMS" connection panel. I do have a script that does everything by hand though. Which is as below. This does require the ActiveMQ client jar placed in the appropriate lib folder in ReadAPI install.

     

    This script browses a queue, per the requirements of the task. It will NOT consume messages from a queue.

     

    package org.apache.activemq.simple;
    
    import javax.jms.*;
    import org.apache.activemq.ActiveMQConnectionFactory;
    import org.apache.activemq.command.ActiveMQQueue;
    
    
    def queueNames = ["Test"];
    def msgToSend = 10;
    def msgCount = 0;
    def user = "username"
    def pass = "password"
    def host = "tcp://x.x.x.x:61616"
    
    // Write to Queue
    for (queueName in queueNames)
    {
    	ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, pass, host);
    
    	Connection connection = connectionFactory.createConnection();
    	connection.start();
    
    	Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    	Destination dest = session.createQueue(queueName);
    	MessageProducer prod = session.createProducer(dest);
    	
    	for (int i = 1; i <= msgToSend; i++)
    	{
    		
    		def messageText = "This is message $i." 
    		TextMessage message = session.createTextMessage(messageText);
    		prod.send(message);
    	}
    	prod.close()
    	
    	QueueBrowser qb = session.createBrowser(dest);
    	Enumeration msgs = qb.getEnumeration();
    	if (!msgs.hasMoreElements())
    	{
    		log.info("Queue is empty.")
    	}
    	else
    	{
    		while (msgs.hasMoreElements())
    		{
    			Message tempMsg = (Message)msgs.nextElement();
    			log.info(tempMsg);
    			msgCount++
    		}
    	}
    	qb.close();
    	session.close();
    	connection.close();
    }
    log.info("Messages sent: $msgToSend. Messages browsed: $msgCount.");
    
    System.gc();
    System.sleep(1000);

     

     

     

    This script CONSUMES messages, use at your own risk. Still a worthwhile example, in my opinion.

     

     

    package org.apache.activemq.simple;
    
    import javax.jms.*;
    import org.apache.activemq.ActiveMQConnectionFactory;
    import org.apache.activemq.command.ActiveMQQueue;
    
    
    // For multiple queues
    def queueNames = ["Test"];
    
    // Configurable messages to send
    def msgToSend = 10;
    
    // Keep track of how many are read
    def msgCount = 0;
    
    // ActiveMQ connection information
    def user = "userName"
    def pass = "P@ssw0rd100$"
    def host = "tcp://x.x.x.x:61616"
    
    // Write to / Read From Queue
    for (queueName in queueNames)
    {
    	// Create ActiveMQ connection, session, destination, and producer.
    	ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, pass, host);
    
    	Connection connection = connectionFactory.createConnection();
    	connection.start();
    
    	Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    	Destination dest = session.createQueue(queueName);
    	MessageProducer prod = session.createProducer(dest);
    	
    	// Send messages
    	for (int i = 1; i <= msgToSend; i++)
    	{
    		def messageText = "This is message $i." 
    		TextMessage message = session.createTextMessage(messageText);
    		prod.send(message);
    	}
    	// Close producer.
    	prod.close()
    	
    	//Create consumer.
    	MessageConsumer consumer = session.createConsumer(dest);
    	Message message = consumer.receive(5000);
    	while (message != null)
    	{
    		msgCount++;
    		message = consumer.receive(5000);
    	}
    	// Close consumer, session, and connection.
    	consumer.close();
    	session.close();
    	connection.close();
    }
    
    log.info("Messages sent: $msgToSend. Messages received: $msgCount.");
    

     

     

     

     

9 Replies

    • sonya_m's avatar
      sonya_m
      SmartBear Alumni (Retired)

      Hi nmrao !

      Yes, we do have a requirement that makes this task a bit different from what's specified in the article🙂

       

      >>

      Notes: use the manual connection, not the HermesJMS session.

      <<

      • groovyguy's avatar
        groovyguy
        Community Hero

        So I've done something similar which relies on downloading and placing the ActiveMQ jar in the ReadyAPI library. This seems like a much easier way. I can see how to manually set up the ActiveMQ connection in the JMS connections, but I cannot figure out how to utilize that from a groovy script. At least, I haven't figured it out yet.

         

        I may have misread this, and it seems like whatever solution is there will require the JAR of the provider being used. In my instance, this will require the ActiveMQ jar. Is that a safe assumption to make, or is there a way to do this without that?