javax.jms.JMSConsumer Java Examples

The following examples show how to use javax.jms.JMSConsumer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JmsContextTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendStreamMessage() throws JMSException, InterruptedException {
   JmsProducerCompletionListenerTest.CountingCompletionListener cl = new JmsProducerCompletionListenerTest.CountingCompletionListener(1);
   JMSProducer producer = context.createProducer();
   producer.setAsync(cl);
   StreamMessage msg = context.createStreamMessage();
   msg.setStringProperty("name", name.getMethodName());
   String bprop = "booleanProp";
   String iprop = "intProp";
   msg.setBooleanProperty(bprop, true);
   msg.setIntProperty(iprop, 42);
   msg.writeBoolean(true);
   msg.writeInt(67);
   producer.send(queue1, msg);
   JMSConsumer consumer = context.createConsumer(queue1);
   Message msg2 = consumer.receive(100);
   Assert.assertNotNull(msg2);
   Assert.assertTrue(cl.completionLatch.await(1, TimeUnit.SECONDS));
   StreamMessage sm = (StreamMessage) cl.lastMessage;
   Assert.assertEquals(true, sm.getBooleanProperty(bprop));
   Assert.assertEquals(42, sm.getIntProperty(iprop));
   Assert.assertEquals(true, sm.readBoolean());
   Assert.assertEquals(67, sm.readInt());
}
 
Example #2
Source File: SharedConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void sharedDurableSubSimpleRoundRobin() throws Exception {
   context = cf.createContext();
   try {
      JMSConsumer con1 = context.createSharedDurableConsumer(topic1, "mySharedCon");
      JMSConsumer con2 = context.createSharedDurableConsumer(topic1, "mySharedCon");
      context.start();
      JMSProducer producer = context.createProducer();
      int numMessages = 10;
      for (int i = 0; i < numMessages; i++) {
         producer.send(topic1, "msg:" + i);
      }

      for (int i = 0; i < numMessages; i += 2) {
         String msg = con1.receiveBody(String.class, 5000);
         msg = con2.receiveBody(String.class, 5000);
      }

   } finally {
      context.close();
   }
}
 
Example #3
Source File: JmsEventChannelTestCase.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@After
public void stop() throws Exception {
    JMSContext context = factory.createContext();
    Destination channel = context.createQueue(MockEvent.class.getName());
    JMSConsumer consumer = context.createConsumer(channel);
    // 清理测试消息
    logger.info("清理JMS测试消息开始");
    AtomicInteger count = new AtomicInteger();
    consumer.setMessageListener((data) -> {
        String message = StringUtility.format("清理JMS测试消息[{}]", count.incrementAndGet());
        logger.info(message);
    });
    Thread.sleep(1000L);
    logger.info("清理JMS测试消息结束");
    factory.close();
}
 
Example #4
Source File: JMSContextTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testJMSContextConsumerThrowsMessageFormatExceptionOnMalformedBody() throws Exception {
   Queue queue = createQueue(true, "ContextMalformedBodyTestQueue");

   JMSContext context = qraConnectionFactory.createContext();
   JMSProducer producer = context.createProducer();

   TextMessage message = context.createTextMessage("TestMessage");
   producer.send(queue, message);

   JMSConsumer consumer = context.createConsumer(queue);

   try {
      consumer.receiveBody(Boolean.class);
      fail("Should thrown MessageFormatException");
   } catch (MessageFormatRuntimeException mfre) {
      // Do nothing test passed
   } catch (Exception e) {
      fail("Threw wrong exception, should be MessageFormatRuntimeException, instead got: " + e.getClass().getCanonicalName());
   }
}
 
