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

The following examples show how to use javax.jms.Message#getBody() . 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: JsonRecordBuilder.java    From kafka-connect-mq-source with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the value schema to use for the Kafka Connect SourceRecord.
 *
 * @param context            the JMS context to use for building messages
 * @param topic              the Kafka topic
 * @param messageBodyJms     whether to interpret MQ messages as JMS messages
 * @param message            the message
 *
 * @return the Kafka Connect SourceRecord's value
 *
 * @throws JMSException      Message could not be converted
 */
@Override public SchemaAndValue getValue(JMSContext context, String topic, boolean messageBodyJms, Message message) throws JMSException {
    byte[] payload;

    if (message instanceof BytesMessage) {
        payload = message.getBody(byte[].class);
    }
    else if (message instanceof TextMessage) {
        String s = message.getBody(String.class);
        payload = s.getBytes(UTF_8);
    }
    else {
        log.error("Unsupported JMS message type {}", message.getClass());
        throw new ConnectException("Unsupported JMS message type");
    }

    return converter.toConnectData(topic, payload);
}
 
Example 2
Source File: BookingQueueReceiver.java    From packt-java-ee-7-code-samples with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        final String text = message.getBody(String.class);
        logger.info("Received message with HIGH priority: " + text);
    } catch (JMSException ex) {
        logger.severe(ex.toString());
    }
}
 
Example 3
Source File: TextMessageIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testReceiveTextMessageWithContentAmqpValue() 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");
        final String expectedMessageContent = "myTextMessage";

        DescribedType amqpValueStringContent = new AmqpValueDescribedType(expectedMessageContent);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueStringContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();
        testPeer.expectClose();

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

        assertTrue(receivedMessage.isBodyAssignableTo(String.class));
        assertTrue(receivedMessage.isBodyAssignableTo(Object.class));
        assertFalse(receivedMessage.isBodyAssignableTo(Boolean.class));
        assertFalse(receivedMessage.isBodyAssignableTo(byte[].class));

        assertNotNull(receivedMessage.getBody(Object.class));
        assertNotNull(receivedMessage.getBody(String.class));
        try {
            receivedMessage.getBody(byte[].class);
            fail("Cannot read TextMessage with this type.");
        } catch (MessageFormatException mfe) {
        }

        assertNotNull(receivedMessage);
        assertTrue(receivedMessage instanceof TextMessage);
        assertEquals(expectedMessageContent, ((TextMessage) receivedMessage).getText());

        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 4
Source File: ActiveMQJMSConsumer.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T receiveBodyNoWait(Class<T> c) {
   try {
      Message message = consumer.receiveNoWait();
      context.setLastMessage(ActiveMQJMSConsumer.this, message);
      return message == null ? null : message.getBody(c);
   } catch (JMSException e) {
      throw JmsExceptionUtils.convertToRuntimeException(e);
   }
}
 
Example 5
Source File: ActiveMQJMSConsumer.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T receiveBody(Class<T> c, long timeout) {
   try {
      Message message = consumer.receive(timeout);
      context.setLastMessage(ActiveMQJMSConsumer.this, message);
      return message == null ? null : message.getBody(c);
   } catch (JMSException e) {
      throw JmsExceptionUtils.convertToRuntimeException(e);
   }
}
 
Example 6
Source File: ActiveMQJMSConsumer.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T receiveBody(Class<T> c) {
   try {
      Message message = consumer.receive();
      context.setLastMessage(ActiveMQJMSConsumer.this, message);
      return message == null ? null : message.getBody(c);
   } catch (JMSException e) {
      throw JmsExceptionUtils.convertToRuntimeException(e);
   }
}
 
Example 7
Source File: BodyIsAssignableFromTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * @param type
 * @param clazz
 * @param bool
 * @throws JMSException
 */
