javax.jms.Message Java Examples

The following examples show how to use javax.jms.Message. 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: MultipleProducersPagingTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
   try {
      Session session = createSession();
      MessageConsumer consumer = session.createConsumer(queue);
      barrierLatch.await();
      while (true) {
         Message msg = consumer.receive(CONSUMER_WAIT_TIME_MS);
         if (msg == null)
            break;
         msgReceived.incrementAndGet();
      }
   } catch (Exception e) {
      throw new RuntimeException(e);
   } finally {
      runnersLatch.countDown();
   }
}
 
Example #2
Source File: MessageHeaderTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a <code>Destination</code> set by the <code>setJMSReplyTo()</code>
 * method on a sended message corresponds to the <code>Destination</code> get by
 * the </code>getJMSReplyTo()</code> method.
 */
@Test
public void testJMSReplyTo_1() {
   try {
      Message message = senderSession.createMessage();
      message.setJMSReplyTo(senderQueue);
      sender.send(message);

      Message msg = receiver.receive(TestConfig.TIMEOUT);
      Destination dest = msg.getJMSReplyTo();
      Assert.assertTrue("JMS ReplyTo header field should be a Queue", dest instanceof Queue);
      Queue replyTo = (Queue) dest;
      Assert.assertEquals("JMS ReplyTo header field should be equals to the sender queue", replyTo.getQueueName(), senderQueue.getQueueName());
   } catch (JMSException e) {
      fail(e);
   }
}
 
Example #3
Source File: JmsClientAckTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if unacknowledged messages are being re-delivered when the consumer connects again.
 *
 * @throws JMSException
 */
public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException {
   connection.start();
   Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   Queue queue = session.createQueue(getQueueName());
   MessageProducer producer = session.createProducer(queue);
   producer.send(session.createTextMessage("Hello"));

   // Consume the message...
   MessageConsumer consumer = session.createConsumer(queue);
   Message msg = consumer.receive(1000);
   assertNotNull(msg);
   // Don't ack the message.

   // Reset the session.  This should cause the unacknowledged message to be re-delivered.
   session.close();
   session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

   // Attempt to Consume the message...
   consumer = session.createConsumer(queue);
   msg = consumer.receive(2000);
   assertNotNull(msg);
   msg.acknowledge();

   session.close();
}
 
Example #4
Source File: AdvisoryTests.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testMessageExpiredAdvisory() throws Exception {
   Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = s.createQueue(getClass().getName());
   MessageConsumer consumer = s.createConsumer(queue);
   assertNotNull(consumer);

   Topic advisoryTopic = AdvisorySupport.getExpiredMessageTopic((ActiveMQDestination) queue);
   MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic);
   //start throwing messages at the consumer
   MessageProducer producer = s.createProducer(queue);
   producer.setTimeToLive(1);
   for (int i = 0; i < MESSAGE_COUNT; i++) {
      BytesMessage m = s.createBytesMessage();
      m.writeBytes(new byte[1024]);
      producer.send(m);
   }

   Message msg = advisoryConsumer.receive(2000);
   assertNotNull(msg);
}
 
Example #5
Source File: CompressionOverNetworkTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapMessageCompression() throws Exception {

   MessageConsumer consumer1 = remoteSession.createConsumer(included);
   MessageProducer producer = localSession.createProducer(included);
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

   waitForConsumerRegistration(localBroker, 1, included);

   MapMessage test = localSession.createMapMessage();

   for (int i = 0; i < 100; ++i) {
      test.setString(Integer.toString(i), "test string: " + i);
   }

   producer.send(test);
   Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
   assertNotNull(msg);
   ActiveMQMapMessage message = (ActiveMQMapMessage) msg;
   assertTrue(message.isCompressed());

   for (int i = 0; i < 100; ++i) {
      assertEquals("test string: " + i, message.getString(Integer.toString(i)));
   }
}
 
