Search in sources :

Example 56 with Destination

use of javax.jms.Destination in project qpid by apache.

the class Console method addConnection.

/**
 * Connect the console to the AMQP cloud.
 * <p>
 * This is an extension to the standard QMF2 API allowing the user to specify address options in order to allow
 * finer control over the Console's request and reply queues, e.g. explicit name, non-default size or durability.
 *
 * @param conn a javax.jms.Connection
 * @param addressOptions options String giving finer grained control of the receiver queue.
 * <p>
 * As an example the following gives the Console's queues the name test-console, size = 500000000 and ring policy.
 * <pre>
 * " ; {link: {name:'test-console', x-declare: {arguments: {'qpid.policy_type': ring, 'qpid.max_size': 500000000}}}}"
 * </pre>
 * Note that the Console uses several queues so this will actually create a test-console queue plus a
 * test-console-async queue and a test-console-event queue.
 * <p>
 * If a name parameter is not present temporary queues will be created, but the other options will still be applied.
 */
public void addConnection(final Connection conn, final String addressOptions) throws QmfException {
    // to the same Console instance at the same time.
    synchronized (this) {
        if (_connection != null) {
            throw new QmfException("Multiple connections per Console is not supported");
        }
        _connection = conn;
    }
    try {
        String syncReplyAddressOptions = addressOptions;
        String asyncReplyAddressOptions = addressOptions;
        String eventAddressOptions = addressOptions;
        if (!addressOptions.equals("")) {
            // If there are address options supplied we need to check if a name parameter is present.
            String[] split = addressOptions.split("name");
            if (split.length == 2) {
                // If options contains a name parameter we extract it and create variants for async and event queues.
                // Look for the end of the key/value block
                split = split[1].split("[,}]");
                // Remove initial colon, space any any quotes.
                String nameValue = split[0].replaceAll("[ :'\"]", "");
                // Hopefully at this point nameValue is actually the value of the name parameter.
                asyncReplyAddressOptions = asyncReplyAddressOptions.replace(nameValue, nameValue + "-async");
                eventAddressOptions = eventAddressOptions.replace(nameValue, nameValue + "-event");
            }
        }
        String topicBase = "qmf." + _domain + ".topic";
        _syncSession = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create a MessageProducer for the QMF topic address used to broadcast requests
        Destination topicAddress = _syncSession.createQueue(topicBase);
        _broadcaster = _syncSession.createProducer(topicAddress);
        // Data Indications, QMF Events, Heartbeats etc. from the broker (or other Agents).
        if (!_disableEvents) {
            // TODO it should be possible to bind _eventConsumer and _asyncResponder to the same queue
            // if I can figure out the correct AddressString to use, probably not a big deal though.
            _asyncSession = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // Set up MessageListener on the Event Address
            Destination eventAddress = _asyncSession.createQueue(topicBase + "/agent.ind.#" + eventAddressOptions);
            _eventConsumer = _asyncSession.createConsumer(eventAddress);
            _eventConsumer.setMessageListener(this);
            // Create the asynchronous JMSReplyTo _replyAddress and MessageConsumer
            _asyncReplyAddress = _asyncSession.createQueue(_address + ".async" + asyncReplyAddressOptions);
            _asyncResponder = _asyncSession.createConsumer(_asyncReplyAddress);
            _asyncResponder.setMessageListener(this);
        }
        // so makes sense if only to get that warm and fuzzy feeling of keeping findbugs happy :-)
        synchronized (this) {
            // Create a MessageProducer for the QMF direct address, mainly used for request/response
            Destination directAddress = _syncSession.createQueue("qmf." + _domain + ".direct");
            _requester = _syncSession.createProducer(directAddress);
            // Create the JMSReplyTo _replyAddress and MessageConsumer
            _replyAddress = _syncSession.createQueue(_address + syncReplyAddressOptions);
            _responder = _syncSession.createConsumer(_replyAddress);
            _connection.start();
            // we've any received *real* Agent updates or not.
            if (_disableEvents) {
                _brokerAgentName = "broker";
                Map<String, String> map = new HashMap<String, String>();
                map.put("_name", _brokerAgentName);
                Agent agent = new Agent(map, this);
                _agents.put(_brokerAgentName, agent);
                _agentAvailable = true;
            } else {
                // If Asynchronous Behaviour is enabled Broadcast an Agent Locate message to get Agent info quickly.
                broadcastAgentLocate();
            }
            // Wait until the Broker Agent has been located (this should generally be pretty quick)
            while (!_agentAvailable) {
                long startTime = System.currentTimeMillis();
                try {
                    wait(_replyTimeout * 1000);
                } catch (InterruptedException ie) {
                    continue;
                }
                // Measure elapsed time to test against spurious wakeups and ensure we really have timed out
                long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
                if (!_agentAvailable && elapsedTime >= _replyTimeout) {
                    _log.info("Broker Agent not found");
                    throw new QmfException("Broker Agent not found");
                }
            }
            // Timer used for tidying up Subscriptions.
            _timer = new Timer(true);
        }
    } catch (JMSException jmse) {
        // If we can't create the QMF Destinations there's not much else we can do
        _log.info("JMSException {} caught in addConnection()", jmse.getMessage());
        throw new QmfException("Failed to create sessions or destinations " + jmse.getMessage());
    }
}
Also used : Destination(javax.jms.Destination) Timer(java.util.Timer) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JMSException(javax.jms.JMSException) QmfException(org.apache.qpid.qmf2.common.QmfException)