private void bodyAssignableFrom(final JmsMessageType type, final boolean bool, Class... clazz) throws JMSException {
   Assert.assertNotNull("clazz!=null", clazz);
   Assert.assertTrue("clazz[] not empty", clazz.length > 0);
   Object body = createBodySendAndReceive(type);
   Message msg = queueConsumer.receive(500);
   Assert.assertNotNull("must have a msg", msg);
   Assert.assertEquals(type.toString(), msg.getStringProperty("type"));
   for (Class<?> c : clazz) {
      Assert.assertEquals(msg + " " + type + " & " + c + ": " + bool, bool, msg.isBodyAssignableTo(c));
      if (bool) {
         Object receivedBody = msg.getBody(c);
         Assert.assertTrue("correct type " + c, c.isInstance(receivedBody));
         if (body.getClass().isAssignableFrom(byte[].class)) {
            Assert.assertArrayEquals(byte[].class.cast(body), (byte[]) receivedBody);
         } else {
            Assert.assertEquals("clazz=" + c + ", bodies must match.. " + body.equals(receivedBody), body, receivedBody);
         }
      } else {
         try {
            Object foo = msg.getBody(c);
            Assert.assertNull("body should be null", foo);
         } catch (MessageFormatException e) {
            // expected
         }
      }
   }
}
 
Example 8
Source File: JMSConsumerImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T receiveBodyNoWait(final Class<T> c) {
    try {
        final Message message = wrap(consumer.receiveNoWait());
        context.setLastMessage(message);
        return message == null ? null : message.getBody(c);
    } catch (JMSException e) {
        throw toRuntimeException(e);
    }
}
 
Example 9
Source File: JMSConsumerImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T receiveBody(final Class<T> c) {
    try {
        final Message message = wrap(consumer.receive());
        context.setLastMessage(message);
        return message == null ? null : message.getBody(c);
    } catch (JMSException e) {
        throw toRuntimeException(e);
    }
}
 
Example 10
Source File: MDBSpecTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(final Message message) {
    try {
        try {
            final String body = message.getBody(String.class);
            ok = "hello".equals(body);
        } catch (final JMSException e) {
            // no-op
        }
    } finally {
        latch.countDown();
    }
}
 
Example 11
Source File: BookingCompletionListener.java    From packt-java-ee-7-code-samples with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onException(Message message, Exception exception) {
    try {
        final String text = message.getBody(String.class);
        logger.info("Send failed..." + text);
    } catch (Throwable e) {
        logger.severe("Problem with message format");
    }
}
 
Example 12
Source File: BookingCompletionListener.java    From packt-java-ee-7-code-samples with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onCompletion(Message message) {
    try {
        final String text = message.getBody(String.class);
        logger.info("Send was successful: " + text);
    } catch (Throwable e) {
        logger.severe("Problem with message format");
    }
}
 
Example 13
Source File: MDB.java    From training with MIT License 5 votes vote down vote up
@Override
public void onMessage(Message message) {
	try {
		// In JMS 1.1:
		// ObjectMessage objectMessage = (ObjectMessage)message;
		// BusinessObject payload = (BusinessObject)objectMessage.getObject();
		MyJavaMessage payload = message.getBody(MyJavaMessage.class);
		context.createProducer().send(responseQueue, new MyJavaMessage("MDB:Processed " + payload));
	} catch (JMSException e) {
		System.err.println("Error while fetching message payload: " + e.getMessage());
	}
}
 
Example 14
Source File: ContractVerifierJmsConfiguration.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private Object getPayload(Message message) throws JMSException {
	if (message == null) {
		return null;
	}
	else if (message instanceof TextMessage) {
		return ((TextMessage) message).getText();
	}
	else if (message instanceof StreamMessage) {
		return ((StreamMessage) message).readObject();
	}
	else if (message instanceof ObjectMessage) {
		return ((ObjectMessage) message).getObject();
	}
	return message.getBody(Object.class);
}
 
Example 15
Source File: DefaultRecordBuilder.java    From kafka-connect-mq-source with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the value schema to use for the Kafka Connect SourceRecord.
 *
 * @param context            the JMS context to use for building messages
 * @param topic              the Kafka topic
 * @param messageBodyJms     whether to interpret MQ messages as JMS messages
 * @param message            the message
 *
 * @return the Kafka Connect SourceRecord's value
 *
 * @throws JMSException      Message could not be converted
 */