Example #6
Source File: JmsServiceEngine.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
protected Message makeMessage(Session session, ModelService modelService, Map<String, Object> context)
    throws GenericServiceException, JMSException {
    List<String> outParams = modelService.getParameterNames(ModelService.OUT_PARAM, false);

    if (UtilValidate.isNotEmpty(outParams))
        throw new GenericServiceException("JMS service cannot have required OUT parameters; no parameters will be returned.");
    String xmlContext = null;

    try {
        if (Debug.verboseOn()) Debug.logVerbose("Serializing Context --> " + context, module);
        xmlContext = JmsSerializer.serialize(context);
    } catch (SerializeException | IOException e) {
        throw new GenericServiceException("Cannot serialize context.", e);
    }
    MapMessage message = session.createMapMessage();

    message.setString("serviceName", modelService.invoke);
    message.setString("serviceContext", xmlContext);
    return message;
}
 
Example #7
Source File: RequestReplyExample.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(final Message request) {
   try {
      System.out.println("Received request message: " + ((TextMessage) request).getText());

      // Extract the ReplyTo destination
      Destination replyDestination = request.getJMSReplyTo();

      System.out.println("Reply to queue: " + replyDestination);

      // Create the reply message
      TextMessage replyMessage = session.createTextMessage("A reply message");

      // Set the CorrelationID, using message id.
      replyMessage.setJMSCorrelationID(request.getJMSMessageID());

      // Send out the reply message
      replyProducer.send(replyDestination, replyMessage);

      System.out.println("Reply sent");
   } catch (JMSException e) {
      e.printStackTrace();
   }
}
 
Example #8
Source File: JMSObjectInputOperator.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
/**
 * This implementation converts a TextMessage back to a String, a
 * ByteMessage back to a byte array, a MapMessage back to a Map,
 * and an ObjectMessage back to a Serializable object. Returns
 * the plain Message object in case of an unknown message type.
 *
 * @return payload
 * @throws javax.jms.JMSException
 */
@Override
public Object convert(Message message) throws JMSException
{
  if (message instanceof TextMessage) {
    return ((TextMessage)message).getText();
  } else if (message instanceof StreamMessage) {
    return ((StreamMessage)message).readString();
  } else if (message instanceof BytesMessage) {
    return extractByteArrayFromMessage((BytesMessage)message);
  } else if (message instanceof MapMessage) {
    return extractMapFromMessage((MapMessage)message);
  } else if (message instanceof ObjectMessage) {
    return extractSerializableFromMessage((ObjectMessage)message);
  } else {
    return message;
  }
}
 
Example #9
Source File: JmsSendReceiveTestSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if the messages received are valid.
 *
 * @param receivedMessages - list of received messages.
 * @throws JMSException
 */
protected void assertMessagesReceivedAreValid(List<Message> receivedMessages) throws JMSException {
   List<Object> copyOfMessages = Arrays.asList(receivedMessages.toArray());
   int counter = 0;

   if (data.length != copyOfMessages.size()) {
      for (Iterator<Object> iter = copyOfMessages.iterator(); iter.hasNext(); ) {
         TextMessage message = (TextMessage) iter.next();
      }
   }

   assertEquals("Not enough messages received", data.length, receivedMessages.size());

   for (int i = 0; i < data.length; i++) {
      TextMessage received = (TextMessage) receivedMessages.get(i);
      String text = received.getText();
      String stringProperty = received.getStringProperty("stringProperty");
      int intProperty = received.getIntProperty("intProperty");

      assertEquals("Message: " + i, data[i], text);
      assertEquals(data[i], stringProperty);
      assertEquals(i, intProperty);
   }
}
 
Example #10
Source File: AcknowledgementTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Topics shouldn't hold on to messages if there are no subscribers
 */
@Test
public void testPersistentMessagesForTopicDropped() throws Exception {
   TopicConnection topicConn = createTopicConnection();
   TopicSession sess = topicConn.createTopicSession(true, 0);
   TopicPublisher pub = sess.createPublisher(ActiveMQServerTestCase.topic1);
   pub.setDeliveryMode(DeliveryMode.PERSISTENT);

   Message m = sess.createTextMessage("testing123");
   pub.publish(m);
   sess.commit();

   topicConn.close();

   checkEmpty(ActiveMQServerTestCase.topic1);
}
 
