Java Code Examples for javax.jms.Message#getIntProperty()

The following examples show how to use javax.jms.Message#getIntProperty() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public void onMessage(Message message) {
   if (!started) {
      startLatch.countDown();
      started = true;
   }
   try {
      int foo = message.getIntProperty("foo");
      if (foo != count) {
         e = new Exception("received out of order expected " + count + " received " + foo);
         failed = true;
         conn.close();
      }
      count++;
   } catch (JMSException e) {

      this.e = e;
      failed = true;
      try {
         conn.close();
      } catch (JMSException e1) {
         e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      }
   }
}
 
Example 2
Source Project: qpid-jms   File: SessionIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        int messageNumber = message.getIntProperty(TestAmqpPeer.MESSAGE_NUMBER);

        LOG.info("Listener received message: {}", messageNumber);

        index.compareAndSet(messageNumber - 1, messageNumber);

        done.countDown();
    } catch (Exception e) {
        LOG.error("Caught exception in listener", e);
    }
}
 
Example 3
/**
 * Gets the status code indicating the outcome of an operation from a response message.
 *
 * @param message The message.
 * @return The status code or {@code 500} if the message does not contain the corresponding property.
 */
public static int getStatus(final Message message) {
    try {
        return message.getIntProperty(MessageHelper.APP_PROPERTY_STATUS);
    } catch (final JMSException e) {
        return 500;
    }
}
 
Example 4
@Override
public void onMessage(final Message msg) {
   count++;

   try {
      msg.getIntProperty("counter");
   } catch (JMSException e) {
      e.printStackTrace();
   }
   if (count == NUM) {
      allMessagesReceived.countDown();
   }
}
 
Example 5
Source Project: activemq-artemis   File: JMSTestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected final void receiveMessages(JMSConsumer consumer, final int start, final int msgCount, final boolean ack) {
   try {
      for (int i = start; i < msgCount; i++) {
         Message message = consumer.receive(100);
         Assert.assertNotNull("Expecting a message " + i, message);
         final int actual = message.getIntProperty("counter");
         Assert.assertEquals("expected=" + i + ". Got: property['counter']=" + actual, i, actual);
         if (ack)
            message.acknowledge();
      }
   } catch (JMSException cause) {
      throw new JMSRuntimeException(cause.getMessage(), cause.getErrorCode(), cause);
   }
}
 
Example 6
@Test(timeout=60000)
public void testJMSXDeliveryCount() throws Exception {
    sendToAmqQueue(1);

    connection = createAmqpConnection();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    assertEquals(true, session.getTransacted());
    Queue queue = session.createQueue(name.getMethodName());
    MessageConsumer consumer = session.createConsumer(queue);
    connection.start();

    // we receive a message...it should be delivered once and not be Re-delivered.
    Message message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(false, message.getJMSRedelivered());
    int jmsxDeliveryCount = message.getIntProperty("JMSXDeliveryCount");
    LOG.info("Incoming message has delivery count: {}", jmsxDeliveryCount);
    assertEquals(1, jmsxDeliveryCount);
    session.rollback();

    // we receive again a message
    message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(true, message.getJMSRedelivered());
    jmsxDeliveryCount = message.getIntProperty("JMSXDeliveryCount");
    LOG.info("Redelivered message has delivery count: {}", jmsxDeliveryCount);
    assertEquals(2, jmsxDeliveryCount);
    session.rollback();

    // we receive again a message
    message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(true, message.getJMSRedelivered());
    jmsxDeliveryCount = message.getIntProperty("JMSXDeliveryCount");
    LOG.info("Redelivered message has delivery count: {}", jmsxDeliveryCount);
    assertEquals(3, jmsxDeliveryCount);
    session.commit();
}
 
Example 7
protected void checkMessage(Message in_msg) throws Exception {
   int seq;

   LOG.debug("received message " + fmtMsgInfo(in_msg) + " from " + in_msg.getJMSDestination());

   //
   // Only check messages with a sequence number.
   //

   if (in_msg.propertyExists("SEQ")) {
      seq = in_msg.getIntProperty("SEQ");

      if ((haveFirstSeq) && (seq != (lastSeq + 1))) {
         LOG.error("***ERROR*** incorrect sequence number; expected " + Integer.toString(lastSeq + 1) + " but have " + Integer.toString(seq));

         testError = true;
      }

      lastSeq = seq;

      if (msgCount > expectedCount) {
         LOG.error("*** have more messages than expected; have " + msgCount + "; expect " + expectedCount);

         testError = true;
      }
   }

   if (in_msg.propertyExists("end-of-response")) {
      LOG.trace("received end-of-response message");
   }
}
 
