javax.jms.Session Java Examples

The following examples show how to use javax.jms.Session. 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: JmsConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeDurable() throws Exception {
   conn = cf.createConnection();
   conn.setClientID("C1");
   conn.start();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   MessageConsumer cons = session.createSharedDurableConsumer(topic, "c1");

   MessageProducer prod = session.createProducer(topic);

   for (int i = 0; i < 100; i++) {
      prod.send(session.createTextMessage("msg" + i));
   }

   Assert.assertNotNull(cons.receive(5000));

   cons.close();

   session.unsubscribe("c1");

   cons = session.createSharedDurableConsumer(topic, "c1");

   // it should be null since the queue was deleted through unsubscribe
   Assert.assertNull(cons.receiveNoWait());
}
 
Example #2
Source File: JMSMessageGroupsTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void readMessagesOnBroker(String queueName, Connection connection, int count, AtomicInteger sequence, BiConsumer<Integer, Message> additionalCheck) throws Exception {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(queueName);
   MessageConsumer consumer = session.createConsumer(queue);

   for (int i = 0; i < MESSAGE_COUNT; ++i) {
      Message message = consumer.receive(RECEIVE_TIMEOUT);
      assertNotNull(message);
      LOG.debug("Read message #{}: type = {}", i, message.getClass().getSimpleName());
      String gid = message.getStringProperty("JMSXGroupID");
      int seq = message.getIntProperty("JMSXGroupSeq");
      LOG.debug("Message assigned JMSXGroupID := {}", gid);
      LOG.debug("Message assigned JMSXGroupSeq := {}", seq);
      assertEquals("Sequence order should match", sequence.incrementAndGet(), seq);
      if (additionalCheck != null) {
         additionalCheck.accept(i, message);
      }
   }

   session.close();
}
 
Example #3
Source File: StandardJmsActivationSpecFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Apply the specified acknowledge mode to the ActivationSpec object.
 * <p>This implementation applies the standard JCA 1.5 acknowledge modes
 * "Auto-acknowledge" and "Dups-ok-acknowledge". It throws an exception in
 * case of {@code CLIENT_ACKNOWLEDGE} or {@code SESSION_TRANSACTED}
 * having been requested.
 * @param bw the BeanWrapper wrapping the ActivationSpec object
 * @param ackMode the configured acknowledge mode
 * (according to the constants in {@link javax.jms.Session}
 * @see javax.jms.Session#AUTO_ACKNOWLEDGE
 * @see javax.jms.Session#DUPS_OK_ACKNOWLEDGE
 * @see javax.jms.Session#CLIENT_ACKNOWLEDGE
 * @see javax.jms.Session#SESSION_TRANSACTED
 */
protected void applyAcknowledgeMode(BeanWrapper bw, int ackMode) {
	if (ackMode == Session.SESSION_TRANSACTED) {
		throw new IllegalArgumentException("No support for SESSION_TRANSACTED: Only \"Auto-acknowledge\" " +
				"and \"Dups-ok-acknowledge\" supported in standard JCA 1.5");
	}
	else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
		throw new IllegalArgumentException("No support for CLIENT_ACKNOWLEDGE: Only \"Auto-acknowledge\" " +
				"and \"Dups-ok-acknowledge\" supported in standard JCA 1.5");
	}
	else if (bw.isWritableProperty("acknowledgeMode")) {
		bw.setPropertyValue("acknowledgeMode",
				ackMode == Session.DUPS_OK_ACKNOWLEDGE ? "Dups-ok-acknowledge" : "Auto-acknowledge");
	}
	else if (ackMode == Session.DUPS_OK_ACKNOWLEDGE) {
		// Standard JCA 1.5 "acknowledgeMode" apparently not supported (e.g. WebSphere MQ 6.0.2.1)
		throw new IllegalArgumentException("Dups-ok-acknowledge not supported by underlying provider");
	}
}
 
Example #4
Source File: ProduceToOpenWireTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testProduceRateToTopic() throws Exception {

    connection = createActiveMQConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(getDestinationName());

    // Warm Up the broker.
    produceMessages(topic, MSG_COUNT);

    List<Long> sendTimes = new ArrayList<Long>();
    long cumulative = 0;

    for (int i = 0; i < NUM_RUNS; ++i) {
        long result = produceMessages(topic, MSG_COUNT);
        sendTimes.add(result);
        cumulative += result;
        LOG.info("Time to send {} topic messages: {} ms", MSG_COUNT, result);
    }

    long smoothed = cumulative / NUM_RUNS;
    LOG.info("Smoothed send time for {} messages: {}", MSG_COUNT, smoothed);
}
 
