All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.pronoia.junit.activemq.AbstractActiveMQClientResource Maven / Gradle / Ivy

Go to download

A library of JUnit assertions and resources to assist in testing with ActiveMQ clients and brokers.

There is a newer version: 1.0.3
Show newest version
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pronoia.junit.activemq;

import java.io.Serializable;
import java.net.URI;
import java.util.Map;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQDestination;
import org.junit.rules.ExternalResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.pronoia.junit.activemq.VmConnectionFactoryUtils.createConnectionFactoryWithFailover;

/**
 * Abstract base class for ActiveMQ client resources.
 */
public abstract class AbstractActiveMQClientResource extends ExternalResource {
    Logger log = LoggerFactory.getLogger(this.getClass());

    ActiveMQConnectionFactory connectionFactory;
    Connection connection;
    Session session;
    ActiveMQDestination destination;

    public AbstractActiveMQClientResource(URI brokerURI) {
        this(new ActiveMQConnectionFactory(brokerURI));
    }

    public AbstractActiveMQClientResource(ActiveMQConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    public AbstractActiveMQClientResource(EmbeddedActiveMQBroker embeddedActiveMQBroker) {
        this(createConnectionFactoryWithFailover(embeddedActiveMQBroker));
    }

    public AbstractActiveMQClientResource(URI brokerURI, String userName, String password) {
        this(new ActiveMQConnectionFactory(userName, password, brokerURI));
    }

    public AbstractActiveMQClientResource(String destinationName, URI brokerURI) {
        this(destinationName, new ActiveMQConnectionFactory(brokerURI));
    }

    public AbstractActiveMQClientResource(String destinationName, ActiveMQConnectionFactory connectionFactory) {
        this(connectionFactory);
        destination = createDestination(destinationName);
    }

    public AbstractActiveMQClientResource(String destinationName, EmbeddedActiveMQBroker embeddedActiveMQBroker) {
        this(destinationName, createConnectionFactoryWithFailover(embeddedActiveMQBroker));
    }


    public AbstractActiveMQClientResource(String destinationName, URI brokerURI, String userName, String password) {
        this(destinationName, new ActiveMQConnectionFactory(userName, password, brokerURI));
    }

    public static void setMessageProperties(Message message, Map properties) throws JMSException {
        if (properties != null) {
            for (Map.Entry property : properties.entrySet()) {
                message.setObjectProperty(property.getKey(), property.getValue());
            }
        }
    }

    public abstract String getClientId();

    protected abstract void createClient() throws JMSException;

    protected ActiveMQDestination createDestination(String destinationName) {
        if (destinationName != null) {
            return ActiveMQDestination.createDestination(destinationName, getDestinationType());
        }

        return null;
    }

    public abstract byte getDestinationType();

    public String getDestinationName() {
        return (destination != null) ? destination.toString() : null;
    }

    /**
     * Invoked by JUnit to setup the client resource.
     */
    @Override
    protected void before() throws Throwable {
        log.info("Starting {}: {}", this.getClass().getSimpleName(), connectionFactory.getBrokerURL());

        this.start();

        super.before();
    }

    /**
     * Invoked by JUnit to tear down the client resource.
     */
    @Override
    protected void after() {
        log.info("Stopping {}: {}", this.getClass().getSimpleName(), connectionFactory.getBrokerURL());

        super.after();

        this.stop();
    }

    /**
     * Manually stop the Client.
     */
    public void stop() {
        try {
            connection.close();
        } catch (JMSException jmsEx) {
            log.warn("Exception encountered closing JMS Connection", jmsEx);
        }
    }

    /**
     * Manually start the Client.
     */
    public void start() {
        try {
            try {
                connection = connectionFactory.createConnection();
                String clientId = getClientId();
                if (clientId != null) {
                    connection.setClientID(clientId);
                }
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                createClient();
            } catch (JMSException jmsEx) {
                throw new RuntimeException("Producer initialization failed" + this.getClass().getSimpleName(), jmsEx);
            }
            connection.start();
        } catch (JMSException jmsEx) {
            throw new IllegalStateException("Producer failed to start", jmsEx);
        }
        log.info("Ready to produce messages to {}", connectionFactory.getBrokerURL());
    }

    public String getBrokerURL() {
        return connectionFactory.getBrokerURL();
    }

    public StreamMessage createStreamMessage() throws JMSException {
        return session.createStreamMessage();
    }

    public BytesMessage createMessage(byte[] body) throws JMSException {
        return this.createMessage(body, null);
    }

    public BytesMessage createMessage(byte[] body, Map properties) throws JMSException {
        BytesMessage message = this.createBytesMessage();
        if (body != null) {
            message.writeBytes(body);
        }

        setMessageProperties(message, properties);

        return message;
    }

    public BytesMessage createBytesMessage() throws JMSException {
        return session.createBytesMessage();
    }

    public TextMessage createMessage(String body) throws JMSException {
        return this.createMessage(body, null);
    }

    public TextMessage createMessage(String body, Map properties) throws JMSException {
        TextMessage message = this.createTextMessage();
        if (body != null) {
            message.setText(body);
        }

        setMessageProperties(message, properties);

        return message;
    }

    public TextMessage createTextMessage() throws JMSException {
        return session.createTextMessage();
    }

    public MapMessage createMessage(Map body) throws JMSException {
        return this.createMessage(body, null);
    }

    public MapMessage createMessage(Map body, Map properties) throws JMSException {
        MapMessage message = this.createMapMessage();

        if (body != null) {
            for (Map.Entry entry : body.entrySet()) {
                message.setObject(entry.getKey(), entry.getValue());
            }
        }

        setMessageProperties(message, properties);

        return message;
    }

    public MapMessage createMapMessage() throws JMSException {
        return session.createMapMessage();
    }

    public ObjectMessage createMessage(Serializable body) throws JMSException {
        return this.createMessage(body, null);
    }

    public ObjectMessage createMessage(Serializable body, Map properties) throws JMSException {
        ObjectMessage message = this.createObjectMessage();

        if (body != null) {
            message.setObject(body);
        }

        setMessageProperties(message, properties);

        return message;
    }

    public ObjectMessage createObjectMessage() throws JMSException {
        return session.createObjectMessage();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy