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

The following examples show how to use javax.jms.Message#getJMSDestination() . 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: MappingJackson2MessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Determine a Jackson JavaType for the given JMS Message,
 * typically parsing a type id message property.
 * <p>The default implementation parses the configured type id property name
 * and consults the configured type id mapping. This can be overridden with
 * a different strategy, e.g. doing some heuristics based on message origin.
 * @param message the JMS Message to set the type id on
 * @throws JMSException if thrown by JMS methods
 * @see #setTypeIdOnMessage(Object, javax.jms.Message)
 * @see #setTypeIdPropertyName(String)
 * @see #setTypeIdMappings(java.util.Map)
 */
protected JavaType getJavaTypeForMessage(Message message) throws JMSException {
	String typeId = message.getStringProperty(this.typeIdPropertyName);
	if (typeId == null) {
		throw new MessageConversionException(
				"Could not find type id property [" + this.typeIdPropertyName + "] on message [" +
				message.getJMSMessageID() + "] from destination [" + message.getJMSDestination() + "]");
	}
	Class<?> mappedClass = this.idClassMappings.get(typeId);
	if (mappedClass != null) {
		return this.objectMapper.getTypeFactory().constructType(mappedClass);
	}
	try {
		Class<?> typeClass = ClassUtils.forName(typeId, this.beanClassLoader);
		return this.objectMapper.getTypeFactory().constructType(typeClass);
	}
	catch (Throwable ex) {
		throw new MessageConversionException("Failed to resolve type id [" + typeId + "]", ex);
	}
}
 
Example 2
Source File: MappingJackson2MessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Determine a Jackson JavaType for the given JMS Message,
 * typically parsing a type id message property.
 * <p>The default implementation parses the configured type id property name
 * and consults the configured type id mapping. This can be overridden with
 * a different strategy, e.g. doing some heuristics based on message origin.
 * @param message the JMS Message to set the type id on
 * @throws JMSException if thrown by JMS methods
 * @see #setTypeIdOnMessage(Object, javax.jms.Message)
 * @see #setTypeIdPropertyName(String)
 * @see #setTypeIdMappings(java.util.Map)
 */
protected JavaType getJavaTypeForMessage(Message message) throws JMSException {
	String typeId = message.getStringProperty(this.typeIdPropertyName);
	if (typeId == null) {
		throw new MessageConversionException(
				"Could not find type id property [" + this.typeIdPropertyName + "] on message [" +
				message.getJMSMessageID() + "] from destination [" + message.getJMSDestination() + "]");
	}
	Class<?> mappedClass = this.idClassMappings.get(typeId);
	if (mappedClass != null) {
		return this.objectMapper.getTypeFactory().constructType(mappedClass);
	}
	try {
		Class<?> typeClass = ClassUtils.forName(typeId, this.beanClassLoader);
		return this.objectMapper.getTypeFactory().constructType(typeClass);
	}
	catch (Throwable ex) {
		throw new MessageConversionException("Failed to resolve type id [" + typeId + "]", ex);
	}
}
 
Example 3
Source File: PaymentUpdateSender.java    From Spring-MVC-Blueprints with MIT License 6 votes vote down vote up
@Override
public void onMessage(final Message message) {
	
	try {
		message.acknowledge();
		message.getJMSDestination();
	        if (message instanceof TextMessage) {
	               TextMessage txtmsg = (TextMessage) message;
	               // Account Id
	               // Get the PO object here and set changes
	              
	        }
	        System.out.println(message.getClass());
	        System.out.println("Done");
	} catch (JMSException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
      
	
}
 
Example 4
Source File: GatewayTokenRevocationMessageListener.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public void onMessage(Message message) {

        try {
            if (message != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Event received in JMS Event Receiver - " + message);
                }
                Topic jmsDestination = (Topic) message.getJMSDestination();
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    if (APIConstants.TopicNames.TOPIC_TOKEN_REVOCATION.equalsIgnoreCase(jmsDestination.getTopicName())) {
                        if (map.get(APIConstants.REVOKED_TOKEN_KEY) !=
                                null) {
                            /*
                             * This message contains revoked token data
                             * revokedToken - Revoked Token which should be removed from the cache
                             * expiryTime - ExpiryTime of the token if token is JWT, otherwise expiry is set to 0
                             */
                            handleRevokedTokenMessage((String) map.get(APIConstants.REVOKED_TOKEN_KEY),
                                    (Long) map.get(APIConstants.REVOKED_TOKEN_EXPIRY_TIME));
                        }

                    }
                } else {
                    log.warn("Event dropped due to unsupported message type " + message.getClass());
                }
            } else {
                log.warn("Dropping the empty/null event received through jms receiver");
            }
        } catch (JMSException e) {
            log.error("JMSException occurred when processing the received message ", e);
        }
    }
 