Example 8
public String formatMessage(Message m) {
   try {
      return "group=" + m.getStringProperty("JMSXGroupID") + ", seq=" + m.getIntProperty("JMSXGroupSeq");
   } catch (Exception e) {
      return e.getClass().getSimpleName() + ": " + e.getMessage();
   }
}
 
Example 9
public void checkMessage(Message m,
                         String consumerId,
                         Map<String, Integer> messageGroups,
                         Set<String> closedGroups) throws JMSException {
   String groupId = m.getStringProperty("JMSXGroupID");
   int seq = m.getIntProperty("JMSXGroupSeq");
   Integer count = messageGroups.get(groupId);
   if (count == null) {
      // first time seeing this group
      if (!m.propertyExists("JMSXGroupFirstForConsumer") || !m.getBooleanProperty("JMSXGroupFirstForConsumer")) {
         LOG.info(consumerId + ": JMSXGroupFirstForConsumer not set for group=" + groupId + ", seq=" + seq);
         errorCountFirstForConsumer++;
      }
      if (seq == -1) {
         closedGroups.add(groupId);
         LOG.info(consumerId + ": wrong consumer got close message for group=" + groupId);
         errorCountWrongConsumerClose++;
      }
      messageGroups.put(groupId, 1);
   } else {
      // existing group
      if (closedGroups.contains(groupId)) {
         // group reassigned to same consumer
         closedGroups.remove(groupId);
         if (!m.propertyExists("JMSXGroupFirstForConsumer") || !m.getBooleanProperty("JMSXGroupFirstForConsumer")) {
            LOG.info(consumerId + ": JMSXGroupFirstForConsumer not set for group=" + groupId + ", seq=" + seq);
            errorCountFirstForConsumer++;
         }
         if (seq == -1) {
            LOG.info(consumerId + ": consumer got duplicate close message for group=" + groupId);
            errorCountDuplicateClose++;
         }
      }
      if (seq == -1) {
         closedGroups.add(groupId);
      }
      messageGroups.put(groupId, count + 1);
   }
}
 
Example 10
@Test
public void testJMSXDeliveryCountConversion() throws Exception {
   Message m1 = queueProducerSession.createMessage();
   queueProducer.send(m1);

   Message m2 = queueConsumer.receive(2000);

   int count = m2.getIntProperty("JMSXDeliveryCount");
   ProxyAssertSupport.assertEquals(String.valueOf(count), m2.getStringProperty("JMSXDeliveryCount"));
   ProxyAssertSupport.assertEquals(count, m2.getLongProperty("JMSXDeliveryCount"));
}
 
Example 11
Source Project: qpid-jms   File: JmsDupsOkTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        int msgNumProperty = message.getIntProperty(MESSAGE_NUMBER);

        if(complete ){
            LOG.info("Test already finished, ignoring delivered message: " + msgNumProperty);
            return;
        }

        if (msgNumProperty == 1) {
            if (!seenFirstMessage) {
                LOG.info("Received first message.");
                seenFirstMessage = true;
            } else {
                LOG.error("Received first message again.");
                complete(true);
            }
        } else if (msgNumProperty == 2) {
            if(!seenSecondMessage){
                seenSecondMessage = true;
                LOG.info("Received second message. Now calling recover()");
                session.recover();
            } else {
                LOG.info("Received second message again as expected.");
                seenSecondMessageTwice = true;
                if(message.getJMSRedelivered()) {
                    LOG.info("Message was marked redelivered as expected.");
                } else {
                    LOG.error("Message was not marked redelivered.");
                    complete(true);
                }
            }
        } else {
            if (msgNumProperty != 3) {
                LOG.error("Received unexpected message: " + msgNumProperty);
                complete(true);
                return;
            }

            if (!(seenFirstMessage && seenSecondMessageTwice)) {
                LOG.error("Third message was not received in expected sequence.");
                complete(true);
                return;
            }

            LOG.info("Received third message.");

            if(message.getJMSRedelivered()) {
                LOG.error("Message was marked redelivered against expectation.");
                complete(true);
            } else {
                LOG.info("Message was not marked redelivered, as expected.");
                complete(false);
            }
        }
    } catch (JMSException e) {
        LOG.error("Exception caught in listener", e);
        complete(true);
    }
}
 