Example #11
Source File: JmsInvokerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void receiveTimeoutExpired() {
	JmsInvokerProxyFactoryBean pfb = new JmsInvokerProxyFactoryBean() {
		@Override
		protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException {
			return null; // faking no message received
		}
	};
	pfb.setServiceInterface(ITestBean.class);
	pfb.setConnectionFactory(this.mockConnectionFactory);
	pfb.setQueue(this.mockQueue);
	pfb.setReceiveTimeout(1500);
	pfb.afterPropertiesSet();
	ITestBean proxy = (ITestBean) pfb.getObject();

	assertThatExceptionOfType(RemoteTimeoutException.class).isThrownBy(() ->
			proxy.getAge())
		.withMessageContaining("1500 ms")
		.withMessageContaining("getAge");
}
 
Example #12
Source File: BrowserTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testBrowseWithSelector() throws Exception {
   try {
      conn = getConnectionFactory().createConnection();

      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer producer = session.createProducer(queue1);

      final int numMessages = 100;

      for (int i = 0; i < numMessages; i++) {
         Message m = session.createMessage();
         m.setIntProperty("test_counter", i + 1);
         producer.send(m);
      }
   } finally {
      removeAllMessages(queue1.getQueueName(), true);
   }
}
 
Example #13
Source File: SelectorTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testLikeComparisons() throws Exception {
   Message message = createMessage();

   assertSelector(message, "quote LIKE '''In G_d We Trust'''", true);
   assertSelector(message, "quote LIKE '''In Gd_ We Trust'''", false);
   assertSelector(message, "quote NOT LIKE '''In G_d We Trust'''", false);
   assertSelector(message, "quote NOT LIKE '''In Gd_ We Trust'''", true);

   assertSelector(message, "foo LIKE '%oo'", true);
   assertSelector(message, "foo LIKE '%ar'", false);
   assertSelector(message, "foo NOT LIKE '%oo'", false);
   assertSelector(message, "foo NOT LIKE '%ar'", true);

   assertSelector(message, "foo LIKE '!_%' ESCAPE '!'", true);
   assertSelector(message, "quote LIKE '!_%' ESCAPE '!'", false);
   assertSelector(message, "foo NOT LIKE '!_%' ESCAPE '!'", false);
   assertSelector(message, "quote NOT LIKE '!_%' ESCAPE '!'", true);

   assertSelector(message, "punctuation LIKE '!#$&()*+,-./:;<=>?@[\\]^`{|}~'", true);
}
 