Example 5
Source File: JmsTopicPublisherTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void testPublishMessageWithDeliveryOptions() throws Exception {
    Topic topic = session.createTopic(getTestName());
    TopicPublisher publisher = session.createPublisher(topic);
    Message message = session.createMessage();
    publisher.publish(message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);

    JmsOutboundMessageDispatch envelope = remotePeer.getLastReceivedMessage();
    assertNotNull(envelope);
    message = envelope.getMessage();
    Destination destination = message.getJMSDestination();
    assertEquals(topic, destination);
}
 
Example 6
Source File: AbstractJMSMessageListener.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
private static String getDestinationName(Message message) {
    try {
        Destination destination = message.getJMSDestination();
        if (destination instanceof Queue) {
            return ((Queue) destination).getQueueName();
        } else if (destination instanceof Topic) {
            return ((Topic) destination).getTopicName();
        } else {
            throw new IllegalStateException("Can't recognize destination type for " + destination.getClass());
        }
    } catch (JMSException e) {
        throw new IllegalStateException("Can't extract destination name from JMS message: " + message, e);
    }
}
 
Example 7
Source File: JmsTopicPublisherTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void testPublishMessage() throws Exception {
    Topic topic = session.createTopic(getTestName());
    TopicPublisher publisher = session.createPublisher(topic);
    Message message = session.createMessage();
    publisher.publish(message);

    JmsOutboundMessageDispatch envelope = remotePeer.getLastReceivedMessage();
    assertNotNull(envelope);
    message = envelope.getMessage();
    Destination destination = message.getJMSDestination();
    assertEquals(topic, destination);
}
 
Example 8
Source File: JmsQueueSenderTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void testSendToQueueWithDeliveryOptsWithNullOnExplicitQueueSender() throws Exception {
    Queue queue = session.createQueue(getTestName());
    QueueSender sender = session.createSender(null);
    Message message = session.createMessage();
    sender.send(queue, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);

    JmsOutboundMessageDispatch envelope = remotePeer.getLastReceivedMessage();
    assertNotNull(envelope);
    message = envelope.getMessage();
    Destination destination = message.getJMSDestination();
    assertEquals(queue, destination);
}
 
Example 9
Source File: JmsQueueSenderTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void testSendToQueueWithNullOnExplicitQueueSender() throws Exception {
    Queue queue = session.createQueue(getTestName());
    QueueSender sender = session.createSender(null);
    Message message = session.createMessage();
    sender.send(queue, message);

    JmsOutboundMessageDispatch envelope = remotePeer.getLastReceivedMessage();
    assertNotNull(envelope);
    message = envelope.getMessage();
    Destination destination = message.getJMSDestination();
    assertEquals(queue, destination);
}
 