Example 57 with Destination

use of javax.jms.Destination in project ignite by apache.

the class IgniteJmsStreamerTest method testQueueFromName.

/**
 * @throws Exception If failed.
 */
public void testQueueFromName() throws Exception {
    Destination dest = new ActiveMQQueue(QUEUE_NAME);
    // produce messages into the queue
    produceObjectMessages(dest, false);
    try (IgniteDataStreamer<String, String> dataStreamer = grid().dataStreamer(DEFAULT_CACHE_NAME)) {
        JmsStreamer<ObjectMessage, String, String> jmsStreamer = newJmsStreamer(ObjectMessage.class, dataStreamer);
        jmsStreamer.setDestinationType(Queue.class);
        jmsStreamer.setDestinationName(QUEUE_NAME);
        // subscribe to cache PUT events and return a countdown latch starting at CACHE_ENTRY_COUNT
        CountDownLatch latch = subscribeToPutEvents(CACHE_ENTRY_COUNT);
        jmsStreamer.start();
        // all cache PUT events received in 10 seconds
        latch.await(10, TimeUnit.SECONDS);
        assertAllCacheEntriesLoaded();
        jmsStreamer.stop();
    }
}
Also used : Destination(javax.jms.Destination) ObjectMessage(javax.jms.ObjectMessage) ActiveMQQueue(org.apache.activemq.command.ActiveMQQueue) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 58 with Destination

use of javax.jms.Destination in project rocketmq-externals by apache.

the class JmsClientIT method testConfigInURI.

@Test
public void testConfigInURI() throws Exception {
    JmsBaseConnectionFactory connectionFactory = new JmsBaseConnectionFactory(new URI(String.format("rocketmq://xxx?%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s", CommonConstant.PRODUCERID, producerId, CommonConstant.CONSUMERID, consumerId, CommonConstant.NAMESERVER, nameServer, CommonConstant.CONSUME_THREAD_NUMS, consumeThreadNums, CommonConstant.SEND_TIMEOUT_MILLIS, 10 * 1000, CommonConstant.INSTANCE_NAME, "JMS_TEST")));
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    connection.start();
    try {
        Destination destination = session.createTopic(topic + ":" + messageType);
        session.createConsumer(destination);
        session.createProducer(destination);
        DefaultMQPushConsumer rmqPushConsumer = (DefaultMQPushConsumer) getRMQPushConsumerExt(consumerId).getConsumer();
        Assert.assertNotNull(rmqPushConsumer);
        Assert.assertEquals(consumerId, rmqPushConsumer.getConsumerGroup());
        Assert.assertEquals("JMS_TEST", rmqPushConsumer.getInstanceName());
        Assert.assertEquals(consumeThreadNums, rmqPushConsumer.getConsumeThreadMax());
        Assert.assertEquals(consumeThreadNums, rmqPushConsumer.getConsumeThreadMin());
        Assert.assertEquals(nameServer, rmqPushConsumer.getNamesrvAddr());
        DefaultMQProducer mqProducer = (DefaultMQProducer) JmsTestUtil.getMQProducer(producerId);
        Assert.assertNotNull(mqProducer);
        Assert.assertEquals(producerId, mqProducer.getProducerGroup());
        Assert.assertEquals("JMS_TEST", mqProducer.getInstanceName());
        Assert.assertEquals(10 * 1000, mqProducer.getSendMsgTimeout());
        Assert.assertEquals(nameServer, mqProducer.getNamesrvAddr());
        Thread.sleep(2000);
    } finally {
        connection.close();
    }
}
Also used : Destination(javax.jms.Destination) JmsBaseConnectionFactory(org.apache.rocketmq.jms.domain.JmsBaseConnectionFactory) Connection(javax.jms.Connection) DefaultMQPushConsumer(org.apache.rocketmq.client.consumer.DefaultMQPushConsumer) URI(java.net.URI) DefaultMQProducer(org.apache.rocketmq.client.producer.DefaultMQProducer) Session(javax.jms.Session) Test(org.junit.Test)

Example 59 with Destination

use of javax.jms.Destination in project rocketmq-externals by apache.

the class JmsClientIT method testProducerAndConsume_TwoConsumer.

