javax.jms.TextMessage Java Examples

The following examples show how to use javax.jms.TextMessage. 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: MessagingMessageListenerAdapterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void replyPayloadNoDestination() throws JMSException {
	Queue replyDestination = mock(Queue.class);

	Session session = mock(Session.class);
	MessageProducer messageProducer = mock(MessageProducer.class);
	TextMessage responseMessage = mock(TextMessage.class);
	given(session.createTextMessage("Response")).willReturn(responseMessage);
	given(session.createProducer(replyDestination)).willReturn(messageProducer);

	MessagingMessageListenerAdapter listener =
			getPayloadInstance("Response", "replyPayloadNoDestination", Message.class);
	listener.setDefaultResponseDestination(replyDestination);
	listener.onMessage(mock(javax.jms.Message.class), session);

	verify(session, times(0)).createQueue(anyString());
	verify(session).createTextMessage("Response");
	verify(messageProducer).send(responseMessage);
	verify(messageProducer).close();
}
 
Example #2
Source File: OpsEventPublisher.java    From oneops with Apache License 2.0 6 votes vote down vote up
/**
   * Publish ci state message.
   *
   * @param event the event
   */
  public void publishCiStateMessage(CiChangeStateEvent event) {
  	
try {
	TextMessage message = session.createTextMessage(gson.toJson(event));
   	message.setLongProperty("ciId", event.getCiId());
   	message.setStringProperty("type", "ci-change-state");
   	message.setStringProperty("ciState", event.getNewState());
   	producer.send(message);
   	logger.info("Published: ciId:" + event.getCiId());
   	logger.info(message.getText());
} catch (JMSException e) {
	// TODO see if we can put some durability here
	logger.error("caught Exception publishing",e);
}
  	
  }
 
Example #3
Source File: PooledSessionExhaustionTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
public void sendMessages(ConnectionFactory connectionFactory) throws Exception {
    for (int i = 0; i < NUM_MESSAGES; i++) {
        Connection connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(QUEUE);
        MessageProducer producer = session.createProducer(destination);

        String msgTo = "hello";
        TextMessage message = session.createTextMessage(msgTo);
        producer.send(message);
        connection.close();
        LOG.debug("sent " + i + " messages using " + connectionFactory.getClass());
    }
}
 
Example #4
Source File: QueueBridgeStandaloneReconnectTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void sendMessageToForeignBroker(String text) throws JMSException {
   Connection connection = null;
   try {
      connection = localConnectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(outbound);
      TextMessage message = session.createTextMessage();
      message.setText(text);
      producer.send(message);
   } finally {
      try {
         connection.close();
      } catch (Throwable ignore) {
      }
   }
}
 
Example #5
Source File: JMSBrokerController.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public TextMessage pushMessage(String messageContent) {
    if (this.producer == null) {
        log.error("The producer is null");
        Assert.fail();
        return null;
    } else {
        TextMessage message = null;
        try {
            message = this.session.createTextMessage(messageContent);
            this.producer.send(message);
        } catch (JMSException e) {
            log.error("Error while sending message", e);
            Assert.fail();
        }
        return message;
    }
}
 
Example #6
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 #7
Source File: OutgoingConnectionNoJTATest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleSendNoXAJMSContext() throws Exception {
   Queue q = ActiveMQJMSClient.createQueue(MDBQUEUE);

   try (ClientSessionFactory sf = locator.createSessionFactory();
        ClientSession session = sf.createSession();
        ClientConsumer consVerify = session.createConsumer(MDBQUEUE);
        JMSContext jmsctx = qraConnectionFactory.createContext();
   ) {
      session.start();
      // These next 4 lines could be written in a single line however it makes difficult for debugging
      JMSProducer producer = jmsctx.createProducer();
      producer.setProperty("strvalue", "hello");
      TextMessage msgsend = jmsctx.createTextMessage("hello");
      producer.send(q, msgsend);

      ClientMessage msg = consVerify.receive(1000);
      assertNotNull(msg);
      assertEquals("hello", msg.getStringProperty("strvalue"));
   }
}
 