Example 10
Source File: JMSDestinationTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void messageSentToTopicComesBackWithTheSameJMSDestination() throws Exception
{
    Topic topic = createTopic(getTestName());
    Connection connection = getConnection();
    try
    {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(topic);

        Utils.sendMessages(session, topic, 1);

        connection.start();

        Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertNotNull("Message should not be null", receivedMessage);

        Destination receivedDestination = receivedMessage.getJMSDestination();

        assertNotNull("JMSDestination should not be null", receivedDestination);
        assertTrue("Unexpected destination type", receivedDestination instanceof Topic);
        assertEquals("Unexpected destination name",
                     topic.getTopicName(),
                     ((Topic) receivedDestination).getTopicName());
    }
    finally
    {
        connection.close();
    }
}
 
Example 11
Source File: JMSDestinationTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void messageSentToQueueComesBackWithTheSameJMSDestination() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(queue);

        Utils.sendMessages(session, queue, 1);

        connection.start();

        Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertNotNull("Message should not be null", receivedMessage);

        Destination receivedDestination = receivedMessage.getJMSDestination();

        assertNotNull("JMSDestination should not be null", receivedDestination);
        assertTrue("Unexpected destination type", receivedDestination instanceof Queue);
        assertEquals("Unexpected destination name",
                     queue.getQueueName(),
                     ((Queue) receivedDestination).getQueueName());
    }
    finally
    {
        connection.close();
    }
}
 
Example 12
Source File: JMSDestinationTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testReceiveResend() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(queue);

        Utils.sendMessages(session, queue, 1);

        connection.start();

        Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertNotNull("Message should not be null", receivedMessage);

        Destination receivedDestination = receivedMessage.getJMSDestination();

        assertNotNull("JMSDestination should not be null", receivedDestination);
        assertTrue("Unexpected destination type", receivedDestination instanceof Queue);
        assertEquals("Unexpected destination name",
                     queue.getQueueName(),
                     ((Queue) receivedDestination).getQueueName());

        MessageProducer producer = session.createProducer(queue);
        producer.send(receivedMessage);

        Message message = consumer.receive(getReceiveTimeout());
        assertNotNull("Message should not be null", message);

        Destination destination = message.getJMSDestination();

        assertNotNull("JMSDestination should not be null", destination);
        assertTrue("Unexpected destination type", destination instanceof Queue);
        assertEquals("Unexpected destination name",
                     queue.getQueueName(),
                     ((Queue) destination).getQueueName());
    }
    finally
    {
        connection.close();
    }
}
 
Example 13
Source File: GatewayJMSMessageListener.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public void onMessage(Message message) {

        try {
            if (message != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Event received in JMS Event Receiver - " + message);
                }
                Topic jmsDestination = (Topic) message.getJMSDestination();
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    if (APIConstants.TopicNames.TOPIC_NOTIFICATION.equalsIgnoreCase(jmsDestination.getTopicName())) {
                        if (map.get(APIConstants.EVENT_TYPE) !=
                                null) {
                            /*
                             * This message contains notification
                             * eventType - type of the event
                             * timestamp - system time of the event published
                             * event - event data
                             */
                            handleNotificationMessage((String) map.get(APIConstants.EVENT_TYPE),
                                    (Long) map.get(APIConstants.EVENT_TIMESTAMP),
                                    (String) map.get(APIConstants.EVENT_PAYLOAD));
                        }
                    }

                } else {
                    log.warn("Event dropped due to unsupported message type " + message.getClass());
                }
            } else {
                log.warn("Dropping the empty/null event received through jms receiver");
            }
        } catch (JMSException e) {
            log.error("JMSException occurred when processing the received message ", e);
        }
    }
 