Example 12
Source Project: qpid-broker-j   File: MaxDeliveryTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void maximumDelivery() throws Exception
{
    String queueName = getTestName();
    String dlqNAme = getTestName() + "_DLQ";

    createMaxDeliveryQueueAndDLQ(queueName, MAX_DELIVERY_ATTEMPTS, dlqNAme);
    int numberOfMessages = 5;
    Connection connection = getConnectionBuilder().setMessageRedelivery(true).build();
    try
    {
        final Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        final Queue queue = session.createQueue(queueName);
        final MessageConsumer consumer = session.createConsumer(queue);
        Utils.sendMessages(connection, queue, numberOfMessages);

        connection.start();

        int expectedMessageIndex = 0;
        int deliveryAttempt = 0;
        int deliveryCounter = 0;
        do
        {
            Message message = consumer.receive(getReceiveTimeout());
            assertNotNull(String.format("Message '%d' was not received in delivery attempt %d",
                                        expectedMessageIndex,
                                        deliveryAttempt), message);
            int index = message.getIntProperty(INDEX);
            assertEquals(String.format("Unexpected message index (delivery attempt %d)", deliveryAttempt),
                         expectedMessageIndex,
                         index);

            deliveryCounter++;

            // dlq all even messages
            if (index % 2 == 0)
            {
                session.rollback();
                if (deliveryAttempt < MAX_DELIVERY_ATTEMPTS - 1)
                {
                    deliveryAttempt++;
                }
                else
                {
                    deliveryAttempt = 0;
                    expectedMessageIndex++;
                }
            }
            else
            {
                session.commit();
                deliveryAttempt = 0;
                expectedMessageIndex++;
            }
        }
        while (expectedMessageIndex != numberOfMessages);

        int numberOfEvenMessages = numberOfMessages / 2 + 1;
        assertEquals("Unexpected total delivery counter",
                     numberOfEvenMessages * MAX_DELIVERY_ATTEMPTS + (numberOfMessages - numberOfEvenMessages),
                     deliveryCounter);

        verifyDeadLetterQueueMessages(connection, dlqNAme, numberOfEvenMessages);
    }
    finally
    {
        connection.close();
    }
}
 
Example 13
private void putMessageInMap(Message message, Map<String, Integer> messageSequenceNumbersByKey) throws JMSException
{
    String keyValue = message.getStringProperty(KEY_PROPERTY);
    Integer messageSequenceNumber = message.getIntProperty(MESSAGE_SEQUENCE_NUMBER_PROPERTY);
    messageSequenceNumbersByKey.put(keyValue, messageSequenceNumber);
}
 
Example 14
private void consumeIgnoringLastSeenOmission(final Connection connection,
                                             final Queue testQueue,
                                             int fromIndex,
                                             int toIndex,
                                             int consumerLastSeenMessageIndex)
        throws JMSException
{
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(testQueue);
    int expectedIndex = fromIndex;
    while (expectedIndex < toIndex)
    {
        Message message = consumer.receive(getReceiveTimeout());
        if (message == null && consumerLastSeenMessageIndex + 1 == toIndex)
        {
            // this is a corner case when one remaining message is expected
            // but it was already received previously, Commit was sent
            // and broker successfully committed and sent back CommitOk
            // but CommitOk did not reach client due to abrupt disconnect
            LOGGER.debug( "Broker transaction was completed for message {}"
                            + " but there was no network to notify client about its completion.",
                    consumerLastSeenMessageIndex);
        }
        else
        {
            assertNotNull("Expected message with index " + expectedIndex + " but got null", message);
            int messageIndex = message.getIntProperty(Utils.INDEX);
            LOGGER.debug("Received message with index {}, expected index is {}", messageIndex, expectedIndex);
            if (messageIndex != expectedIndex
                    && expectedIndex == fromIndex
                    && messageIndex == consumerLastSeenMessageIndex + 1)
            {
                LOGGER.debug("Broker transaction was completed for message {}"
                                + " but there was no network to notify client about its completion.",
                        consumerLastSeenMessageIndex);
                expectedIndex = messageIndex;
            }
            assertEquals("Unexpected message index", expectedIndex, messageIndex);
        }
        expectedIndex++;
    }
    session.close();
}
 