Example #8
Source File: SelectorTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Test the BETWEEN condition in message selector.
 * <br />
 * <ul>
 * <li>"age BETWEEN 15 and 19" is <code>true</code> for 17 and <code>false</code> for 20</li>
 * </ul>
 */
@Test
public void testBetween() throws Exception {
   if (receiver != null) {
      receiver.close();
   }
   receiver = receiverSession.createReceiver(receiverQueue, "age BETWEEN 15 and 19");

   TextMessage dummyMessage = senderSession.createTextMessage();
   dummyMessage.setIntProperty("age", 20);
   dummyMessage.setText("testBetween:1");
   sender.send(dummyMessage);

   TextMessage message = senderSession.createTextMessage();
   message.setIntProperty("age", 17);
   message.setText("testBetween:2");
   sender.send(message);

   TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT);
   Assert.assertTrue("Message not received", msg != null);
   Assert.assertTrue("Message of another test: " + msg.getText(), msg.getText().startsWith("testBetween"));
   Assert.assertEquals("testBetween:2", msg.getText());
}
 
Example #9
Source File: TestIntegrationActiveMQ.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
private void putQueue(List<String> events) throws Exception {
  ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
      PASSWORD, BROKER_BIND_URL);
  Connection connection = factory.createConnection();
  connection.start();

  Session session = connection.createSession(true,
      Session.AUTO_ACKNOWLEDGE);
  Destination destination = session.createQueue(DESTINATION_NAME);
  MessageProducer producer = session.createProducer(destination);


  for(String event : events) {
    TextMessage message = session.createTextMessage();
    message.setText(event);
    producer.send(message);
  }
  session.commit();
  session.close();
  connection.close();
}
 
Example #10
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testRollback() throws Exception {
   try (Connection connection = factory.createConnection()) {
      Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
      Queue queue = session.createQueue(queueName);
      MessageProducer producer = session.createProducer(queue);
      MessageConsumer consumer = session.createConsumer(queue);
      producer.send(session.createTextMessage("test"));
      producer.send(session.createTextMessage("test2"));
      connection.start();
      Assert.assertNull(consumer.receiveNoWait());
      session.rollback();
      producer.send(session.createTextMessage("test2"));
      Assert.assertNull(consumer.receiveNoWait());
      session.commit();
      TextMessage msg = (TextMessage) consumer.receive(1000);

      Assert.assertNotNull(msg);
      Assert.assertEquals("test2", msg.getText());
   }
}
 
Example #11
Source File: AmqpLargeMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendTextMessages(int nMsgs, ConnectionFactory factory) throws Exception {
   try (Connection connection = factory.createConnection()) {
      Session session = connection.createSession();
      Queue queue = session.createQueue(testQueueName);
      MessageProducer producer = session.createProducer(queue);
      TextMessage msg = session.createTextMessage();

      StringBuilder builder = new StringBuilder();
      for (int i = 0; i < PAYLOAD; ++i) {
         builder.append("A");
      }

      msg.setText(builder.toString());

      for (int i = 0; i < nMsgs; ++i) {
         msg.setIntProperty("i", (Integer) i);
         producer.send(msg);
      }
   }
}
 
Example #12
Source File: JmsTopicSelectorTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertySelector() throws Exception {
   int remaining = 5;
   Message message = null;
   consumer = createConsumer("stringProperty = 'a' and longProperty = 1 and booleanProperty = true");
   sendMessages();
   while (true) {
      message = consumer.receive(1000);
      if (message == null) {
         break;
      }
      String text = ((TextMessage) message).getText();
      if (!text.equals("1") && !text.equals("3")) {
         fail("unexpected message: " + text);
      }
      remaining--;
   }
   assertEquals(remaining, 3);
   consumer.close();
   consumeMessages(remaining);

}
 