Example 14
Source File: MessageVerifier.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private static void verifyMessageHeaders(final MessageDescription messageDescription,
                                         final Message message) throws VerificationException
{
    try
    {
        for (Map.Entry<MessageDescription.MessageHeader, Serializable> entry : messageDescription.getHeaders()
                                                                                                 .entrySet())
        {
            Object actualValue;

            switch (entry.getKey())
            {
                case DESTINATION:
                    actualValue = message.getJMSDestination();
                    break;
                case DELIVERY_MODE:
                    actualValue = message.getJMSDeliveryMode();
                    break;
                case MESSAGE_ID:
                    actualValue = message.getJMSMessageID();
                    break;
                case TIMESTAMP:
                    actualValue = message.getJMSTimestamp();
                    break;
                case CORRELATION_ID:
                    if (entry.getValue() instanceof byte[])
                    {
                        actualValue = message.getJMSCorrelationIDAsBytes();
                    }
                    else
                    {
                        actualValue = message.getJMSCorrelationID();
                    }
                    break;
                case REPLY_TO:
                    actualValue = message.getJMSReplyTo();
                    break;
                case REDELIVERED:
                    actualValue = message.getJMSRedelivered();
                    break;
                case TYPE:
                    actualValue = message.getJMSType();
                    break;
                case EXPIRATION:
                    actualValue = message.getJMSExpiration();
                    break;
                case PRIORITY:
                    actualValue = message.getJMSPriority();
                    break;
                default:
                    throw new RuntimeException(String.format("unexpected message header '%s'", entry.getKey()));
            }

            verifyEquals(String.format("Unexpected message header '%s'", entry.getKey()),
                         entry.getValue(),
                         actualValue);
        }
    }
    catch (JMSException e)
    {
        throw new RuntimeException("Unexpected exception during message header verification", e);
    }
}
 
Example 15
Source File: JmsFactory.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
public static Map<String, String> createAttributeMap(final Message message) throws JMSException {
    final Map<String, String> attributes = new HashMap<>();

    final Enumeration<?> enumeration = message.getPropertyNames();
    while (enumeration.hasMoreElements()) {
        final String propName = (String) enumeration.nextElement();

        final Object value = message.getObjectProperty(propName);

        if (value == null) {
            attributes.put(ATTRIBUTE_PREFIX + propName, "");
            attributes.put(ATTRIBUTE_PREFIX + propName + ATTRIBUTE_TYPE_SUFFIX, "Unknown");
            continue;
        }

        final String valueString = value.toString();
        attributes.put(ATTRIBUTE_PREFIX + propName, valueString);

        final String propType;
        if (value instanceof String) {
            propType = PROP_TYPE_STRING;
        } else if (value instanceof Double) {
            propType = PROP_TYPE_DOUBLE;
        } else if (value instanceof Float) {
            propType = PROP_TYPE_FLOAT;
        } else if (value instanceof Long) {
            propType = PROP_TYPE_LONG;
        } else if (value instanceof Integer) {
            propType = PROP_TYPE_INTEGER;
        } else if (value instanceof Short) {
            propType = PROP_TYPE_SHORT;
        } else if (value instanceof Byte) {
            propType = PROP_TYPE_BYTE;
        } else if (value instanceof Boolean) {
            propType = PROP_TYPE_BOOLEAN;
        } else {
            propType = PROP_TYPE_OBJECT;
        }

        attributes.put(ATTRIBUTE_PREFIX + propName + ATTRIBUTE_TYPE_SUFFIX, propType);
    }

    if (message.getJMSCorrelationID() != null) {
        attributes.put(ATTRIBUTE_PREFIX + JMS_CORRELATION_ID, message.getJMSCorrelationID());
    }
    if (message.getJMSDestination() != null) {
        String destinationName;
        if (message.getJMSDestination() instanceof Queue) {
            destinationName = ((Queue) message.getJMSDestination()).getQueueName();
        } else {
            destinationName = ((Topic) message.getJMSDestination()).getTopicName();
        }
        attributes.put(ATTRIBUTE_PREFIX + JMS_DESTINATION, destinationName);
    }
    if (message.getJMSMessageID() != null) {
        attributes.put(ATTRIBUTE_PREFIX + JMS_MESSAGE_ID, message.getJMSMessageID());
    }
    if (message.getJMSReplyTo() != null) {
        attributes.put(ATTRIBUTE_PREFIX + JMS_REPLY_TO, message.getJMSReplyTo().toString());
    }
    if (message.getJMSType() != null) {
        attributes.put(ATTRIBUTE_PREFIX + JMS_TYPE, message.getJMSType());
    }

    attributes.put(ATTRIBUTE_PREFIX + JMS_DELIVERY_MODE, String.valueOf(message.getJMSDeliveryMode()));
    attributes.put(ATTRIBUTE_PREFIX + JMS_EXPIRATION, String.valueOf(message.getJMSExpiration()));
    attributes.put(ATTRIBUTE_PREFIX + JMS_PRIORITY, String.valueOf(message.getJMSPriority()));
    attributes.put(ATTRIBUTE_PREFIX + JMS_REDELIVERED, String.valueOf(message.getJMSRedelivered()));
    attributes.put(ATTRIBUTE_PREFIX + JMS_TIMESTAMP, String.valueOf(message.getJMSTimestamp()));
    return attributes;
}
 
