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

The following examples show how to use javax.jms.Message#getBody() . 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
/**
 * 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 Project: tomee   File: MDBSpecTest.java    License: 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 3
Source Project: javaee8-cookbook   File: Consumer.java    License: 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 4
/**
 * 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 5
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 6
Source Project: training   File: MDB.java    License: 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 7
@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 8
@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 9
@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 10
Source Project: tomee   File: JMSConsumerImpl.java    License: 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 11
Source Project: tomee   File: JMSConsumerImpl.java    License: 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 12
/**
 * @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 13
@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 14
@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 15
@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 16
Source Project: galeb   File: ScheduleProducerTest.java    License: 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 17
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
@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 19
@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);
    }
}
 
Example 20
@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);
    }
}