Example 15
@Override
public void run()
{
    _thread = Thread.currentThread();
    try
    {
        while (!_closed.get())
        {
            if (_consumedMessageCounter == _numberOfMessagesToInvokeRunnableAfter && _runnable != null)
            {
                _executorService.execute(_runnable);
            }

            Message message = _messageConsumer.receive(getReceiveTimeout());
            if (message != null)
            {
                int messageIndex = message.getIntProperty(Utils.INDEX);
                _lastSeenMessageIndex = messageIndex;
                LOGGER.debug("Received message with index {}, expected index {}",
                             messageIndex,
                             _consumedMessageCounter);
                assertEquals("Unexpected message index",
                                      _consumedMessageCounter,
                                      messageIndex);

                if (_session.getTransacted())
                {
                    _session.commit();
                    LOGGER.debug("Committed message with index {}", messageIndex);
                }
                _consumedMessageCounter++;
            }
        }
        LOGGER.debug("Stopping consumer gracefully");
    }
    catch (Exception e)
    {
        LOGGER.debug("Stopping consumer due to exception, number of consumed {}", _consumedMessageCounter, e);
        _exception = e;
    }
}
 
Example 16
Source Project: qpid-jms   File: JmsClientAckTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        int msgNumProperty = message.getIntProperty(MESSAGE_NUMBER);

        if(complete ){
            LOG.info("Test already finished, ignoring delivered message: " + msgNumProperty);
            return;
        }

        if (msgNumProperty == 1) {
            if (!seenFirstMessage) {
                LOG.info("Received first message.");
                seenFirstMessage = true;
            } else {
                LOG.info("Received first message again.");
                if(message.getJMSRedelivered()) {
                    LOG.info("Message was marked redelivered as expected.");
                } else {
                    LOG.error("Message was not marked redelivered.");
                    complete(true);
                }
                seenFirstMessageTwice = true;
            }
        } else if (msgNumProperty == 2) {
            if(!seenSecondMessage){
                seenSecondMessage = true;
                LOG.info("Received second message. Now calling recover()");
                session.recover();
            } else {
                if (!seenFirstMessageTwice) {
                    LOG.error("Received second message again before seeing first message again.");
                    complete(true);
                    return;
                }

                LOG.info("Received second message again as expected.");
                seenSecondMessageTwice = true;

                if(message.getJMSRedelivered()) {
                    LOG.info("Message was marked redelivered as expected.");
                } else {
                    LOG.error("Message was not marked redelivered.");
                    complete(true);
                }
            }
        } else {
            if (msgNumProperty != 3) {
                LOG.error("Received unexpected message: " + msgNumProperty);
                complete(true);
                return;
            }

            if (!(seenFirstMessageTwice && seenSecondMessageTwice)) {
                LOG.error("Third message was not received in expected sequence.");
                complete(true);
                return;
            }

            if(message.getJMSRedelivered()) {
                LOG.error("Message was marked redelivered against expectation.");
                complete(true);
            } else {
                LOG.info("Message was not marked redelivered, as expected.");
                complete(false);
            }
        }
    } catch (JMSException e) {
        LOG.error("Exception caught in listener", e);
        complete(true);
    }
}
 
Example 17
Source Project: qpid-jms   File: JmsAutoAckTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        int msgNumProperty = message.getIntProperty(MESSAGE_NUMBER);

        if(complete ){
            LOG.info("Test already finished, ignoring delivered message: " + msgNumProperty);
            return;
        }

        if (msgNumProperty == 1) {
            if (!seenFirstMessage) {
                LOG.info("Received first message.");
                seenFirstMessage = true;
            } else {
                LOG.error("Received first message again.");
                complete(true);
            }
        } else if (msgNumProperty == 2) {
            if(!seenSecondMessage){
                seenSecondMessage = true;
                LOG.info("Received second message. Now calling recover()");
                session.recover();
            } else {
                LOG.info("Received second message again as expected.");
                seenSecondMessageTwice = true;
                if(message.getJMSRedelivered()) {
                    LOG.info("Message was marked redelivered as expected.");
                } else {
                    LOG.error("Message was not marked redelivered.");
                    complete(true);
                }
            }
        } else {
            if (msgNumProperty != 3) {
                LOG.error("Received unexpected message: " + msgNumProperty);
                complete(true);
                return;
            }

            if (!(seenFirstMessage && seenSecondMessageTwice)) {
                LOG.error("Third message was not received in expected sequence.");
                complete(true);
                return;
            }

            LOG.info("Received third message.");

            if(message.getJMSRedelivered()) {
                LOG.error("Message was marked redelivered against expectation.");
                complete(true);
            } else {
                LOG.info("Message was not marked redelivered, as expected.");
                complete(false);
            }
        }
    } catch (JMSException e) {
        LOG.error("Exception caught in listener", e);
        complete(true);
    }
}
 