Example 16
Source File: JmsMessageConsumerInstrumentation.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void afterReceive(@Advice.Origin Class<?> clazz,
                                @Advice.Origin("#m") String methodName,
                                @Advice.Enter @Nullable final AbstractSpan abstractSpan,
                                @Advice.Return @Nullable final Message message,
                                @Advice.Thrown final Throwable throwable) {

    //noinspection ConstantConditions
    JmsInstrumentationHelper<Destination, Message, MessageListener> helper =
        jmsInstrHelperManager.getForClassLoaderOfClass(MessageListener.class);

    Destination destination = null;
    String destinationName = null;
    boolean discard = false;
    boolean addDetails = true;
    if (message != null) {
        try {
            destination = message.getJMSDestination();
            if (helper != null) {
                destinationName = helper.extractDestinationName(message, destination);
                discard = helper.ignoreDestination(destinationName);
            }
        } catch (JMSException e) {
            logger.error("Failed to retrieve meta info from Message", e);
        }

        if (abstractSpan instanceof Transaction) {
            Transaction transaction = (Transaction) abstractSpan;
            if (discard) {
                transaction.ignoreTransaction();
            } else if (helper != null) {
                helper.makeChildOf(transaction, message);
                transaction.withType(MESSAGING_TYPE);
                helper.addMessageDetails(message, abstractSpan);
            }
        }
    } else if (abstractSpan instanceof Transaction) {
        // Do not report polling transactions if not yielding messages
        ((Transaction) abstractSpan).ignoreTransaction();
        addDetails = false;
    }

    if (abstractSpan != null) {
        try {
            if (discard) {
                abstractSpan.requestDiscarding();
            } else if (addDetails) {
                if (message != null && helper != null && destinationName != null) {
                    abstractSpan.appendToName(" from ");
                    helper.addDestinationDetails(message, destination, destinationName, abstractSpan);
                    helper.setMessageAge(message, abstractSpan);
                }
                abstractSpan.captureException(throwable);
            }
        } finally {
            abstractSpan.deactivate().end();
        }
    }

    if (!discard && tracer != null && tracer.currentTransaction() == null && helper != null
        && message != null && messagingConfiguration != null
        && messagingConfiguration.getMessagePollingTransactionStrategy() != MessagingConfiguration.Strategy.POLLING
        && !"receiveNoWait".equals(methodName)) {

        Transaction messageHandlingTransaction = helper.startJmsTransaction(message, clazz);
        if (messageHandlingTransaction != null) {
            messageHandlingTransaction.withType(MESSAGE_HANDLING)
                .withName(RECEIVE_NAME_PREFIX);

            if (destinationName != null) {
                messageHandlingTransaction.appendToName(" from ");
                helper.addDestinationDetails(message, destination, destinationName, messageHandlingTransaction);
                helper.addMessageDetails(message, messageHandlingTransaction);
                helper.setMessageAge(message, messageHandlingTransaction);
            }

            messageHandlingTransaction.activate();
        }
    }
}
 