Example #5
Source File: JmsContext.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createDurableConsumer(Topic topic, String name, String selector, boolean noLocal) {
    try {
        return startIfNeeded(new JmsConsumer(getSession(), (JmsMessageConsumer) getSession().createDurableConsumer(topic, name, selector, noLocal)));
    } catch (JMSException jmse) {
        throw JmsExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example #6
Source File: JmsContextTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloseSecondContextConnectionRemainsOpen() throws JMSException {
   JMSContext localContext = context.createContext(JMSContext.CLIENT_ACKNOWLEDGE);
   Assert.assertEquals("client_ack", JMSContext.CLIENT_ACKNOWLEDGE, localContext.getSessionMode());
   JMSProducer producer = localContext.createProducer();
   JMSConsumer consumer = localContext.createConsumer(queue1);

   final int pass = 1;
   for (int idx = 0; idx < 2; idx++) {
      Message m = localContext.createMessage();
      int intProperty = random.nextInt();
      m.setIntProperty("random", intProperty);
      Assert.assertNotNull(m);
      producer.send(queue1, m);
      m = null;
      Message msg = consumer.receive(100);
      Assert.assertNotNull("must have a msg", msg);
      Assert.assertEquals(intProperty, msg.getIntProperty("random"));
      /* In the second pass we close the connection before ack'ing */
      if (idx == pass) {
         localContext.close();
      }
      /**
       * From {@code JMSContext.close()}'s javadoc:<br/>
       * Invoking the {@code acknowledge} method of a received message from a closed connection's
       * session must throw an {@code IllegalStateRuntimeException}. Closing a closed connection
       * must NOT throw an exception.
       */
      try {
         msg.acknowledge();
         Assert.assertEquals("connection should be open on pass 0. It is " + pass, 0, idx);
      } catch (javax.jms.IllegalStateException expected) {
         // HORNETQ-1209 "JMS 2.0" XXX JMSContext javadoc says we must expect a
         // IllegalStateRuntimeException here. But Message.ack...() says it must throws the
         // non-runtime variant.
         Assert.assertEquals("we only close the connection on pass " + pass, pass, idx);
      }
   }
}
 
Example #7
Source File: ActiveMQJMSContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector) {
   checkSession();
   try {
      ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createSharedDurableConsumer(topic, name, messageSelector));
      checkAutoStart();
      return consumer;
   } catch (JMSException e) {
      throw JmsExceptionUtils.convertToRuntimeException(e);
   }
}
 
Example #8
Source File: JmsContext.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createSharedConsumer(Topic topic, String name, String selector) {
    try {
        return startIfNeeded(new JmsConsumer(getSession(), (JmsMessageConsumer) getSession().createSharedConsumer(topic, name, selector)));
    } catch (JMSException jmse) {
        throw JmsExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example #9
Source File: JMSConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
public void doTestReceiveBodyFailsDoesNotAcceptMessage(int sessionMode) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer);

        testPeer.expectBegin();

        final String content = "Message-Content";
        Queue queue = context.createQueue("myQueue");

        DescribedType amqpValueContent = new AmqpValueDescribedType(content);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueContent);
        testPeer.expectEnd();
        testPeer.expectClose();

        JMSConsumer messageConsumer = context.createConsumer(queue);
        try {
            messageConsumer.receiveBody(Boolean.class, 3000);
            fail("Should not read as Boolean type");
        } catch (MessageFormatRuntimeException mfre) {
        }

        context.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example #10
Source File: JMSConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testReceiveMessageWithReceiveZeroTimeout() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer);

        testPeer.expectBegin();

        Queue queue = context.createQueue("myQueue");

        DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueNullContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

        JMSConsumer messageConsumer = context.createConsumer(queue);
        Message receivedMessage = messageConsumer.receive(0);

        assertNotNull("A message should have been recieved", receivedMessage);

        testPeer.expectEnd();
        testPeer.expectClose();
        context.close();

        testPeer.waitForAllHandlersToComplete(2000);
    }
}
 