@Test
public void testProducerAndConsume_TwoConsumer() throws Exception {
    Connection connection = createConnection(producerId, consumerId);
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destinationA = session.createTopic("TopicA");
    Destination destinationB = session.createTopic("TopicB");
    final CountDownLatch countDownLatch = new CountDownLatch(2);
    JmsTestListener listenerA = new JmsTestListener(10, countDownLatch);
    JmsTestListener listenerB = new JmsTestListener(10, countDownLatch);
    try {
        // two consumers
        MessageConsumer messageConsumerA = session.createConsumer(destinationA);
        messageConsumerA.setMessageListener(listenerA);
        MessageConsumer messageConsumerB = session.createConsumer(destinationB);
        messageConsumerB.setMessageListener(listenerB);
        // producer
        MessageProducer messageProducer = session.createProducer(destinationA);
        connection.start();
        for (int i = 0; i < 10; i++) {
            TextMessage message = session.createTextMessage(text + i);
            Assert.assertNull(message.getJMSMessageID());
            messageProducer.send(message);
            Assert.assertNotNull(message.getJMSMessageID());
        }
        for (int i = 0; i < 10; i++) {
            TextMessage message = session.createTextMessage(text + i);
            Assert.assertNull(message.getJMSMessageID());
            messageProducer.send(destinationB, message);
            Assert.assertNotNull(message.getJMSMessageID());
        }
        if (countDownLatch.await(30, TimeUnit.SECONDS)) {
            Thread.sleep(2000);
        }
        Assert.assertEquals(10, listenerA.getConsumedNum());
        Assert.assertEquals(10, listenerB.getConsumedNum());
    } finally {
        // Close the connection
        connection.close();
    }
}
Also used : Destination(javax.jms.Destination) MessageConsumer(javax.jms.MessageConsumer) JmsTestListener(org.apache.rocketmq.jms.JmsTestListener) Connection(javax.jms.Connection) MessageProducer(javax.jms.MessageProducer) CountDownLatch(java.util.concurrent.CountDownLatch) TextMessage(javax.jms.TextMessage) Session(javax.jms.Session) Test(org.junit.Test)

Example 60 with Destination

use of javax.jms.Destination in project rocketmq-externals by apache.

the class JmsConsumerIT method testStartIdempotency.

@Test
public void testStartIdempotency() throws Exception {
    JmsBaseConnectionFactory connectionFactory = new JmsBaseConnectionFactory(new URI("rocketmq://xxx?consumerId=" + consumerId + "&nameServer=" + nameServer));
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    checkConsumerState(consumerId, true, false);
    try {
        Destination destination = session.createTopic(topic + ":" + messageType);
        MessageConsumer consumer = session.createConsumer(destination);
        consumer.setMessageListener(listener);
        checkConsumerState(consumerId, false, false);
        ((JmsBaseMessageConsumer) consumer).startConsumer();
        checkConsumerState(consumerId, false, true);
        Destination destination1 = session.createTopic(topic2 + ":" + messageType);
        MessageConsumer consumer1 = session.createConsumer(destination1);
        consumer1.setMessageListener(listener);
        ((JmsBaseMessageConsumer) consumer1).startConsumer();
        checkConsumerState(consumerId, false, true);
        // the start is idempotent
        connection.start();
        connection.start();
        Thread.sleep(5000);
    } finally {
        connection.close();
    }
}
Also used : Destination(javax.jms.Destination) JmsBaseMessageConsumer(org.apache.rocketmq.jms.domain.JmsBaseMessageConsumer) MessageConsumer(javax.jms.MessageConsumer) JmsBaseMessageConsumer(org.apache.rocketmq.jms.domain.JmsBaseMessageConsumer) JmsBaseConnectionFactory(org.apache.rocketmq.jms.domain.JmsBaseConnectionFactory) Connection(javax.jms.Connection) URI(java.net.URI) Session(javax.jms.Session) Test(org.junit.Test)

Aggregations

Destination (javax.jms.Destination)178 Test (org.junit.Test)51 TextMessage (javax.jms.TextMessage)47 Session (javax.jms.Session)46 JMSException (javax.jms.JMSException)45 Connection (javax.jms.Connection)32 MessageProducer (javax.jms.MessageProducer)31 Message (javax.jms.Message)30 ConnectionFactory (javax.jms.ConnectionFactory)24 MessageConsumer (javax.jms.MessageConsumer)24 JMSContext (javax.jms.JMSContext)16 CountDownLatch (java.util.concurrent.CountDownLatch)15 ObjectMessage (javax.jms.ObjectMessage)12 StubTextMessage (org.springframework.jms.StubTextMessage)11 InitialContext (javax.naming.InitialContext)10 ActiveMQQueue (org.apache.activemq.command.ActiveMQQueue)10 Queue (javax.jms.Queue)8 ActiveMQConnectionFactory (org.apache.activemq.ActiveMQConnectionFactory)8 MapMessage (javax.jms.MapMessage)7 HashMap (java.util.HashMap)6