Example 17
Source File: JmsMessageListenerInstrumentation.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
@Advice.OnMethodEnter(suppress = Throwable.class)
@Nullable
public static Transaction beforeOnMessage(@Advice.Argument(0) @Nullable final Message message,
                                          @Advice.Origin Class<?> clazz) {

    if (message == null || tracer == null || tracer.currentTransaction() != null) {
        return null;
    }

    Destination destination = null;
    String destinationName = null;
    long timestamp = 0;
    try {
        destination = message.getJMSDestination();
        timestamp = message.getJMSTimestamp();
    } catch (JMSException e) {
        logger.warn("Failed to retrieve message's destination", e);
    }

    //noinspection ConstantConditions
    JmsInstrumentationHelper<Destination, Message, MessageListener> helper =
        jmsInstrHelperManager.getForClassLoaderOfClass(MessageListener.class);
    if (helper == null) {
        return null;
    }

    if (destination != null) {
        destinationName = helper.extractDestinationName(message, destination);
        if (helper.ignoreDestination(destinationName)) {
            return null;
        }
    }

    // Create a transaction - even if running on same JVM as the sender
    Transaction transaction = helper.startJmsTransaction(message, clazz);
    if (transaction != null) {
        transaction.withType(MESSAGING_TYPE)
            .withName(RECEIVE_NAME_PREFIX);

        if (destinationName != null) {
            helper.addDestinationDetails(message, destination, destinationName, transaction.appendToName(" from "));
        }
        helper.addMessageDetails(message, transaction);
        helper.setMessageAge(message, transaction);
        transaction.activate();
    }

    return transaction;
}
 
Example 18
Source File: MessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the {@link AmqpMessageSupport#LEGACY_TO_TYPE_MSG_ANNOTATION_SYMBOL} set on a message to
 * indicate its 'to' address represents a Topic results in the JMSDestination object being a
 * Topic. Ensure the consumers destination is not used by consuming from a Queue.
 *
 * @throws Exception if an error occurs during the test.
 */
@Test(timeout = 20000)
public void testReceivedMessageFromQueueWithToLegacyTypeAnnotationForTopic() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

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

        MessageAnnotationsDescribedType msgAnnotations = new MessageAnnotationsDescribedType();
        msgAnnotations.setSymbolKeyedAnnotation(AmqpMessageSupport.LEGACY_TO_TYPE_MSG_ANNOTATION_SYMBOL.toString(), AmqpMessageSupport.LEGACY_TOPIC_ATTRIBUTE);

        PropertiesDescribedType props = new PropertiesDescribedType();
        String myTopicAddress = "myTopicAddress";
        props.setTo(myTopicAddress );
        props.setMessageId("myMessageIDString");
        DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, msgAnnotations, props, null, amqpValueNullContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

        MessageConsumer messageConsumer = session.createConsumer(queue);
        Message receivedMessage = messageConsumer.receive(3000);
        testPeer.waitForAllHandlersToComplete(3000);

        assertNotNull(receivedMessage);

        Destination dest = receivedMessage.getJMSDestination();
        assertNotNull("Expected Topic destination but got null", dest);
        assertTrue("Expected Topic instance but did not get one. Actual type was: " + dest.getClass().getName(), dest instanceof Topic);
        assertEquals(myTopicAddress, ((Topic)dest).getTopicName());

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 19
Source File: MessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
public void receivedMessageFromQueueWithoutToResultsInUseOfConsumerDestinationImpl(boolean useQueue) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

        String queueName = "myQueue";
        String topicName = "myTopic";
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Destination destination = null;
        if (useQueue) {
            destination = session.createQueue(queueName);
        } else {
            destination = session.createTopic(topicName);
        }

        PropertiesDescribedType props = new PropertiesDescribedType();
        props.setMessageId("myMessageIDString");

        DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, props, null, amqpValueNullContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

        MessageConsumer messageConsumer = session.createConsumer(destination);
        Message receivedMessage = messageConsumer.receive(3000);

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

        testPeer.waitForAllHandlersToComplete(3000);

        assertNotNull(receivedMessage);

        Destination dest = receivedMessage.getJMSDestination();
        if (useQueue) {
            assertNotNull("expected Queue instance, got null", dest);
            assertTrue("expected Queue instance. Actual type was: " + dest.getClass().getName(), dest instanceof Queue);
            assertEquals(queueName, ((Queue) dest).getQueueName());
        } else {
            assertNotNull("expected Topic instance, got null", dest);
            assertTrue("expected Topic instance. Actual type was: " + dest.getClass().getName(), dest instanceof Topic);
            assertEquals(topicName, ((Topic) dest).getTopicName());
        }
    }
}
 