Example #11
Source File: JmsContext.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination, String selector, boolean noLocal) {
    try {
        return startIfNeeded(new JmsConsumer(getSession(), (JmsMessageConsumer) getSession().createConsumer(destination, selector, noLocal)));
    } catch (JMSException jmse) {
        throw JmsExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example #12
Source File: JmsContext.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination, String selector) {
    try {
        return startIfNeeded(new JmsConsumer(getSession(), (JmsMessageConsumer) getSession().createConsumer(destination, selector)));
    } catch (JMSException jmse) {
        throw JmsExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example #13
Source File: JmsContext.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination) {
    try {
        return startIfNeeded(new JmsConsumer(getSession(), (JmsMessageConsumer) getSession().createConsumer(destination)));
    } catch (JMSException jmse) {
        throw JmsExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example #14
Source File: ActiveMQJMSContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * this is to ensure Context.acknowledge would work on ClientACK
 */
Message setLastMessage(final JMSConsumer consumer, final Message lastMessageReceived) {
   if (sessionMode == CLIENT_ACKNOWLEDGE) {
      lastMessagesWaitingAck = lastMessageReceived;
   }
   return lastMessageReceived;
}
 
Example #15
Source File: ActiveMQJMSContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector) {
   checkSession();
   try {
      ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createSharedConsumer(topic, sharedSubscriptionName, messageSelector));
      checkAutoStart();
      return consumer;
   } catch (JMSException e) {
      throw JmsExceptionUtils.convertToRuntimeException(e);
   }
}
 
Example #16
Source File: ActiveMQJMSContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination) {
   checkSession();
   try {
      ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createConsumer(destination));
      checkAutoStart();
      return consumer;
   } catch (JMSException e) {
      throw JmsExceptionUtils.convertToRuntimeException(e);
   }
}
 
Example #17
Source File: ActiveMQJMSContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination, String messageSelector) {
   checkSession();
   try {
      ActiveMQJMSConsumer consumer = new ActiveMQJMSConsumer(this, session.createConsumer(destination, messageSelector));
      checkAutoStart();
      return consumer;
   } catch (JMSException e) {
      throw JmsExceptionUtils.convertToRuntimeException(e);
   }
}
 
Example #18
Source File: JmsPoolJMSConsumerTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceiveNoWait() throws JMSException {
    JMSConsumer consumer = context.createConsumer(context.createTemporaryQueue());

    assertNull(consumer.receiveNoWait());

    consumer.close();

    try {
        consumer.receiveNoWait();
        fail("Should not be able to interact with closed consumer");
    } catch (IllegalStateRuntimeException ise) {}
}
 
Example #19
Source File: JmsProducerCompletionListenerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompletionListener() throws InterruptedException {
   CountingCompletionListener cl = new CountingCompletionListener(TOTAL_MSGS);
   Assert.assertEquals(null, producer.getAsync());
   producer.setAsync(cl);
   Assert.assertEquals(cl, producer.getAsync());
   producer.setAsync(null);
   producer.setAsync(cl);
   JMSConsumer consumer = context.createConsumer(queue);
   sendMessages(context, producer, queue, TOTAL_MSGS);
   receiveMessages(consumer, 0, TOTAL_MSGS, true);
   assertEquals(TOTAL_MSGS, cl.completion.get());
   context.close();
   Assert.assertTrue("completion listener should be called", cl.completionLatch.await(3, TimeUnit.SECONDS));
}
 
Example #20
Source File: JMSConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testConsumerReceiveNoWaitThrowsIfConnectionLost() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer);

        testPeer.expectBegin();

        Queue queue = context.createQueue("queue");

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlow(false, notNullValue(UnsignedInteger.class));
        testPeer.expectLinkFlow(true, notNullValue(UnsignedInteger.class));
        testPeer.dropAfterLastHandler();

        final JMSConsumer consumer = context.createConsumer(queue);

        try {
            consumer.receiveNoWait();
            fail("An exception should have been thrown");
        } catch (JMSRuntimeException jmsre) {
            // Expected
        }

        try {
            context.close();
        } catch (Throwable ignored) {
        }
    }
}
 
Example #21
Source File: ConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextOnConsumerAMQP() throws Throwable {
   if (!isNetty()) {
      // no need to run the test, there's no AMQP support
      return;
   }

   assertNull(server.getAddressInfo(SimpleString.toSimpleString("queue")));

   ConnectionFactory factory = createFactory(2);
   JMSContext context = factory.createContext("admin", "admin", Session.AUTO_ACKNOWLEDGE);

   try {
      javax.jms.Queue queue = context.createQueue("queue");

      JMSConsumer consumer = context.createConsumer(queue);

      ServerConsumer serverConsumer = null;
      for (ServerSession session : server.getSessions()) {
         for (ServerConsumer sessionConsumer : session.getServerConsumers()) {
            serverConsumer = sessionConsumer;
         }
      }

      consumer.close();

      Assert.assertTrue(serverConsumer.getProtocolContext() instanceof ProtonServerSenderContext);

      final AMQPSessionContext sessionContext = ((ProtonServerSenderContext)
         serverConsumer.getProtocolContext()).getSessionContext();

      Wait.assertEquals(0, () -> sessionContext.getSenderCount(), 1000, 10);
   } finally {
      context.stop();
      context.close();
   }
}
 