Example #5
Source File: MessageTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void publishEmptyMessage() throws Exception
{
    Map<String, Object> messageBody = new HashMap<>();
    messageBody.put("address", QUEUE_NAME);

    getHelper().submitRequest("virtualhost/publishMessage",
                              "POST",
                              Collections.singletonMap("message", messageBody),
                              SC_OK);

    Connection connection = getConnection();
    try
    {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(queue);
        Message message = consumer.receive(getReceiveTimeout());
        assertThat(message, is(notNullValue()));
    }
    finally
    {
        connection.close();
    }
}
 
Example #6
Source File: testSendMessage1InSB_TestingSessionBean.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void sendJMSMessageToTestingMessageBean(Object messageData) throws JMSException, NamingException {
    Context c = new InitialContext();
    ConnectionFactory cf = (ConnectionFactory) c.lookup("java:comp/env/jms/TestingMessageBeanFactory");
    Connection conn = null;
    Session s = null;
    try {
        conn = cf.createConnection();
        s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
        Destination destination = (Destination) c.lookup("java:comp/env/jms/TestingMessageBean");
        MessageProducer mp = s.createProducer(destination);
        mp.send(createJMSMessageForjmsTestingMessageBean(s, messageData));
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (JMSException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
            }
        }
        if (conn != null) {
            conn.close();
        }
    }
}
 
Example #7
Source File: MQTTTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void doTestSendJMSReceiveMQTT(String destinationName) throws Exception {
   final MQTTClientProvider provider = getMQTTClientProvider();
   initializeConnection(provider);
   provider.subscribe("foo/+", AT_MOST_ONCE);

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

   Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   javax.jms.Topic topic = s.createTopic(destinationName);
   MessageProducer producer = s.createProducer(topic);

   // send retained message from JMS
   final byte[] bytes = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   BytesMessage bytesMessage = s.createBytesMessage();
   bytesMessage.writeBytes(bytes);
   producer.send(bytesMessage);

   byte[] message = provider.receive(10000);
   assertNotNull("Should get retained message", message);
   assertArrayEquals(bytes, message);

   provider.disconnect();
   connection.close();
}
 
Example #8
Source File: MessageConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSelector() throws Exception {
   Connection consumerConnection = null;

   try {
      consumerConnection = createConnection();

      Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      String selector = "JMSType = 'something'";

      MessageConsumer topicConsumer = consumerSession.createConsumer(ActiveMQServerTestCase.topic1, selector);

      ProxyAssertSupport.assertEquals(selector, topicConsumer.getMessageSelector());
   } finally {
      if (consumerConnection != null) {
         consumerConnection.close();
      }
   }
}
 
Example #9
Source File: JMSFacade.java    From iaf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a MessageConsumer. In this overloaded function the selector is taken into account.
 * This ensures that listeners (or other extensions of this class) do not influence how the selector
 * is used: when a correlationID should be in the filter the  <code>getMessageConsumerForCorrelationId</code>
 * should be used, other wise the <code>getMessageConsumer</code> function which has no attribute for
 * <code>selector</code>. When a MessageSelector is set, it will be used when no correlation id is required.
 * @param session the Session
 * @param destination the Destination
 * @param selector the MessageSelector
 * @return MessageConsumer
 */
public MessageConsumer getMessageConsumer(Session session, Destination destination, String selector) throws NamingException, JMSException {
	if (useTopicFunctions) {
		if (useJms102()) {
			return getTopicSubscriber((TopicSession)session, (Topic)destination, selector);
		} else {
			return getTopicSubscriber(session, (Topic)destination, selector);
		}
	} else {
		if (useJms102()) {
			return getQueueReceiver((QueueSession)session, (Queue)destination, selector);
		} else {
			return session.createConsumer(destination, selector);
		}
	}
}
 
Example #10
Source File: ProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testCloseSender() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");
        MessageProducer producer = session.createProducer(queue);

        testPeer.expectDetach(true, true, true);
        testPeer.expectClose();

        producer.close();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example #11
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Create a browser
 *
 * @param queue           The queue
 * @param messageSelector The message selector
 * @return The browser
 * @throws JMSException Thrown if an error occurs
 */
@Override
public QueueBrowser createBrowser(final Queue queue, final String messageSelector) throws JMSException {
   if (cri.getType() == ActiveMQRAConnectionFactory.TOPIC_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_TOPIC_CONNECTION) {
      throw new IllegalStateException("Cannot create browser for javax.jms.TopicSession");
   }

   Session session = getSessionInternal();

   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("createBrowser " + session + " queue=" + queue + " selector=" + messageSelector);
   }

   QueueBrowser result = session.createBrowser(queue, messageSelector);

   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("createdBrowser " + session + " browser=" + result);
   }

   return result;
}
 