Example #14
Source File: MessageReceiver.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        if (TextMessage.class.isAssignableFrom(message.getClass())) {
            String receiverClassName = getClass().getName();
            logger.info("Receiver {}, sending message.", receiverClassName);
            logger.debug("Event message: {}", message);
            TextMessage textMessage = (TextMessage) message;
            T event = gson.fromJson(textMessage.getText(), eventClass);
            logger.debug("{} event {}", receiverClassName, event);
            handleEvent(event);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example #15
Source File: AmqpPublisherActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void verifyPublishedMessage() throws Exception {
    final ArgumentCaptor<JmsMessage> messageCaptor = ArgumentCaptor.forClass(JmsMessage.class);

    verify(messageProducer, timeout(1000)).send(messageCaptor.capture(), any(CompletionListener.class));

    final Message message = messageCaptor.getValue();
    assertThat(message).isNotNull();
    assertThat(message.getStringProperty("thing_id")).isEqualTo(TestConstants.Things.THING_ID.toString());
    assertThat(message.getStringProperty("suffixed_thing_id")).isEqualTo(
            TestConstants.Things.THING_ID + ".some.suffix");
    assertThat(message.getStringProperty("prefixed_thing_id")).isEqualTo(
            "some.prefix." + TestConstants.Things.THING_ID);
    assertThat(message.getStringProperty("eclipse")).isEqualTo("ditto");
    assertThat(message.getStringProperty("device_id"))
            .isEqualTo(TestConstants.Things.THING_ID.toString());
}
 
Example #16
Source File: AbstractEndpointHandler.java    From tomee with Apache License 2.0 6 votes vote down vote up
private Object[] wrapMessageForAmq5(final Object[] args) {
    if (args == null || args.length != 1 || DelegateMessage.class.isInstance(args[0])) {
        return args;
    }

    if (isAmq == null) {
        synchronized (this) {
            if (isAmq == null) {
                isAmq = args[0].getClass().getName().startsWith("org.apache.activemq.");
            }
        }
    }
    if (isAmq) {
        args[0] = JMS2.wrap(Message.class.cast(args[0]));
    }
    return args;
}
 
Example #17
Source File: JMSMessageHeadersType.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void read(Message message) throws JMSException {
    setJMSCorrelationID(message.getJMSCorrelationID());
    setJMSDeliveryMode(Integer.valueOf(message.getJMSDeliveryMode()));
    setJMSExpiration(Long.valueOf(message.getJMSExpiration()));
    setJMSMessageID(message.getJMSMessageID());
    setJMSPriority(Integer.valueOf(message.getJMSPriority()));
    setJMSRedelivered(Boolean.valueOf(message.getJMSRedelivered()));
    setJMSTimeStamp(Long.valueOf(message.getJMSTimestamp()));
    setJMSType(message.getJMSType());
    setSOAPJMSTargetService(message.getStringProperty(JMSSpecConstants.TARGETSERVICE_FIELD));
    setSOAPJMSBindingVersion(message.getStringProperty(JMSSpecConstants.BINDINGVERSION_FIELD));
    setSOAPJMSContentType(message.getStringProperty(JMSSpecConstants.CONTENTTYPE_FIELD));
    setSOAPJMSContentEncoding(message.getStringProperty(JMSSpecConstants.CONTENTENCODING_FIELD));
    setSOAPJMSSOAPAction(message.getStringProperty(JMSSpecConstants.SOAPACTION_FIELD));
    if (message.propertyExists(JMSSpecConstants.ISFAULT_FIELD)) {
        setSOAPJMSIsFault(message.getBooleanProperty(JMSSpecConstants.ISFAULT_FIELD));
    }
    setSOAPJMSRequestURI(message.getStringProperty(JMSSpecConstants.REQUESTURI_FIELD));

    setJMSReplyTo(getDestName(message));
    readProperties(message);
}
 
Example #18
Source File: AbstractAdaptableMessageListener.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Destination getResponseDestination(Message request, Message response, Session session, Object result)
		throws JMSException {

	if (result instanceof JmsResponse) {
		JmsResponse<?> jmsResponse = (JmsResponse) result;
		Destination destination = jmsResponse.resolveDestination(getDestinationResolver(), session);
		if (destination != null) {
			return destination;
		}
	}
	return getResponseDestination(request, response, session);
}
 
Example #19
Source File: AdvancedNotifyMessageListener.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * MessageListener回调函数.
 */
@Override
public void onMessage(Message message) {
	try {
		MapMessage mapMessage = (MapMessage) message;

		System.out.println("消费消息");
		//打印消息详情
	/*	logger.info("UserName:" + mapMessage.getString("userName") + ", Email:" + mapMessage.getString("email")
				+ ", ObjectType:" + mapMessage.getStringProperty("objectType"));*/
	} catch (Exception e) {
		logger.error("处理消息时发生异常.", e);
	}
}
 
Example #20
Source File: ActiveMQClientHeader.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public final void setMessage(Message message, ActiveMQClientHeader key, T value) throws JMSException {
    String id = key.id;
    if (message instanceof ActiveMQMessage) {
        ActiveMQMessage activeMQMessage = (ActiveMQMessage) message;
        if (activeMQMessage.isReadOnlyProperties()) {
            activeMQMessage.setReadOnlyProperties(false);
            setMessage0(message, id, value);
            activeMQMessage.setReadOnlyProperties(true);
            return;
        }
    }
    setMessage0(message, id, value);
}
 
Example #21
Source File: JMSMessageTypesTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void testMessageSendReceive(Connection producerConnection, Connection consumerConnection) throws Throwable {
   long time = System.currentTimeMillis();

   Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(getQueueName());

   byte[] bytes = new byte[0xf + 1];
   for (int i = 0; i <= 0xf; i++) {
      bytes[i] = (byte) i;
   }

   MessageProducer producer = session.createProducer(queue);
   for (int i = 0; i < NUM_MESSAGES; i++) {
      instanceLog.debug("Sending " + i);
      Message message = session.createMessage();

      message.setIntProperty("count", i);
      producer.send(message);
   }

   Session sessionConsumer = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue consumerQueue = sessionConsumer.createQueue(getQueueName());
   final MessageConsumer consumer = sessionConsumer.createConsumer(consumerQueue);

   for (int i = 0; i < NUM_MESSAGES; i++) {
      Message m = consumer.receive(5000);
      Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m);
   }

   long taken = (System.currentTimeMillis() - time) / 1000;
   instanceLog.debug("taken = " + taken);
}
 