Example #13
Source File: ActiveMQRAMessageConsumer.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Wrap message
 *
 * @param message The message to be wrapped
 * @return The wrapped message
 */
Message wrapMessage(final Message message) {
   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("wrapMessage(" + message + ")");
   }

   if (message instanceof BytesMessage) {
      return new ActiveMQRABytesMessage((BytesMessage) message, session);
   } else if (message instanceof MapMessage) {
      return new ActiveMQRAMapMessage((MapMessage) message, session);
   } else if (message instanceof ObjectMessage) {
      return new ActiveMQRAObjectMessage((ObjectMessage) message, session);
   } else if (message instanceof StreamMessage) {
      return new ActiveMQRAStreamMessage((StreamMessage) message, session);
   } else if (message instanceof TextMessage) {
      return new ActiveMQRATextMessage((TextMessage) message, session);
   }
   return new ActiveMQRAMessage(message, session);
}
 
Example #14
Source File: StompV11Test.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMessageWithReceipt() throws Exception {
   MessageConsumer consumer = session.createConsumer(queue);

   conn.connect(defUser, defPass);


   send(conn, getQueuePrefix() + getQueueName(), null, "Hello World", true);

   TextMessage message = (TextMessage) consumer.receive(1000);
   Assert.assertNotNull(message);
   Assert.assertEquals("Hello World", message.getText());

   // Make sure that the timestamp is valid - should
   // be very close to the current time.
   long tnow = System.currentTimeMillis();
   long tmsg = message.getJMSTimestamp();
   Assert.assertTrue(Math.abs(tnow - tmsg) < 1000);

   conn.disconnect();
}
 
Example #15
Source File: MessagingMessageListenerAdapterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void replyPayloadToQueue() throws JMSException {
	Session session = mock(Session.class);
	Queue replyDestination = mock(Queue.class);
	given(session.createQueue("queueOut")).willReturn(replyDestination);

	MessageProducer messageProducer = mock(MessageProducer.class);
	TextMessage responseMessage = mock(TextMessage.class);
	given(session.createTextMessage("Response")).willReturn(responseMessage);
	given(session.createProducer(replyDestination)).willReturn(messageProducer);

	MessagingMessageListenerAdapter listener = getPayloadInstance("Response", "replyPayloadToQueue", Message.class);
	listener.onMessage(mock(javax.jms.Message.class), session);

	verify(session).createQueue("queueOut");
	verify(session).createTextMessage("Response");
	verify(messageProducer).send(responseMessage);
	verify(messageProducer).close();
}
 
Example #16
Source File: TopicBridgeStandaloneReconnectTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void sendMessageToLocalBroker(String text) throws JMSException {
   Connection connection = null;
   try {
      connection = foreignConnectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(inbound);
      TextMessage message = session.createTextMessage();
      message.setText(text);
      producer.send(message);
   } finally {
      try {
         connection.close();
      } catch (Throwable ignore) {
      }
   }
}
 
Example #17
Source File: MessageSerializerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnycastQueueToMulticastTopicBothAddress() throws Exception {
   String address = "testBoth";
   String clientId = "test-client-id";

   File file = createMessageFile();

   connection.setClientID(clientId);
   createBothTypeAddress(address);
   createQueue(RoutingType.ANYCAST, address, address);
   Session session = createSession(connection);

   TopicSubscriber subscriber = session.createDurableSubscriber(session.createTopic(address), "test-subscriber");

   List<Message> messages = generateTextMessages(session, getDestination(address));

   exportMessages(address, file);

   importMessages(ActiveMQDestination.TOPIC_QUALIFIED_PREFIX + address, file);
   for (int i = 0; i < TEST_MESSAGE_COUNT; i++) {
      TextMessage messageReceived = (TextMessage) subscriber.receive(1000);
      assertNotNull(messageReceived);
      assertEquals(((TextMessage) messages.get(i)).getText(), messageReceived.getText());
   }
}
 
Example #18
Source File: InductorListenerTest.java    From oneops with Apache License 2.0 6 votes vote down vote up
@Test
/** test the message impl */
public void testListening() throws JMSException {
	try {
		listener.init();

		TextMessage message = mock(TextMessage.class);
		when(message.getText()).thenReturn("{messgetext:true}");
		when(message.getStringProperty("task_id")).thenReturn("corel-id");
		when(message.getStringProperty("task_result_code")).thenReturn(
				"200");
		when(message.getStringProperty("type")).thenReturn("deploybom");
		when(message.getJMSCorrelationID()).thenReturn("jms|cor!rel!ation!id");

		listener.onMessage(message);
		listener.cleanup();
		listener.getConnectionStats();
	} catch (JMSException e) {
		System.out.println("CAUTH EXCEPTION " + e.getMessage());
		e.printStackTrace();
		throw e;
	}

}
 
Example #19
Source File: DefaultMessageQueueListener.java    From zheng with MIT License 6 votes vote down vote up
@Override
public void onMessage(final Message message) {
    // 使用线程池多线程处理
    threadPoolTaskExecutor.execute(new Runnable() {
        @Override
        public void run() {
            TextMessage textMessage = (TextMessage) message;
            try {
                String text = textMessage.getText();
                LOGGER.info("消费:{}", text);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
 
Example #20
Source File: JmsInstrumentationHelperImpl.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public void addMessageDetails(@Nullable Message message, AbstractSpan span) {
    if (message == null) {
        return;
    }
    try {
        co.elastic.apm.agent.impl.context.Message messageContext = span.getContext().getMessage();

        // Currently only capturing body of TextMessages. The javax.jms.Message#getBody() API is since 2.0, so,
        // if we are supporting JMS 1.1, it makes no sense to rely on isAssignableFrom.
        if (coreConfiguration.getCaptureBody() != CoreConfiguration.EventType.OFF && message instanceof TextMessage) {
            messageContext.withBody(((TextMessage) message).getText());
        }

        // Addition of non-String headers/properties will cause String instance allocations
        if (coreConfiguration.isCaptureHeaders()) {
            messageContext.addHeader(JMS_MESSAGE_ID_HEADER, message.getJMSMessageID());
            messageContext.addHeader(JMS_EXPIRATION_HEADER, String.valueOf(message.getJMSExpiration()));
            messageContext.addHeader(JMS_TIMESTAMP_HEADER, String.valueOf(message.getJMSTimestamp()));

            Enumeration properties = message.getPropertyNames();
            while (properties.hasMoreElements()) {
                String propertyName = String.valueOf(properties.nextElement());
                if (!propertyName.equals(JMS_DESTINATION_NAME_PROPERTY) && !propertyName.equals(JMS_TRACE_PARENT_PROPERTY)
                    && WildcardMatcher.anyMatch(coreConfiguration.getSanitizeFieldNames(), propertyName) == null) {
                    messageContext.addHeader(propertyName, String.valueOf(message.getObjectProperty(propertyName)));
                }
            }
        }
    } catch (JMSException e) {
        logger.warn("Failed to retrieve message details", e);
    }
}
 
Example #21
Source File: JmsRollbackRedeliveryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void doTestRedelivery(String brokerUrl, boolean interleaveProducer) throws Exception {
   LOG.debug("entering doTestRedelivery interleaveProducer is " + interleaveProducer);
   ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

   Connection connection = connectionFactory.createConnection();
   connection.start();

   if (interleaveProducer) {
      populateDestinationWithInterleavedProducer(nbMessages, destinationName, connection);
   } else {
      populateDestination(nbMessages, destinationName, connection);
   }

   // Consume messages and rollback transactions
   {
      AtomicInteger received = new AtomicInteger();
      Map<String, Boolean> rolledback = new ConcurrentHashMap<>();
      while (received.get() < nbMessages) {
         Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
         Destination destination = session.createQueue(destinationName);
         MessageConsumer consumer = session.createConsumer(destination);
         TextMessage msg = (TextMessage) consumer.receive(5000);
         if (msg != null) {
            if (rolledback.put(msg.getText(), Boolean.TRUE) != null) {
               LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID());
               assertTrue(msg.getJMSRedelivered());
               assertEquals(2, msg.getLongProperty("JMSXDeliveryCount"));
               session.commit();
            } else {
               LOG.info("Rollback message " + msg.getText() + " id: " + msg.getJMSMessageID());
               assertFalse("should not have redelivery flag set, id: " + msg.getJMSMessageID(), msg.getJMSRedelivered());
               session.rollback();
            }
         }
         consumer.close();
         session.close();
      }
   }
}
 
Example #22
Source File: ZeroPrefetchConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testBrokerZeroPrefetchConfig() throws Exception {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

   MessageProducer producer = session.createProducer(brokerZeroQueue);
   producer.send(session.createTextMessage("Msg1"));
   // now lets receive it
   MessageConsumer consumer = session.createConsumer(brokerZeroQueue);

   TextMessage answer = (TextMessage) consumer.receive(5000);
   assertEquals("Should have received a message!", answer.getText(), "Msg1");
}
 
Example #23
Source File: MessageRoutingTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousRelayRoutingToQueue() throws Exception
{
    assumeThat("AMQP 1.0 test", getProtocol(), is(equalTo(Protocol.AMQP_1_0)));

    prepare();

    Connection connection = getConnection();
    try
    {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Destination sendingDestination = session.createQueue(QUEUE_NAME);
        Destination receivingDestination = session.createQueue(QUEUE_NAME);

        Message message = session.createTextMessage("test");

        MessageProducer messageProducer = session.createProducer(null);
        messageProducer.send(sendingDestination, message);

        MessageConsumer messageConsumer = session.createConsumer(receivingDestination);
        Message receivedMessage = messageConsumer.receive(getReceiveTimeout());

        assertNotNull("Message not received", receivedMessage);
        assertEquals("test", ((TextMessage) message).getText());
    }
    finally
    {
        connection.close();
    }
}
 
Example #24
Source File: SecurityExample.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static void checkUserReceiveNoSend(final Topic topic,
                                           final Connection connection,
                                           final String user,
                                           final Connection sendingConn) throws JMSException {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(topic);
   MessageConsumer consumer = session.createConsumer(topic);
   TextMessage msg = session.createTextMessage("hello-world-1");

   try {
      producer.send(msg);
      throw new IllegalStateException("Security setting is broken! User " + user +
                                         " can send message [" +
                                         msg.getText() +
                                         "] to topic " +
                                         topic);
   } catch (JMSException e) {
      System.out.println("User " + user + " cannot send message [" + msg.getText() + "] to topic: " + topic);
   }

   // Now send a good message
   Session session1 = sendingConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   producer = session1.createProducer(topic);
   producer.send(msg);

   TextMessage receivedMsg = (TextMessage) consumer.receive(2000);

   if (receivedMsg != null) {
      System.out.println("User " + user + " can receive message [" + receivedMsg.getText() + "] from topic " + topic);
   } else {
      throw new IllegalStateException("Security setting is broken! User " + user + " cannot receive message from topic " + topic);
   }

   session1.close();
   session.close();
}
 
Example #25
Source File: JmsSchedulerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testScheduleRestart() throws Exception {
   // send a message
   Connection connection = createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   connection.start();
   MessageProducer producer = session.createProducer(destination);
   TextMessage message = session.createTextMessage("test msg");
   long time = 5000;
   message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
   producer.send(message);
   producer.close();

   //restart broker
   broker.stop();
   broker.waitUntilStopped();

   broker = createBroker(false);
   broker.start();
   broker.waitUntilStarted();

   // consume the message
   connection = createConnection();
   connection.start();
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createConsumer(destination);
   Message msg = consumer.receive(5000);
   assertNotNull("Didn't receive the message", msg);

   //send another message
   producer = session.createProducer(destination);
   message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
   producer.send(message);
   producer.close();
}
 
Example #26
Source File: JmsZeroPrefetchTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=60000)
public void testConsumerReceivePrefetchZeroRedeliveryZero() throws Exception {
    connection = createAmqpConnection();
    connection.start();

    // push message to queue
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("test.prefetch.zero");
    MessageProducer producer = session.createProducer(queue);
    TextMessage textMessage = session.createTextMessage("test Message");
    producer.send(textMessage);
    session.close();

    // consume and rollback - increase redelivery counter on message
    session = connection.createSession(true, Session.SESSION_TRANSACTED);
    MessageConsumer consumer = session.createConsumer(queue);
    Message message = consumer.receive(3000);
    assertNotNull(message);
    session.rollback();
    session.close();

    JmsDefaultRedeliveryPolicy redeliveryPolicy = new JmsDefaultRedeliveryPolicy();
    redeliveryPolicy.setMaxRedeliveries(0);

    // Reconnect with zero prefetch and zero redeliveries allowed.
    connection.close();
    connection = createAmqpConnection();
    ((JmsConnection)connection).setRedeliveryPolicy(redeliveryPolicy);
    connection.start();

    // try consume with timeout - expect it to timeout and return NULL message
    session = connection.createSession(true, Session.SESSION_TRANSACTED);
    consumer = session.createConsumer(queue);
    message = consumer.receive(1000);

    assertNull(message);
}
 
Example #27
Source File: JmsTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected void doTestJmsException(JMSException original, Class<? extends JmsException> thrownExceptionClass) throws Exception {
	JmsTemplate template = createTemplate();
	template.setConnectionFactory(connectionFactory);
	template.setMessageConverter(new SimpleMessageConverter());
	String s = "Hello world";

	MessageProducer messageProducer = mock(MessageProducer.class);
	TextMessage textMessage = mock(TextMessage.class);

	reset(session);
	given(session.createProducer(queue)).willReturn(messageProducer);
	given(session.createTextMessage("Hello world")).willReturn(textMessage);

	willThrow(original).given(messageProducer).send(textMessage);

	try {
		template.convertAndSend(queue, s);
		fail("Should have thrown JmsException");
	}
	catch (JmsException wrappedEx) {
		// expected
		assertEquals(thrownExceptionClass, wrappedEx.getClass());
		assertEquals(original, wrappedEx.getCause());
	}

	verify(messageProducer).close();
	verify(session).close();
	verify(connection).close();
}
 
Example #28
Source File: QReceiverListenerClient.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onMessage(Message message) {
	try {
		TextMessage textMessage = (TextMessage) message;
		System.out.println("消息内容:" + textMessage.getText() + ",是否重发:" + textMessage.getJMSRedelivered());
		textMessage.acknowledge();
		throw new RuntimeException("test");
	} catch (JMSException e) {
		e.printStackTrace();
	}
}
 
Example #29
Source File: SessionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Test that it is valid to use message objects created or received via the [closed] session with the
 * exception of a received message <code>acknowledge()</code> method.
 */
@Test
public void testUseMessage() {
   try {
      TextMessage message = senderSession.createTextMessage();
      message.setText("testUseMessage");
      sender.send(message);

      TextMessage m = (TextMessage) receiver.receive(TestConfig.TIMEOUT);
      receiverSession.close();
      Assert.assertEquals("testUseMessage", m.getText());
   } catch (Exception e) {
      Assert.fail("sec. 4.4.1 It is valid to continue to use message objects created or received via " + "the [closed] session.\n");
   }
}
 
Example #30
Source File: JMS2AMQTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(final Message message) {
    try {
        try {
            ok = (TextMessage.class.isInstance(message)
                    && TEXT.equals(TextMessage.class.cast(message).getText())
                    && TEXT.equals(message.getBody(String.class)))
                    || message.getStringProperty("text").equals(TEXT);
        } catch (final JMSException e) {
            // no-op
        }
    } finally {
        latch.countDown();
    }
}