Example #12
Source File: ProducerFlowControlBaseTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected CountDownLatch asyncSendTo(final ActiveMQQueue queue, final String message) throws JMSException {
   final CountDownLatch done = new CountDownLatch(1);
   new Thread("Send thread.") {
      @Override
      public void run() {
         Session session = null;
         try {
            session = flowControlConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(queue);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            producer.send(session.createTextMessage(message));
            done.countDown();
         } catch (JMSException e) {
            e.printStackTrace();
         } finally {
            safeClose(session);
         }
      }
   }.start();
   return done;
}
 
Example #13
Source File: JournalPendingMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeliveringStats() throws Exception {
   AtomicLong publishedMessageSize = new AtomicLong();

   Connection connection = cf.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
   producer.send(session.createTextMessage("test"));

   verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
   verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
   verifyDeliveringStats(defaultQueueName, 0, 0);

   MessageConsumer consumer = session.createConsumer(session.createQueue(defaultQueueName));
   Message msg = consumer.receive();
   verifyDeliveringStats(defaultQueueName, 1, publishedMessageSize.get());
   msg.acknowledge();

   verifyPendingStats(defaultQueueName, 0, 0);
   verifyPendingDurableStats(defaultQueueName, 0, 0);
   verifyDeliveringStats(defaultQueueName, 0, 0);

   connection.close();
}
 
Example #14
Source File: AmqpManagementFacade.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public Map<String,Object> updateEntityUsingAmqpManagementAndReceiveResponse(final String name,
                                                              final String type,
                                                              Map<String, Object> attributes,
                                                              final Session session)
        throws JMSException
{

    Destination replyToDestination;
    Destination replyConsumerDestination;
    if (_protocol == Protocol.AMQP_1_0)
    {
        replyToDestination = session.createTemporaryQueue();
        replyConsumerDestination = replyToDestination;
    }
    else
    {
        replyToDestination = session.createQueue(AMQP_0_X_REPLY_TO_DESTINATION);
        replyConsumerDestination = session.createQueue(AMQP_0_X_CONSUMER_REPLY_DESTINATION);
    }

    MessageConsumer consumer = session.createConsumer(replyConsumerDestination);

    updateEntityUsingAmqpManagement(name, type, attributes, replyToDestination, session);

    return receiveManagementResponse(consumer, replyToDestination, 200);
}
 
Example #15
Source File: DestinationListenerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testProducerForcesNotificationOfNewDestination() throws Exception {
   // now lets cause a destination to be created
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   ActiveMQQueue newQueue = new ActiveMQQueue("Test.Beer");
   MessageProducer producer = session.createProducer(newQueue);
   TextMessage message = session.createTextMessage("<hello>world</hello>");
   producer.send(message);

   Thread.sleep(3000);

   assertThat(newQueue, isIn(newDestinations));

   LOG.info("New destinations are: " + newDestinations);
}
 
Example #16
Source File: MQClientHandler.java    From Thunder with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(final BytesMessage message, final Session session) throws JMSException {
    final ProtocolResponse response = (ProtocolResponse) mqMessageConverter.fromMessage(message);
    // 如果消费线程里面放子线程:
    // 好处是可以加快消费速度,减少MQ消息堆积,
    // 坏处是如果子线程消费速度跟不上,会造成消息在内存中的堆积,一旦服务器挂掉,消息全部丢失
    // 最终还是去掉子线程
    String interfaze = response.getInterface();
    /*ThreadPoolFactory.createThreadPoolClientExecutor(interfaze).submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {*/
            try {
                String responseSelector = MQSelectorUtil.getResponseSelector(message);
                // String requestSelector = MQSelectorUtil.getRequestSelector(message);

                if (transportLogPrint) {
                    LOG.info("Response from server={}, service={}", responseSelector, interfaze);
                }

                ClientExecutorAdapter clientExecutorAdapter = executorContainer.getClientExecutorAdapter();
                clientExecutorAdapter.handle(response);
            } catch (Exception e) {
                LOG.error("Consume request failed", e);
            }

            /*return null;
        }
    });*/
}
 
Example #17
Source File: AbstractMessageListenerContainer.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Perform a rollback, if appropriate.
 * @param session the JMS Session to rollback
 * @throws javax.jms.JMSException in case of a rollback error
 */