Example #22
Source File: QueueReceiver1.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message) {
	try {
		/*
		 * 实际项目中拿到String类型的message(通常是JSON字符串)之后,会进行反序列化成对象,做进一步的处理
		 */
		System.out.println("QueueReceiver1接收到消息:" + ((TextMessage) message).getText());
	} catch (JMSException e) {
		e.printStackTrace();
	}
}
 
Example #23
Source File: JMSCacheableMailQueue.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Mono<MailQueueItem> deQueueOneItem() {
    Session session = null;
    MessageConsumer consumer = null;
    try {
        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        Queue queue = session.createQueue(queueName.asString());
        consumer = session.createConsumer(queue, getMessageSelector());

        Message message = consumer.receive(10000);

        if (message != null) {
            dequeuedMailsMetric.increment();
            return Mono.just(createMailQueueItem(session, consumer, message));
        } else {
            session.commit();
            closeConsumer(consumer);
            closeSession(session);
        }

    } catch (Exception e) {
        rollback(session);
        closeConsumer(consumer);
        closeSession(session);
        return Mono.error(new MailQueueException("Unable to dequeue next message", e));
    }
    return Mono.empty();
}
 
Example #24
Source File: TopicPublisher.java    From chipster with MIT License 5 votes vote down vote up
public void onMessage(Message message) {
    synchronized (mutex) {
        System.out.println("Received report " + getReport(message) + " " + --remaining + " remaining");
        if (remaining == 0) {
            mutex.notify();
        }
    }
}
 
Example #25
Source File: AmqpAcknowledgementsIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testAcknowledgeFailsAfterSessionIsClosed() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType(null), 1);

        MessageConsumer messageConsumer = session.createConsumer(queue);

        Message receivedMessage = messageConsumer.receive(6000);
        assertNotNull("Message was not recieved", receivedMessage);

        testPeer.expectDisposition(true, new ModifiedMatcher().withDeliveryFailed(equalTo(true)), 1, 1);
        testPeer.expectEnd();

        session.close();

        try {
            receivedMessage.acknowledge();
            fail("Should not be able to acknowledge the message after session closed");
        } catch (JMSException jmsex) {}

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example #26
Source File: JmsTransactionTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a batch of messages and validates that the message sent before
 * session close is not consumed.
 *
 * This test only works with local transactions, not xa.
 *
 * @throws Exception
 */