Example 20
Source File: MessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doReceivedMessageOnConnectionWithBrokerDefinedPrefixPropertiesTestImpl(Class<? extends Destination> destType,
                                                                              String destPrefix,
                                                                              String destName,
                                                                              String replyName,
                                                                              String destAddress,
                                                                              String replyAddress,
                                                                              String annotationName,
                                                                              Object annotationValue,
                                                                              String replyAnnotationName,
                                                                              Object replyAnnotationValue) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // Have the test peer provide the destination prefixes as connection properties
        Map<Symbol, Object> properties = new HashMap<Symbol, Object>();
        properties.put(QUEUE_PREFIX, destPrefix);
        properties.put(TOPIC_PREFIX, destPrefix);

        Connection connection = testFixture.establishConnecton(testPeer, null, null, properties);
        connection.start();

        testPeer.expectBegin();

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

        // Create the destination
        Destination dest = null;
        if (destType == Topic.class) {
            dest= session.createTopic(destName);
        } else if (destType == Queue.class) {
            dest = session.createQueue(destName);
        } else {
            fail("non-temporary destination type set");
        }

        MessageAnnotationsDescribedType msgAnnotations = null;
        if (annotationName != null || replyAnnotationName != null) {
            msgAnnotations = new MessageAnnotationsDescribedType();
            if (annotationName != null) {
                msgAnnotations.setSymbolKeyedAnnotation(annotationName, annotationValue);
            }

            if (replyAnnotationName != null) {
                msgAnnotations.setSymbolKeyedAnnotation(replyAnnotationName, replyAnnotationValue);
            }
        }

        PropertiesDescribedType props = new PropertiesDescribedType();
        props.setTo(destAddress);
        props.setReplyTo(replyAddress);
        DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        SourceMatcher sourceMatcher = new SourceMatcher();
        sourceMatcher.withAddress(equalTo(destAddress));

        testPeer.expectReceiverAttach(notNullValue(), sourceMatcher);
        testPeer.expectLinkFlowRespondWithTransfer(null, msgAnnotations, props, null, amqpValueNullContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

        MessageConsumer messageConsumer = session.createConsumer(dest);
        Message receivedMessage = messageConsumer.receive(3000);

        testPeer.waitForAllHandlersToComplete(2000);
        assertNotNull(receivedMessage);

        Destination jmsDest = receivedMessage.getJMSDestination();
        Destination jmsReplyTo = receivedMessage.getJMSReplyTo();

        assertNotNull("Expected JMSDestination but got null", jmsDest);
        assertNotNull("Expected JMSReplyTo but got null", jmsReplyTo);

        // Verify destination/replyto names on received message
        String recievedName = null;
        String recievedReplyName = null;
        if (destType == Topic.class) {
            recievedName = ((Topic) jmsDest).getTopicName();
            recievedReplyName = ((Topic) jmsReplyTo).getTopicName();
        } else if (destType == Queue.class) {
            recievedName = ((Queue) jmsDest).getQueueName();
            recievedReplyName = ((Queue) jmsReplyTo).getQueueName();
        }

        assertEquals("Unexpected name for JMSDestination", destName, recievedName);
        assertEquals("Unexpected name for JMSReplyTo", replyName, recievedReplyName);

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}