Example #22
Source File: JMSSessionFactory.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param topic
 * @param consumer
 * @param producer
 * @param commandHandler
 */
MessagingSessionContainer(Topic topic,
                          JMSConsumer consumer,
                          JMSProducer producer,
                          IOperationHandler commandHandler) {
    this.topic = topic;
    this.consumer = consumer;
    this.producer = producer;
    this.commandHandler = commandHandler;
    setupHandler();
}
 
Example #23
Source File: JMSSessionFactory.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * Called to add a consumer to the JMS topic specific to the given design id.
 * @param designId
 * @param handler
 */
public synchronized MessagingSessionContainer joinSession(String designId, IOperationHandler handler) {
    logger.debug("Joining session {}", designId);
    JMSContext context = connectionFactory.createContext();
    Topic sessionTopic = context.createTopic(JAVA_JMS_TOPIC_SESSION + designId);
    // Subscribe to the topic
    JMSConsumer consumer = context.createConsumer(sessionTopic, null, true);
    // When a new node joins the distributed session, it doesn't know about the session(s) attached to the
    // other nodes already in the session(s).
    return new MessagingSessionContainer(sessionTopic, consumer, context.createProducer(), handler);
}
 
Example #24
Source File: JMSContextImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(final Destination destination, final String messageSelector) {
    try {
        final JMSConsumerImpl consumer = new JMSConsumerImpl(this, session().createConsumer(destination, messageSelector));
        checkAutoStart();
        return consumer;
    } catch (final JMSException e) {
        throw toRuntimeException(e);
    }
}
 
Example #25
Source File: JmsPoolJMSConsumerTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceiveBodyTimed() throws JMSException {
    JMSConsumer consumer = context.createConsumer(context.createTemporaryQueue());

    try {
        consumer.receiveBody(String.class, 1);
        fail("Should not be able to interact with closed consumer");
    } catch (JMSRuntimeException ise) {}
}
 
Example #26
Source File: ActiveMqArtemisFacade.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Message> registerConcreteListenerImplementation(Destination destination) {
    JMSConsumer consumer = context.createConsumer(destination);
    final CompletableFuture<Message> incomingMessageFuture = new CompletableFuture<>();
    //noinspection Convert2Lambda,Anonymous2MethodRef
    consumer.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            incomingMessageFuture.complete(message);
        }
    });
    return incomingMessageFuture;
}
 
Example #27
Source File: JmsPoolJMSConsumerTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceiveBody() throws JMSException {
    JMSConsumer consumer = context.createConsumer(context.createTemporaryQueue());

    try {
        consumer.receiveBody(String.class);
        fail("Should not be able to interact with closed consumer");
    } catch (JMSRuntimeException ise) {}
}
 
Example #28
Source File: JmsPoolJMSConsumerTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMessageSelector() throws JMSException {
    JMSConsumer consumer = context.createConsumer(context.createTemporaryQueue(), "Color = Red");

    assertNotNull(consumer.getMessageSelector());
    assertEquals("Color = Red", consumer.getMessageSelector());

    consumer.close();

    try {
        consumer.getMessageSelector();
        fail("Should not be able to interact with closed consumer");
    } catch (IllegalStateRuntimeException ise) {}
}
 
Example #29
Source File: JmsPoolJMSConsumerTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceiveTimed() throws JMSException {
    JMSConsumer consumer = context.createConsumer(context.createTemporaryQueue());

    assertNull(consumer.receive(1));

    consumer.close();

    try {
        consumer.receive(1);
        fail("Should not be able to interact with closed consumer");
    } catch (IllegalStateRuntimeException ise) {}
}
 
Example #30
Source File: JmsContext.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSConsumer createSharedDurableConsumer(Topic topic, String name, String selector) {
    try {
        return startIfNeeded(new JmsConsumer(getSession(), (JmsMessageConsumer) getSession().createSharedDurableConsumer(topic, name, selector)));
    } catch (JMSException jmse) {
        throw JmsExceptionSupport.createRuntimeException(jmse);
    }
}