@Test
public void testSendSessionClose() throws Exception {
   Message[] outbound = new Message[]{session.createTextMessage("First Message"), session.createTextMessage("Second Message")};

   // sends a message
   beginTx();
   producer.send(outbound[0]);
   commitTx();

   // sends a message that gets rollbacked
   beginTx();
   producer.send(session.createTextMessage("I'm going to get rolled back."));
   consumer.close();

   reconnectSession();

   // sends a message
   producer.send(outbound[1]);
   commitTx();

   // receives the first message
   ArrayList<Message> messages = new ArrayList<>();
   beginTx();
   Message message = consumer.receive(1000);
   messages.add(message);

   // receives the second message
   message = consumer.receive(4000);
   messages.add(message);

   // validates that the rollbacked was not consumed
   commitTx();
   Message[] inbound = new Message[messages.size()];
   messages.toArray(inbound);
   assertTextMessagesEqual("Rollback did not work.", outbound, inbound);
}
 
Example #27
Source File: JMSHeadersAndPropertiesTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void resentJMSMessageGetsReplacementJMSMessageID() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        MessageProducer producer = session.createProducer(queue);

        final Message sentMessage = session.createMessage();
        producer.send(sentMessage);

        final String originalId = sentMessage.getJMSMessageID();
        assertNotNull("JMSMessageID must be set after first publish", originalId);

        producer.send(sentMessage);
        final String firstResendID = sentMessage.getJMSMessageID();
        assertNotNull("JMSMessageID must be set after first resend", firstResendID);
        assertNotSame("JMSMessageID must be changed second publish", originalId, firstResendID);
    }
    finally
    {
        connection.close();
    }
}
 
Example #28
Source File: NoConsumerDeadLetterTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
protected void doTest() throws Exception {
   makeDlqConsumer();
   sendMessages();

   for (int i = 0; i < messageCount; i++) {
      Message msg = dlqConsumer.receive(1000);
      assertNotNull("Should be a message for loop: " + i, msg);
   }
}
 
Example #29
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testTempTopicDelete() throws Exception {
   connection.start();
   TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

   TemporaryTopic tempTopic = topicSession.createTemporaryTopic();

   ActiveMQConnection newConn = (ActiveMQConnection) factory.createConnection();

   try {
      TopicSession newTopicSession = newConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      TopicPublisher publisher = newTopicSession.createPublisher(tempTopic);

      // need to wait here because the ActiveMQ client's temp destination map is updated asynchronously, not waiting can introduce a race
      assertTrue(Wait.waitFor(() -> newConn.activeTempDestinations.size() == 1, 2000, 100));

      TextMessage msg = newTopicSession.createTextMessage("Test Message");

      publisher.publish(msg);

      try {
         TopicSubscriber consumer = newTopicSession.createSubscriber(tempTopic);
         fail("should have gotten exception but got consumer: " + consumer);
      } catch (JMSException ex) {
         //correct
      }

      connection.close();

      try {
         Message newMsg = newTopicSession.createMessage();
         publisher.publish(newMsg);
      } catch (JMSException e) {
         //ok
      }

   } finally {
      newConn.close();
   }
}
 
Example #30
Source File: SQSMessageConsumerPrefetchTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test ConvertToJMSMessage with text message with text type attribute
 */
@Test
public void testConvertToJMSMessageTextTypeAttribute() throws JMSException, IOException {

    /*
     * Set up consumer prefetch and mocks
     */

    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();
    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.TEXT_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");

    com.amazonaws.services.sqs.model.Message message = mock(com.amazonaws.services.sqs.model.Message.class);
    // Return message attributes with message type 'TEXT'
    when(message.getMessageAttributes()).thenReturn(mapMessageAttributes);
    when(message.getAttributes()).thenReturn(mapAttributes);
    when(message.getBody()).thenReturn("MessageBody");

    /*
     * Convert the SQS message to JMS Message
     */
    javax.jms.Message jsmMessage = consumerPrefetch.convertToJMSMessage(message);

    /*
     * Verify results
     */
    assertTrue(jsmMessage instanceof SQSTextMessage);
    assertEquals(message.getBody(), "MessageBody");
}