Running an ActiveMQ Broker with Maven

By | February 22, 2016

This short example will show you how to run an ActiveMQ broker with Maven using the ActiveMQ Maven plug-in, as part of running tests.
In the example I will implement a Java unit test, but I think that running ActiveMQ with Maven will be more useful when, for instance, wanting to run a broker in connection to running a Gatling stress tests (which can also be run using Maven).
The example consists of three files:

  • A Maven pom.xml file.
    Manages dependencies as well as contains the configuration of the ActiveMQ Maven plug-in etc.
  • An activemq.xml file.
    Contains broker configuration.
  • A JUnit test class implemented in Java.

Maven pom.xml File

The Maven pom.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>se.ivankrizsan.java</groupId>
    <artifactId>maven-amqexample</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <activemq.version>5.13.0</activemq.version>
        <spring.version>4.2.4.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>${activemq.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--
                Starts an minimal embedded ActiveMQ broker for the test.
            -->
            <plugin>
                <groupId>org.apache.activemq.tooling</groupId>
                <artifactId>activemq-maven-plugin</artifactId>
                <version>${activemq.version}</version>
                <configuration>
                    <configUri>xbean:file:./src/test/resources/activemq.xml</configUri>
                    <fork>true</fork>
                    <systemProperties>
                        <property>
                            <name>org.apache.activemq.default.directory.prefix</name>
                            <value>./target/</value>
                        </property>
                    </systemProperties>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.activemq</groupId>
                        <artifactId>activemq-spring</artifactId>
                        <version>${activemq.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.activemq</groupId>
                        <artifactId>activemq-leveldb-store</artifactId>
                        <version>${activemq.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>start-activemq</id>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <phase>process-test-resources</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

The spring-jms dependency is used by the test-class that will be implemented below and is not necessary to start the ActiveMQ broker.

ActiveMQ Configuration File

The ActiveMQ configuration file I have used is provided below. Further details on the ActiveMQ XML configuration can be found in the ActiveMQ documentation.
The activemq.xml file is to be located in the src/test/resources directory in the Maven project.

<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="ActiveMQData" useShutdownHook="false">
        <persistenceAdapter>
            <kahaDB directory="ActiveMQData/kahadb"/>
        </persistenceAdapter>

        <transportConnectors>
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=100"/>
        </transportConnectors>
    </broker>
</beans>

Note the useShutdownHook=”false” attribute in the <broker> element. The ActiveMQ shutdown-hook is disabled in order to avoid an exception when the JMV in which the test(s) has run is shut down.

JUnit Test Class

Finally the JUnit test class is provided as to show that things work as expected and not as a good example on how to implement JUnit tests:

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import javax.jms.*;

/**
 * Simple test case that sends and receives messages to/from a JMS broker.
 *
 * @author Ivan Krizsan
 */
public class MyJmsTest {
    /* Constant(s): */
    public static final String AMQ_BROKER_URL = "tcp://localhost:61616";
    public static final String QUEUE_NAME = "testQueue";

    /* Instance variable(s): */
    protected ConnectionFactory mActiveMQConnectionFactory;
    protected JmsTemplate mJmsTemplate;

    @Before
    public void setUp() {
        mActiveMQConnectionFactory = new ActiveMQConnectionFactory(AMQ_BROKER_URL);
        mJmsTemplate = new JmsTemplate(mActiveMQConnectionFactory);
        final Destination theTestDestination = new ActiveMQQueue(QUEUE_NAME);
        mJmsTemplate.setDefaultDestination(theTestDestination);
        mJmsTemplate.setReceiveTimeout(500L);
    }

    @Test
    public void someIntegrationTest() throws Exception {
        System.out.println("Test starting...");
        sendMessages();
        receiveMessages();
        System.out.println("Test done!");
    }

    protected void sendMessages() {
        for (int i = 1; i <= 10; i++) {
            final int theMessageIndex = i;
            final String theMessageString = "Message: " + theMessageIndex;
            System.out.println("Sending message with text: " + theMessageString);

            mJmsTemplate.send(new MessageCreator() {
                public Message createMessage(Session inJmsSession) throws JMSException {
                    TextMessage theTextMessage = inJmsSession.createTextMessage(theMessageString);
                    theTextMessage.setIntProperty("messageNumber", theMessageIndex);

                    return theTextMessage;
                }
            });
        }
    }

    protected void receiveMessages() throws Exception {
        Message theReceivedMessage = mJmsTemplate.receive();
        while (theReceivedMessage != null) {
            if (theReceivedMessage instanceof TextMessage) {
                final TextMessage theTextMessage = (TextMessage)theReceivedMessage;
                System.out.println("Received a message with text: " + theTextMessage.getText());
            }

            theReceivedMessage = mJmsTemplate.receive();
        }
        System.out.println("All messages received!");
    }
}

Running the Example

The example can be run by going to a console/terminal window and issuing the following command:

mvn test

Among a lot of other output, you should see the following in the console:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running MyJmsTest
Test starting...
Sending message with text: Message: 1
Sending message with text: Message: 2
Sending message with text: Message: 3
Sending message with text: Message: 4
Sending message with text: Message: 5
Sending message with text: Message: 6
Sending message with text: Message: 7
Sending message with text: Message: 8
Sending message with text: Message: 9
Sending message with text: Message: 10
Received a message with text: Message: 1
Received a message with text: Message: 2
Received a message with text: Message: 3
Received a message with text: Message: 4
Received a message with text: Message: 5
Received a message with text: Message: 6
Received a message with text: Message: 7
Received a message with text: Message: 8
Received a message with text: Message: 9
Received a message with text: Message: 10
All messages received!
Test done!
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.092 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

That’s it for this time. Happy coding!

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *