javax.jms.DeliveryMode Java Examples

The following examples show how to use javax.jms.DeliveryMode. 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: SimpleJmsHeaderMapperTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jmsReadOnlyPropertiesNotMapped() throws JMSException {
	Message<String> message = initBuilder()
			.setHeader(JmsHeaders.DESTINATION, new Destination() {})
			.setHeader(JmsHeaders.DELIVERY_MODE, DeliveryMode.NON_PERSISTENT)
			.setHeader(JmsHeaders.EXPIRATION, 1000L)
			.setHeader(JmsHeaders.MESSAGE_ID, "abc-123")
			.setHeader(JmsHeaders.PRIORITY, 9)
			.setHeader(JmsHeaders.REDELIVERED, true)
			.setHeader(JmsHeaders.TIMESTAMP, System.currentTimeMillis())
			.build();
	javax.jms.Message jmsMessage = new StubTextMessage();
	mapper.fromHeaders(message.getHeaders(), jmsMessage);
	assertNull(jmsMessage.getJMSDestination());
	assertEquals(DeliveryMode.PERSISTENT, jmsMessage.getJMSDeliveryMode());
	assertEquals(0, jmsMessage.getJMSExpiration());
	assertNull(jmsMessage.getJMSMessageID());
	assertEquals(javax.jms.Message.DEFAULT_PRIORITY, jmsMessage.getJMSPriority());
	assertFalse(jmsMessage.getJMSRedelivered());
	assertEquals(0, jmsMessage.getJMSTimestamp());
}
 
Example #2
Source File: ApplicationTest.java    From examples with Apache License 2.0 6 votes vote down vote up
/**
 * Create an embedded AMQ broker and a client as the producer for our test.
 * Create a queue with the supplied queue name.
 * 
 * @throws Exception
 */
private void createAMQClient(String brokerURL) throws Exception 
{
  startEmbeddedActiveMQBroker();
  
  // Create a ConnectionFactory
  ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerURL);

  // Create a Connection
  connection = connectionFactory.createConnection();
  connection.start();

  // Create a Session
  session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

  // Create the destination queue
  Destination destination = session.createQueue(qNameToUse);

  // Create a MessageProducer from the Session to the Topic or Queue
  producer = session.createProducer(destination);
  producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
 
Example #3
Source File: ActivemqLocalBroker.java    From hadoop-mini-clusters with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    String uri = uriPrefix + hostName + ":" + port;
    LOG.info("ACTIVEMQ: Starting ActiveMQ on {}", uri);
    configure();

    broker = new BrokerService();
    broker.addConnector(uri);
    broker.start();

    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri + uriPostfix);
    Connection conn = factory.createConnection();
    conn.start();

    session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    dest = session.createQueue(queueName);
    consumer = session.createConsumer(dest);
    producer = session.createProducer(dest);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
 
Example #4
Source File: MessagingMessageListenerAdapterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void replyWithFullQoS() 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);
	QosSettings settings = new QosSettings(DeliveryMode.NON_PERSISTENT, 6, 6000);
	listener.setResponseQosSettings(settings);
	listener.onMessage(mock(javax.jms.Message.class), session);
	verify(session).createQueue("queueOut");
	verify(session).createTextMessage("Response");
	verify(messageProducer).send(responseMessage, DeliveryMode.NON_PERSISTENT, 6, 6000);
	verify(messageProducer).close();
}
 
Example #5
Source File: SimpleJmsHeaderMapperTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jmsReadOnlyPropertiesNotMapped() throws JMSException {
	Message<String> message = initBuilder()
			.setHeader(JmsHeaders.DESTINATION, new Destination() {})
			.setHeader(JmsHeaders.DELIVERY_MODE, DeliveryMode.NON_PERSISTENT)
			.setHeader(JmsHeaders.EXPIRATION, 1000L)
			.setHeader(JmsHeaders.MESSAGE_ID, "abc-123")
			.setHeader(JmsHeaders.PRIORITY, 9)
			.setHeader(JmsHeaders.REDELIVERED, true)
			.setHeader(JmsHeaders.TIMESTAMP, System.currentTimeMillis())
			.build();
	javax.jms.Message jmsMessage = new StubTextMessage();
	mapper.fromHeaders(message.getHeaders(), jmsMessage);
	assertNull(jmsMessage.getJMSDestination());
	assertEquals(DeliveryMode.PERSISTENT, jmsMessage.getJMSDeliveryMode());
	assertEquals(0, jmsMessage.getJMSExpiration());
	assertNull(jmsMessage.getJMSMessageID());
	assertEquals(javax.jms.Message.DEFAULT_PRIORITY, jmsMessage.getJMSPriority());
	assertFalse(jmsMessage.getJMSRedelivered());
	assertEquals(0, jmsMessage.getJMSTimestamp());
}
 
Example #6
Source File: SelectorTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the JMS property <code>JMSDeliveryMode</code> is treated as having the values <code>'PERSISTENT'</code>
 * or <code>'NON_PERSISTENT'</code> when used in a message selector (chapter 3.8.1.3).
 */
@Test
public void testJMSDeliveryModeInSelector() throws Exception {
   if (receiver != null) {
      receiver.close();
   }
   receiver = receiverSession.createReceiver(receiverQueue, "JMSDeliveryMode = 'PERSISTENT'");

   TextMessage dummyMessage = senderSession.createTextMessage();
   dummyMessage.setText("testJMSDeliveryModeInSelector:1");
   // send a dummy message in *non persistent* mode
   sender.send(dummyMessage, DeliveryMode.NON_PERSISTENT, sender.getPriority(), sender.getTimeToLive());

   TextMessage message = senderSession.createTextMessage();
   message.setText("testJMSDeliveryModeInSelector:2");
   // send a message in *persistent*
   sender.send(message, DeliveryMode.PERSISTENT, sender.getPriority(), sender.getTimeToLive());

   TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT);
   Assert.assertTrue("No message was received", msg != null);
   // only the message sent in persistent mode should be received.
   Assert.assertEquals(DeliveryMode.PERSISTENT, msg.getJMSDeliveryMode());
   Assert.assertEquals("testJMSDeliveryModeInSelector:2", msg.getText());
}
 
Example #7
Source File: ProducerSB.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED)
   @Override
   public void sendMessage() throws JMSException {

System.out.println("Sending reply message");
Connection conn = null;
Session session = null;
MessageProducer prod = null;

try {
    conn = myCF.createConnection();
    session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    prod = session.createProducer(myReplyQueue);

    ObjectMessage msg = session.createObjectMessage();
    msg.setObject("Hello world!");
    prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
} finally {
    if (prod != null)
	prod.close();
    if (session != null)
	session.close();
    if (conn != null)
	conn.close();
}
   }
 
Example #8
Source File: DurableSubscriptionTestSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testMessageExpire() throws Exception {
   session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
   Topic topic = session.createTopic("TestTopic");
   consumer = session.createDurableSubscriber(topic, "sub1");
   producer = session.createProducer(topic);
   producer.setDeliveryMode(DeliveryMode.PERSISTENT);
   producer.setTimeToLive(1000);
   connection.start();

   // Make sure it works when the durable sub is active.
   producer.send(session.createTextMessage("Msg:1"));
   assertTextMessageEquals("Msg:1", consumer.receive(1000));

   consumer.close();

   producer.send(session.createTextMessage("Msg:2"));
   producer.send(session.createTextMessage("Msg:3"));

   consumer = session.createDurableSubscriber(topic, "sub1");

   // Try to get the message.
   assertTextMessageEquals("Msg:2", consumer.receive(1000));
   Thread.sleep(1000);
   assertNull(consumer.receive(1000));
}
 
Example #9
Source File: ProducerSB.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@Override
public void sendMessage() throws JMSException {

    Connection conn = null;
    Session session = null;
    MessageProducer prod = null;

    try {
        conn = myCF.createConnection();
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        prod = session.createProducer(myReplyQueue);

        ObjectMessage msg = session.createObjectMessage();
        msg.setObject("Hello world!");
        prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
    } finally {
        if (prod != null)
            prod.close();
        if (session != null)
            session.close();
        if (conn != null)
            conn.close();
    }
}
 
Example #10
Source File: XAProducerSB.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@TransactionAttribute(value = TransactionAttributeType.REQUIRED)
@Override
public void sendMessage() throws JMSException {

    Connection conn = null;
    Session session = null;
    MessageProducer prod = null;

    try {
        conn = myCF.createConnection();
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        prod = session.createProducer(myReplyQueue);

        ObjectMessage msg = session.createObjectMessage();
        msg.setObject("Hello world!");
        prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
    } finally {
        if (prod != null)
            prod.close();
        if (session != null)
            session.close();
        if (conn != null)
            conn.close();
    }
}
 
Example #11
Source File: JmsTempDestinationTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that a temp queue does not drop message if there are no active
 * consumers.
 *
 * @throws JMSException
 */
@Test
public void testTempQueueHoldsMessagesWithoutConsumers() throws JMSException {

   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createTemporaryQueue();
   MessageProducer producer = session.createProducer(queue);
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
   TextMessage message = session.createTextMessage("Hello");
   producer.send(message);

   connection.start();
   MessageConsumer consumer = session.createConsumer(queue);
   Message message2 = consumer.receive(3000);
   Assert.assertNotNull(message2);
   Assert.assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage);
   Assert.assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage) message2).getText().equals(message.getText()));

}
 
Example #12
Source File: CompressionOverNetworkTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testTextMessageCompression() throws Exception {

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

   waitForConsumerRegistration(localBroker, 1, included);

   StringBuilder payload = new StringBuilder("test-");
   for (int i = 0; i < 100; ++i) {
      payload.append(UUID.randomUUID().toString());
   }

   Message test = localSession.createTextMessage(payload.toString());
   producer.send(test);
   Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
   assertNotNull(msg);
   ActiveMQTextMessage message = (ActiveMQTextMessage) msg;
   assertTrue(message.isCompressed());
   assertEquals(payload.toString(), message.getText());
}
 
Example #13
Source File: ParticipantResultTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testProducerParticipantResultAttributes() throws Exception
{
    ProducerParticipantResult result = new ProducerParticipantResult();

    int priority = 2;
    long timeToLive = 30;
    long producerInterval = 50;
    int messageSize = 60;
    int deliveryMode = DeliveryMode.PERSISTENT;

    result.setPriority(priority);
    result.setTimeToLive(timeToLive);
    result.setInterval(producerInterval);
    result.setPayloadSize(messageSize);
    result.setDeliveryMode(deliveryMode);

    assertEquals(priority, result.getAttributes().get(PRIORITY));
    assertEquals(timeToLive, result.getAttributes().get(TIME_TO_LIVE));
    assertEquals(producerInterval, result.getAttributes().get(PRODUCER_INTERVAL));
    assertEquals(messageSize, result.getAttributes().get(PAYLOAD_SIZE));
    assertEquals(deliveryMode, result.getAttributes().get(DELIVERY_MODE));
}
 
Example #14
Source File: MultipleProducersTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendMessage(Queue queue, Session session) throws Exception {

      MessageProducer mp = session.createProducer(queue);

      try {
         mp.setDisableMessageID(true);
         mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
         mp.setPriority(Message.DEFAULT_PRIORITY);
         mp.setTimeToLive(Message.DEFAULT_TIME_TO_LIVE);

         mp.send(session.createTextMessage("This is message for " + queue.getQueueName()));
      } finally {

         mp.close();
      }
   }
 
Example #15
Source File: QosSettingsFactory.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * We Take the first {@link SourceDataTagValue} object from collection to determine
 * the Quality-of-Service settings for the message sending
 * @param sourceDataTagValue the first tag extracted from {@link DataTagValueUpdate}
 * @return the Quality-of-Service settings for determine the {@link JmsTemplate}
 */
static QosSettings extractQosSettings(SourceDataTagValue sourceDataTagValue) {
  QosSettings settings = new QosSettings();
  
  settings.setPriority(sourceDataTagValue.getPriority());
  settings.setTimeToLive(sourceDataTagValue.getTimeToLive());

  if (sourceDataTagValue.isGuaranteedDelivery()) {
    log.debug("\t sending PERSISTENT message");
    settings.setDeliveryMode(DeliveryMode.PERSISTENT);
  } else {
    log.debug("\t sending NON-PERSISTENT message");
    settings.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
  }
  
  return settings;
}
 
Example #16
Source File: CompressionOverNetworkTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectMessageCompression() throws Exception {

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

   waitForConsumerRegistration(localBroker, 1, included);

   StringBuilder payload = new StringBuilder("test-");
   for (int i = 0; i < 100; ++i) {
      payload.append(UUID.randomUUID().toString());
   }

   Message test = localSession.createObjectMessage(payload.toString());
   producer.send(test);
   Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
   assertNotNull(msg);
   ActiveMQObjectMessage message = (ActiveMQObjectMessage) msg;
   assertTrue(message.isCompressed());
   assertEquals(payload.toString(), message.getObject());
}
 
Example #17
Source File: JournalPendingMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testTopicNonPersistentMessageSize() throws Exception {
   AtomicLong publishedMessageSize = new AtomicLong();

   Connection connection = cf.createConnection();
   connection.setClientID("clientId");
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

   publishTestTopicMessages(200, DeliveryMode.NON_PERSISTENT, publishedMessageSize);

   verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());

   // consume all messages
   consumeTestMessages(consumer, 200);

   // All messages should now be gone
   verifyPendingStats(defaultTopicName, 0, 0);

   connection.close();
}
 
Example #18
Source File: QueueUtils.java    From karate with MIT License 6 votes vote down vote up
public static void send(String queueName, String text, int delayMillis) {
    new Thread(() -> {
        try {
            logger.info("*** artificial delay {}: {}", queueName, delayMillis);
            Thread.sleep(delayMillis);
            Connection connection = getConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            TextMessage message = session.createTextMessage(text);
            producer.send(message);
            logger.info("*** sent message {}: {}", queueName, text); 
            session.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }).start();
}
 
Example #19
Source File: DurableConsumerCloseAndReconnectTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void publish(int numMessages) throws Exception {
   connection = createConnection();
   connection.start();

   session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   destination = createDestination();

   producer = session.createProducer(destination);
   producer.setDeliveryMode(DeliveryMode.PERSISTENT);
   for (int i = 0; i < numMessages; i++) {
      TextMessage msg = session.createTextMessage("This is a test: " + messageCount++);
      producer.send(msg);
   }

   producer.close();
   producer = null;
   closeSession();
}
 
Example #20
Source File: JmsTempDestinationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure Temp destination can only be consumed by local connection
 *
 * @throws JMSException
 */
@Test
public void testTempDestOnlyConsumedByLocalConn() throws JMSException {
   connection.start();

   Session tempSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   TemporaryQueue queue = tempSession.createTemporaryQueue();
   MessageProducer producer = tempSession.createProducer(queue);
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
   TextMessage message = tempSession.createTextMessage("First");
   producer.send(message);

   // temp destination should not be consume when using another connection
   Connection otherConnection = factory.createConnection();
   connections.add(otherConnection);
   Session otherSession = otherConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   TemporaryQueue otherQueue = otherSession.createTemporaryQueue();
   MessageConsumer consumer = otherSession.createConsumer(otherQueue);
   Message msg = consumer.receive(3000);
   Assert.assertNull(msg);

   // should throw InvalidDestinationException when consuming a temp
   // destination from another connection
   try {
      consumer = otherSession.createConsumer(queue);
      Assert.fail("Send should fail since temp destination should be used from another connection");
   } catch (InvalidDestinationException e) {
      Assert.assertTrue("failed to throw an exception", true);
   }

   // should be able to consume temp destination from the same connection
   consumer = tempSession.createConsumer(queue);
   msg = consumer.receive(3000);
   Assert.assertNotNull(msg);

}
 
Example #21
Source File: JmsDurableTopicWildcardSendReceiveTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
   topic = true;
   durable = true;
   deliveryMode = DeliveryMode.PERSISTENT;
   super.setUp();
}
 
Example #22
Source File: NoConsumerDeadLetterTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testConsumerReceivesMessages() throws Exception {
   this.topic = false;
   ActiveMQConnectionFactory factory = createConnectionFactory();
   connection = factory.createConnection();
   connection.start();

   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(getDestination());
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

   Topic advisoryTopic = AdvisorySupport.getNoQueueConsumersAdvisoryTopic(getDestination());
   MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic);

   TextMessage msg = session.createTextMessage("Message: x");
   producer.send(msg);

   Message advisoryMessage = advisoryConsumer.receive(1000);
   assertNotNull("Advisory message not received", advisoryMessage);

   Thread.sleep(1000);

   factory = createConnectionFactory();
   connection = factory.createConnection();
   connection.start();

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

   MessageConsumer consumer = session.createConsumer(getDestination());
   Message received = consumer.receive(1000);
   assertNotNull("Message not received", received);
}
 
Example #23
Source File: RedeliveryRestartWithExceptionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void populateDestination(final int nbMessages,
                                 final Destination destination,
                                 javax.jms.Connection connection,
                                 boolean persistent) throws JMSException {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(destination);
   producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
   for (int i = 1; i <= nbMessages; i++) {
      producer.send(session.createTextMessage("<hello id='" + i + "'/>"));
   }
   producer.close();
   session.close();
}
 
Example #24
Source File: JMSMessageConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testSelectorsWithJMSTimestampOnQueue() throws Exception {
   final Connection connection = createConnection();

   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = session.createQueue(getQueueName());

      MessageProducer producer = session.createProducer(destination);

      TextMessage message1 = session.createTextMessage();
      message1.setText("filtered");
      producer.send(message1, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);

      // short delay to prevent the timestamps from being the same
      Thread.sleep(2);

      TextMessage message2 = session.createTextMessage();
      message2.setText("expected");
      producer.send(message2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);

      MessageConsumer consumer = session.createConsumer(destination, "JMSTimestamp = " + message2.getJMSTimestamp());

      connection.start();

      Message msg = consumer.receive(2000);
      assertNotNull(msg);
      assertTrue(msg instanceof TextMessage);
      assertEquals("Unexpected JMSTimestamp value", message2.getJMSTimestamp(), msg.getJMSTimestamp());
      assertEquals("Unexpected message content", "expected", ((TextMessage) msg).getText());
   } finally {
      connection.close();
   }
}
 
Example #25
Source File: JMSMessageConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void testDeliveryMode(Connection connection1, Connection connection2) throws JMSException {
   try {
      Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

      javax.jms.Queue queue1 = session1.createQueue(getQueueName());
      javax.jms.Queue queue2 = session2.createQueue(getQueueName());

      final MessageConsumer consumer2 = session2.createConsumer(queue2);

      MessageProducer producer = session1.createProducer(queue1);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);
      connection1.start();

      TextMessage message = session1.createTextMessage();
      message.setText("hello");
      producer.send(message);

      Message received = consumer2.receive(100);

      assertNotNull("Should have received a message by now.", received);
      assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);
      assertEquals(DeliveryMode.PERSISTENT, received.getJMSDeliveryMode());
   } finally {
      connection1.close();
      connection2.close();
   }
}
 
Example #26
Source File: JMSStringInputOperatorTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private void produceMsg(int numMessages) throws Exception
{
  // Create a ConnectionFactory
  ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

  // Create a Connection
  Connection connection = connectionFactory.createConnection();
  connection.start();

  // Create a Session
  Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

  // Create the destination (Topic or Queue)
  Destination destination = session.createQueue("TEST.FOO");

  // Create a MessageProducer from the Session to the Topic or Queue
  MessageProducer producer = session.createProducer(destination);
  producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

  // Create a messages
  String text = "Hello world! From tester producer";
  TextMessage message = session.createTextMessage(text);
  for (int i = 0; i < numMessages; i++) {
    producer.send(message);
  }

  // Clean up
  session.close();
  connection.close();

}
 
Example #27
Source File: XAProducerBMTSB.java    From solace-integration-guides with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage() throws JMSException {

    System.out.println("Sending reply message");
    Connection conn = null;
    Session session = null;
    MessageProducer prod = null;
    UserTransaction ux = sessionContext.getUserTransaction();

    try {
        ux.begin();
        conn = myCF.createConnection();
        session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
        prod = session.createProducer(myReplyQueue);
        ObjectMessage msg = session.createObjectMessage();
        msg.setObject("Hello world!");
        prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
        ux.commit();
    } catch (Exception e) {
        e.printStackTrace();
        try {
           ux.rollback();
        } catch (Exception ex) {
           throw new EJBException(
            "rollback failed: " + ex.getMessage(), ex);
        }
    } finally {
        if (prod != null)
      prod.close();
        if (session != null)
      session.close();
        if (conn != null)
      conn.close();
    }
}
 
Example #28
Source File: Producer.java    From jms with MIT License 5 votes vote down vote up
public void send(String text, int priority) throws JMSException {
  TextMessage message = session.createTextMessage(text);
  // Note: setting the priority directly on the JMS Message does not work
  // as in that case the priority of the producer is taken
  producer.send(message, DeliveryMode.PERSISTENT, priority, 0);

  LOGGER.info("{} sent with priority={}", text, priority);
}
 
Example #29
Source File: MessagingAddressJMSTest.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private void assertSendReceiveLargeMessage(JmsProvider jmsProvider, MessageProducer sender, MessageConsumer receiver, double sizeInMB, int mode, int count, List<javax.jms.Message> messages) {
    List<javax.jms.Message> recvd;

    jmsProvider.sendMessages(sender, messages, mode, javax.jms.Message.DEFAULT_PRIORITY, javax.jms.Message.DEFAULT_TIME_TO_LIVE);
    log.info("{}MB {} message sent", sizeInMB, mode == DeliveryMode.PERSISTENT ? "durable" : "non-durable");

    recvd = jmsProvider.receiveMessages(receiver, count, 2000);
    assertThat("Wrong count of received messages", recvd.size(), Matchers.is(count));
    log.info("{}MB {} message received", sizeInMB, mode == DeliveryMode.PERSISTENT ? "durable" : "non-durable");
}
 
Example #30
Source File: SimpleDurableTopicTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
protected PerfProducer createProducer(ConnectionFactory fac,
                                      Destination dest,
                                      int number,
                                      byte payload[]) throws JMSException {
   PerfProducer pp = new PerfProducer(fac, dest, payload);
   pp.setDeliveryMode(DeliveryMode.PERSISTENT);
   return pp;
}