protected void rollbackIfNecessary(Session session) throws JMSException {
	if (session.getTransacted()) {
		if (isSessionLocallyTransacted(session)) {
			// Transacted session created by this container -> rollback.
			JmsUtils.rollbackIfNecessary(session);
		}
	}
	else if (isClientAcknowledge(session)) {
		session.recover();
	}
}
 
Example #18
Source File: PollingMessageListenerContainer.java    From cxf with Apache License 2.0 5 votes vote down vote up
private MessageConsumer createConsumer(Destination destination, Session session) throws JMSException {
    if (durableSubscriptionName != null && destination instanceof Topic) {
        return session.createDurableSubscriber((Topic)destination, durableSubscriptionName,
                                               messageSelector, pubSubNoLocal);
    }
    return session.createConsumer(destination, messageSelector);
}
 
Example #19
Source File: JMSUtil.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static Message sendMessageWithProperty(final Session session,
                                              final Destination destination,
                                              final String key,
                                              final String value) throws JMSException {
   MessageProducer producer = session.createProducer(destination);
   Message message = session.createMessage();
   message.setStringProperty(key, value);
   producer.send(message);
   return message;
}
 
Example #20
Source File: MessageTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void publishMessageApplicationHeaders() throws Exception
{
    final String stringPropValue = "mystring";
    final String longStringPropValue = Strings.repeat("*", 256);
    final Map<String, Object> headers = new HashMap<>();
    headers.put("stringprop", stringPropValue);
    headers.put("longstringprop", longStringPropValue);
    headers.put("intprop", Integer.MIN_VALUE);
    headers.put("longprop", Long.MAX_VALUE);
    headers.put("boolprop", Boolean.TRUE);

    final Map<String, Object> messageBody = new HashMap<>();
    messageBody.put("address", QUEUE_NAME);
    messageBody.put("headers", headers);

    getHelper().submitRequest("virtualhost/publishMessage",
                              "POST",
                              Collections.singletonMap("message", messageBody),
                              SC_OK);

    Connection connection = getConnection();
    try
    {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(queue);
        Message message = consumer.receive(getReceiveTimeout());
        assertThat(message, is(notNullValue()));
        assertThat(message.getStringProperty("stringprop"), is(equalTo(stringPropValue)));
        assertThat(message.getIntProperty("intprop"), is(equalTo(Integer.MIN_VALUE)));
        assertThat(message.getLongProperty("longprop"), is(equalTo(Long.MAX_VALUE)));
        assertThat(message.getBooleanProperty("boolprop"), is(equalTo(Boolean.TRUE)));
    }
    finally
    {
        connection.close();
    }
}
 
Example #21
Source File: ExpiryHogTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
protected TextMessage createTextMessage(Session session, String initText) throws Exception {
   if (sleep) {
      TimeUnit.SECONDS.sleep(10);
   }
   TextMessage msg = super.createTextMessage(session, initText);
   msg.setJMSExpiration(4000);
   return msg;
}
 
Example #22
Source File: JMSSharedDurableConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void testSharedDurableConsumer(Connection connection1, Connection connection2) throws JMSException {
   try {
      Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Topic topic = session1.createTopic(getTopicName());
      Topic topic2 = session2.createTopic(getTopicName());

      final MessageConsumer consumer1 = session1.createSharedDurableConsumer(topic, "SharedConsumer");
      final MessageConsumer consumer2 = session2.createSharedDurableConsumer(topic2, "SharedConsumer");

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

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

      Message message1 = consumer1.receive(100);
      Message message2 = consumer2.receive(100);

      Message received = null;
      if (message1 != null) {
         assertNull("Message should only be delivered once per subscribtion but see twice", message2);
         received = message1;
      } else {
         received = message2;
      }
      assertNotNull("Should have received a message by now.", received);
      assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);

      consumer1.close();
      consumer2.close();
      session1.unsubscribe("SharedConsumer");
   } finally {
      connection1.close();
      connection2.close();
   }
}
 
Example #23
Source File: MessageCompressionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private ActiveMQStreamMessage receiveTestStreamMessage(ActiveMQConnectionFactory factory) throws JMSException {
   ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createConsumer(queue);
   ActiveMQStreamMessage rc = (ActiveMQStreamMessage) consumer.receive();
   connection.close();
   return rc;
}
 
Example #24
Source File: JmsTopicRequestReplyTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
   super.setUp();

   serverConnection = createConnection();
   serverConnection.setClientID("serverConnection:" + getSubject());
   serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

   replyProducer = serverSession.createProducer(null);

   requestDestination = createDestination(serverSession);

     /* build queues */
   final MessageConsumer requestConsumer = serverSession.createConsumer(requestDestination);
   if (useAsyncConsume) {
      requestConsumer.setMessageListener(this);
   } else {
      Thread thread = new Thread(new Runnable() {
         @Override
         public void run() {
            syncConsumeLoop(requestConsumer);
         }
      });
      thread.start();
   }
   serverConnection.start();
}
 
Example #25
Source File: JmsMessageConsumer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the next available message for this consumer and returns the body of that message
 * if the type requested matches that of the message.  The amount of time this method blocks
 * is based on the timeout value.
 *
 *   {@literal timeout < 0} then it blocks until a message is received.
 *   {@literal timeout = 0} then it returns the body immediately or null if none available.
 *   {@literal timeout > 0} then it blocks up to timeout amount of time.
 *
 * @param desired
 *      The type to assign the body of the message to for return.
 * @param timeout
 *      The time to wait for an incoming message before this method returns null.
 *
 * @return the assigned body of the next available message or null if the consumer is closed
 *         or the specified timeout elapses.
 *
 * @throws MessageFormatException if the message body cannot be assigned to the requested type.
 * @throws JMSException if an error occurs while receiving the next message.
 */
public <T> T receiveBody(Class<T> desired, long timeout) throws JMSException {
    checkClosed();
    checkMessageListener();

    T messageBody = null;
    JmsInboundMessageDispatch envelope = null;

    try {
        envelope = dequeue(timeout, connection.isReceiveLocalOnly());
        if (envelope != null) {
            messageBody = envelope.getMessage().getBody(desired);
        }
    } catch (MessageFormatException mfe) {
        // Should behave as if receiveBody never happened in these modes.
        if (acknowledgementMode == Session.AUTO_ACKNOWLEDGE ||
            acknowledgementMode == Session.DUPS_OK_ACKNOWLEDGE) {

            envelope.setEnqueueFirst(true);
            onInboundMessage(envelope);
            envelope = null;
        }

        throw mfe;
    } finally {
        if (envelope != null) {
            ackFromReceive(envelope);
        }
    }

    return messageBody;
}
 
Example #26
Source File: OutgoingConnectionNoJTATest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleMessageSendAndReceive() throws Exception {
   QueueConnection queueConnection = qraConnectionFactory.createQueueConnection();
   Session s = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue q = ActiveMQJMSClient.createQueue(MDBQUEUE);
   MessageProducer mp = s.createProducer(q);
   MessageConsumer consumer = s.createConsumer(q);
   Message message = s.createTextMessage("test");
   mp.send(message);
   queueConnection.start();
   TextMessage textMessage = (TextMessage) consumer.receive(1000);
   assertNotNull(textMessage);
   assertEquals(textMessage.getText(), "test");
}
 
Example #27
Source File: DynamicDestinationResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolveWithPointToPointVanillaSession() throws Exception {
	Queue expectedDestination = new StubQueue();
	Session session = mock(Session.class);
	given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination);
	testResolveDestination(session, expectedDestination, false);
}
 
Example #28
Source File: ClientJmsDelegate.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void addSubscription(String subscriptionName, Session session)
{
    if(_testSubscriptions.putIfAbsent(subscriptionName, session) != null)
    {
        throw new DistributedTestException("Subscribing session '" + subscriptionName + "' is already registered");
    }
}
 
Example #29
Source File: MessageCompressionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private ActiveMQBytesMessage receiveTestBytesMessage(ActiveMQConnectionFactory factory) throws JMSException, UnsupportedEncodingException {
   ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createConsumer(queue);
   ActiveMQBytesMessage rc = (ActiveMQBytesMessage) consumer.receive();
   connection.close();
   return rc;
}
 
Example #30
Source File: AutoAckMessageListenerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoAckMsgListenerQueue() throws Exception {
   Connection conn = null;

   try {
      CountDownLatch latch = new CountDownLatch(1);

      conn = createConnection();
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(queue1);
      MessageConsumer consumer = session.createConsumer(queue1);
      AutoAckMsgListener listener = new AutoAckMsgListener(latch, session);
      consumer.setMessageListener(listener);

      // create and send messages
      log.debug("Send and receive two message");
      Message messageSent = session.createMessage();
      messageSent.setBooleanProperty("last", false);
      producer.send(messageSent);
      messageSent.setBooleanProperty("last", true);
      producer.send(messageSent);

      conn.start();

      // wait until message is received
      log.debug("waiting until message has been received by message listener...");
      latch.await(10, TimeUnit.SECONDS);

      // check message listener status
      if (listener.getPassed() == false) {
         throw new Exception("failed");
      }
   } finally {
      if (conn != null) {
         conn.close();
      }
   }
}