Example 18
private void process(long millis) throws JMSException {
   //long end = System.currentTimeMillis() + millis;
   long end = System.currentTimeMillis() + 200;
   long hardEnd = end + 20000; // wait to finish the transaction.
   boolean inTransaction = false;
   int transCount = 0;

   Connection con = openConnection();
   Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   consumer = (ActiveMQMessageConsumer) sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false);
   LOG.info(toString() + " ONLINE.");
   try {
      do {
         long max = end - System.currentTimeMillis();
         if (max <= 0) {
            if (!inTransaction) {
               LOG.info(toString() + " done after no work!");
               break;
            }

            max = hardEnd - System.currentTimeMillis();
            if (max <= 0)
               exit("" + this + " failed: Transaction is not finished.");
         }

         Message message = consumer.receive(max);
         if (message == null)
            continue;

         onClientMessage(message);

         if (message.propertyExists("COMMIT")) {
            message.acknowledge(); // CLIENT_ACKNOWLEDGE

            int trans = message.getIntProperty("TRANS");
            LOG.info("Received Trans[id=" + trans + ", count=" + transCount + "] in " + this + ".");

            inTransaction = false;
            transCount = 0;

            int committing = server.committingTransaction;
            if (committing == trans) {
               LOG.info("Going offline during transaction commit. messageID=" + message.getIntProperty("ID"));
               break;
            }
         } else {
            inTransaction = true;
            transCount++;
            if (1 == transCount) {
               LOG.info("In Trans[id=" + message.getIntProperty("TRANS") + "] first ID=" + message.getIntProperty("ID"));
            }
         }
      } while (true);
   } finally {
      sess.close();
      con.close();

      LOG.info(toString() + " OFFLINE.");

      // Check if the messages are in the waiting
      // list for long time.
      Message topMessage = waitingList.peek();
      if (topMessage != null)
         checkDeliveryTime(topMessage);
   }
}
 
Example 19
public void testGetAndSetJMSXDeliveryCount() throws JMSException {
   Message msg = new ActiveMQMessage();
   msg.setIntProperty("JMSXDeliveryCount", 1);
   int count = msg.getIntProperty("JMSXDeliveryCount");
   assertTrue("expected delivery count = 1 - got: " + count, count == 1);
}
 
Example 20
Source Project: qpid-jms   File: SessionIntegrationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testAcknowledgeIndividualMessages()  throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

        Session session = connection.createSession(INDIVIDUAL_ACK);
        Queue queue = session.createQueue("myQueue");

        int msgCount = 5;
        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType(null), msgCount, false, false,
                Matchers.greaterThanOrEqualTo(UnsignedInteger.valueOf(msgCount)), 1, false, true);

        MessageConsumer messageConsumer = session.createConsumer(queue);

        List<Message> messages = new ArrayList<>();
        Message lastReceivedMessage = null;
        for (int i = 0; i < msgCount; i++) {
            lastReceivedMessage = messageConsumer.receive(3000);
            assertNotNull("Message " + i + " was not received", lastReceivedMessage);
            messages.add(lastReceivedMessage);

            assertEquals("unexpected message number property", i, lastReceivedMessage.getIntProperty(TestAmqpPeer.MESSAGE_NUMBER));
        }

        // Acknowledge the messages in a random order, verify only that messages disposition arrives each time.
        Random rand = new Random();
        for (int i = 0; i < msgCount; i++) {
            Message msg = messages.remove(rand.nextInt(msgCount - i));

            int deliveryNumber =  msg.getIntProperty(TestAmqpPeer.MESSAGE_NUMBER) + 1;

            testPeer.expectDisposition(true, new AcceptedMatcher(), deliveryNumber, deliveryNumber);

            msg.acknowledge();

            testPeer.waitForAllHandlersToComplete(3000);
        }

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

        testPeer.waitForAllHandlersToComplete(3000);
    }
}