@Override public SchemaAndValue getValue(JMSContext context, String topic, boolean messageBodyJms, Message message) throws JMSException {
    Schema valueSchema = null;
    Object value = null;

    // Interpreting the body as a JMS message type, we can accept BytesMessage and TextMessage only.
    // We do not know the schema so do not specify one.
    if (messageBodyJms) {
        if (message instanceof BytesMessage) {
            log.debug("Bytes message with no schema");
            value = message.getBody(byte[].class);
        }
        else if (message instanceof TextMessage) {
            log.debug("Text message with no schema");
            value = message.getBody(String.class);
        }
        else {
            log.error("Unsupported JMS message type {}", message.getClass());
            throw new ConnectException("Unsupported JMS message type");
        }
    }
    else {
        // Not interpreting the body as a JMS message type, all messages come through as BytesMessage.
        // In this case, we specify the value schema as OPTIONAL_BYTES.
        log.debug("Bytes message with OPTIONAL_BYTES schema");
        valueSchema = Schema.OPTIONAL_BYTES_SCHEMA;
        value = message.getBody(byte[].class);
    }

    return new SchemaAndValue(valueSchema, value);
}
 
Example 16
Source File: Consumer.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message msg) {
    try {
        User user = msg.getBody(User.class);
        System.out.println("User: " + user);
    } catch (JMSException ex) {
        System.err.println(ex.getMessage());
    }
}
 
Example 17
Source File: TextMessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doReceiveTextMessageUsingDataSectionTestImpl(String contentType, byte[] sentBytes, String expectedString)
                                                                 throws JMSException, InterruptedException, Exception, IOException {
    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");

        PropertiesDescribedType properties = new PropertiesDescribedType();
        properties.setContentType(Symbol.valueOf(contentType));

        DescribedType dataContent = new DataDescribedType(new Binary(sentBytes));

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, properties, null, dataContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();
        testPeer.expectClose();

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

        assertNotNull(receivedMessage);
        assertTrue(receivedMessage instanceof TextMessage);
        String text = ((TextMessage) receivedMessage).getText();

        assertEquals(expectedString, text);

        assertTrue(receivedMessage.isBodyAssignableTo(String.class));
        assertTrue(receivedMessage.isBodyAssignableTo(Object.class));
        assertFalse(receivedMessage.isBodyAssignableTo(Boolean.class));
        assertFalse(receivedMessage.isBodyAssignableTo(byte[].class));

        assertNotNull(receivedMessage.getBody(Object.class));
        assertNotNull(receivedMessage.getBody(String.class));
        try {
            receivedMessage.getBody(byte[].class);
            fail("Cannot read TextMessage with this type.");
        } catch (MessageFormatException mfe) {
        }

        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 18
Source File: ScheduleProducerTest.java    From galeb with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldSendTargetToQueue() throws JMSException {
    //Arrange
    Environment environment = new Environment();
    environment.setId(1L);
    environment.setName("env1");
    List<Environment> environments = new ArrayList<>();
    environments.add(environment);
    when(environmentRepository.findAll()).thenReturn(environments);

    Pool pool = new Pool();
    pool.setId(1L);
    pool.setName("pool");
    Target target = new Target();
    target.setName("http://127.0.0.1:8080");
    target.setId(1L);
    target.setLastModifiedAt(new Date());
    target.setPool(pool);
    List<Target> targets = new ArrayList<>();
    targets.add(target);
    Pageable pageable = new PageRequest(0, 100);
    Page<Target> page = new PageImpl<Target>(targets, pageable, 1);
    when(targetRepository.findByEnvironmentName("env1", pageable)).thenReturn(page);

    String sourceName = "xxx";
    String envId = String.valueOf(environment.getId());

    Set<HealthSchema.Source> sources = Collections.singleton(new HealthSchema.Source(sourceName, Collections.emptySet()));
    Set<HealthSchema.Env> envs = Collections.singleton(new HealthSchema.Env(envId, sources));
    when(healthService.get(anyString())).thenReturn(envs);

    //Action
    scheduledProducer.sendToTargetsToQueue();
    jmsTemplate.setReceiveTimeout(5000);
    Message message = jmsTemplate.receive(SystemEnv.QUEUE_NAME.getValue() + "_" + envId + "_" + sourceName);

    //Assert
    Assert.assertTrue(message.isBodyAssignableTo(Target.class));
    Target t = message.getBody(Target.class);
    Assert.assertTrue(t.getName().equals("http://127.0.0.1:8080"));

}
 
Example 19
Source File: ObjectMessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testReceiveBasicObjectMessageWithSerializedContent() 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");

        PropertiesDescribedType properties = new PropertiesDescribedType();
        properties.setContentType(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE);

        String expectedContent = "expectedContent";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(expectedContent);
        oos.flush();
        oos.close();
        byte[] bytes = baos.toByteArray();

        MessageAnnotationsDescribedType msgAnnotations = new MessageAnnotationsDescribedType();
        msgAnnotations.setSymbolKeyedAnnotation(AmqpMessageSupport.JMS_MSG_TYPE.toString(), AmqpMessageSupport.JMS_OBJECT_MESSAGE);

        DescribedType dataContent = new DataDescribedType(new Binary(bytes));

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, msgAnnotations, properties, null, dataContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();
        testPeer.expectClose();

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

        assertNotNull(receivedMessage);
        assertTrue(receivedMessage instanceof ObjectMessage);
        ObjectMessage objectMessage = (ObjectMessage)receivedMessage;

        Object object = objectMessage.getObject();
        assertNotNull("Expected object but got null", object);
        assertEquals("Message body object was not as expected", expectedContent, object);

        assertTrue(receivedMessage.isBodyAssignableTo(String.class));
        assertTrue(receivedMessage.isBodyAssignableTo(Serializable.class));
        assertTrue(receivedMessage.isBodyAssignableTo(Object.class));
        assertFalse(receivedMessage.isBodyAssignableTo(Boolean.class));
        assertFalse(receivedMessage.isBodyAssignableTo(byte[].class));

        assertNotNull(receivedMessage.getBody(Object.class));
        assertNotNull(receivedMessage.getBody(Serializable.class));
        assertNotNull(receivedMessage.getBody(String.class));
        try {
            receivedMessage.getBody(byte[].class);
            fail("Cannot read TextMessage with this type.");
        } catch (MessageFormatException mfe) {
        }

        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 20
Source File: ObjectMessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testReceiveAndThenResendBasicObjectMessageWithSerializedContent() 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.JMS_MSG_TYPE.toString(), AmqpMessageSupport.JMS_OBJECT_MESSAGE);
        PropertiesDescribedType properties = new PropertiesDescribedType();
        properties.setContentType(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE);

        String expectedContent = "expectedContent";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(expectedContent);
        oos.flush();
        oos.close();
        byte[] bytes = baos.toByteArray();

        DescribedType dataContent = new DataDescribedType(new Binary(bytes));

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, msgAnnotations, properties, null, dataContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

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

        assertNotNull(receivedMessage);
        assertTrue(receivedMessage instanceof ObjectMessage);

        testPeer.expectSenderAttach();
        MessageProducer producer = session.createProducer(queue);

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        msgAnnotationsMatcher.withEntry(AmqpMessageSupport.JMS_MSG_TYPE, equalTo(AmqpMessageSupport.JMS_OBJECT_MESSAGE));
        MessagePropertiesSectionMatcher propertiesMatcher = new MessagePropertiesSectionMatcher(true);
        propertiesMatcher.withContentType(equalTo(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE));
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propertiesMatcher);
        messageMatcher.setMessageContentMatcher(new EncodedDataMatcher(new Binary(bytes)));

        testPeer.expectTransfer(messageMatcher);
        testPeer.expectClose();

        producer.send(receivedMessage);

        assertTrue(receivedMessage.isBodyAssignableTo(String.class));
        assertTrue(receivedMessage.isBodyAssignableTo(Serializable.class));
        assertTrue(receivedMessage.isBodyAssignableTo(Object.class));
        assertFalse(receivedMessage.isBodyAssignableTo(Boolean.class));
        assertFalse(receivedMessage.isBodyAssignableTo(byte[].class));

        assertNotNull(receivedMessage.getBody(Object.class));
        assertNotNull(receivedMessage.getBody(Serializable.class));
        assertNotNull(receivedMessage.getBody(String.class));
        try {
            receivedMessage.getBody(byte[].class);
            fail("Cannot read TextMessage with this type.");
        } catch (MessageFormatException mfe) {
        }

        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}