Java Code Examples for javax.jms.BytesMessage#readBytes()

The following examples show how to use javax.jms.BytesMessage#readBytes() . 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: ScannerBuildListener.java    From repairnator with MIT License 7 votes vote down vote up
/**
 * Method implemented from MessageListener and is called 
 * each time this is done with the previous message
 *
 * @param message ActiveMQ message object containing a string message.
 */
public void onMessage(Message message) {
    String messageText = null;
    try {
        message.acknowledge();
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            messageText = textMessage.getText();
            LOGGER.info("A new slug has arrived: " + messageText);
            this.launcher.kubernetesProcess(messageText);
        } else if (message instanceof BytesMessage) {
            BytesMessage bytesMessage = (BytesMessage) message;
            byte[] data = new byte[(int) bytesMessage.getBodyLength()];
            bytesMessage.readBytes(data);
            messageText = new String(data);
            LOGGER.info("A new slug has arrived: " + messageText);
            this.launcher.kubernetesProcess(messageText);
        } 
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: TestJmsTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private List<String> getQueue() throws Exception {
  List<String> rows = new ArrayList<>();

  Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
  Destination destination = session.createQueue(DESTINATION_NAME);
  MessageConsumer consumer = session.createConsumer(destination);

  Message temp;
  while((temp = consumer.receive(100)) != null) {
    if(temp instanceof BytesMessage) {
      BytesMessage message = (BytesMessage) temp;
      byte[] payload = new byte[(int) message.getBodyLength()];
      message.readBytes(payload);
      rows.add(new String(payload) + RECORD_SEPERATOR);
    } else if(temp instanceof TextMessage) {
      rows.add(((TextMessage) temp).getText());
    } else {
      throw new Exception("Unexpected message type");
    }
  }

  return rows;
}
 
Example 3
Source File: BytesMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
protected void assertEquivalent(final Message m, final int mode, final boolean redelivered) throws JMSException {
   super.assertEquivalent(m, mode, redelivered);

   BytesMessage bm = (BytesMessage) m;

   ProxyAssertSupport.assertEquals(true, bm.readBoolean());
   ProxyAssertSupport.assertEquals((byte) 3, bm.readByte());
   byte[] bytes = new byte[3];
   bm.readBytes(bytes);
   ProxyAssertSupport.assertEquals((byte) 4, bytes[0]);
   ProxyAssertSupport.assertEquals((byte) 5, bytes[1]);
   ProxyAssertSupport.assertEquals((byte) 6, bytes[2]);
   ProxyAssertSupport.assertEquals((char) 7, bm.readChar());
   ProxyAssertSupport.assertEquals(new Double(8.0), new Double(bm.readDouble()));
   ProxyAssertSupport.assertEquals(new Float(9.0), new Float(bm.readFloat()));
   ProxyAssertSupport.assertEquals(10, bm.readInt());
   ProxyAssertSupport.assertEquals(11L, bm.readLong());
   ProxyAssertSupport.assertEquals((short) 12, bm.readShort());
   ProxyAssertSupport.assertEquals("this is an UTF String", bm.readUTF());
}
 
Example 4
Source File: MappingJackson2MessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Convert a BytesMessage to a Java Object with the specified type.
 * @param message the input message
 * @param targetJavaType the target type
 * @return the message converted to an object
 * @throws JMSException if thrown by JMS
 * @throws IOException in case of I/O errors
 */
protected Object convertFromBytesMessage(BytesMessage message, JavaType targetJavaType)
		throws JMSException, IOException {

	String encoding = this.encoding;
	if (this.encodingPropertyName != null && message.propertyExists(this.encodingPropertyName)) {
		encoding = message.getStringProperty(this.encodingPropertyName);
	}
	byte[] bytes = new byte[(int) message.getBodyLength()];
	message.readBytes(bytes);
	try {
		String body = new String(bytes, encoding);
		return this.objectMapper.readValue(body, targetJavaType);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessageConversionException("Cannot convert bytes to String", ex);
	}
}
 
Example 5
Source File: MappingJackson2MessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a BytesMessage to a Java Object with the specified type.
 * @param message the input message
 * @param targetJavaType the target type
 * @return the message converted to an object
 * @throws JMSException if thrown by JMS
 * @throws IOException in case of I/O errors
 */
protected Object convertFromBytesMessage(BytesMessage message, JavaType targetJavaType)
		throws JMSException, IOException {

	String encoding = this.encoding;
	if (this.encodingPropertyName != null && message.propertyExists(this.encodingPropertyName)) {
		encoding = message.getStringProperty(this.encodingPropertyName);
	}
	byte[] bytes = new byte[(int) message.getBodyLength()];
	message.readBytes(bytes);
	try {
		String body = new String(bytes, encoding);
		return this.objectMapper.readValue(body, targetJavaType);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessageConversionException("Cannot convert bytes to String", ex);
	}
}
 
Example 6
Source File: BDBAMQP10V0UpgradeTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoverAmqpV0Message() throws Exception
{
    Connection connection = getConnectionBuilder().setVirtualHost("test").build();
    try
    {
        connection.start();
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        Queue queue = session.createQueue("queue");
        MessageConsumer consumer = session.createConsumer(queue);

        Message message = consumer.receive(getReceiveTimeout());
        assertThat("Recovered message not received", message, is(instanceOf(BytesMessage.class)));
        BytesMessage bytesMessage = ((BytesMessage) message);

        long length = bytesMessage.getBodyLength();
        String expectedContentHash = message.getStringProperty("sha256hash");
        byte[] content = new byte[(int) length];
        bytesMessage.readBytes(content);

        assertThat("Unexpected content length",  length, is(equalTo(EXPECTED_MESSAGE_LENGTH)));
        assertThat("Message should carry expectedShaHash property", expectedContentHash, is(notNullValue()));

        String contentHash = computeContentHash(content);
        assertThat("Unexpected content hash", expectedContentHash, is(equalTo(contentHash)));
        session.commit();
    }
    finally
    {
        connection.close();
    }
}
 
Example 7
Source File: ActiveMQBytesMessage.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Foreign message constructor
 */
public ActiveMQBytesMessage(final BytesMessage foreign, final ClientSession session) throws JMSException {
   super(foreign, ActiveMQBytesMessage.TYPE, session);

   foreign.reset();

   byte[] buffer = new byte[1024];
   int n = foreign.readBytes(buffer);
   while (n != -1) {
      writeBytes(buffer, 0, n);
      n = foreign.readBytes(buffer);
   }
}
 
Example 8
Source File: ForeignBytesMessageTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException {
   super.assertEquivalent(m, mode, redelivery);

   BytesMessage byteMsg = (BytesMessage) m;

   StringBuffer sb = new StringBuffer();
   byte[] buffer = new byte[1024];
   int n = byteMsg.readBytes(buffer);
   while (n != -1) {
      sb.append(new String(buffer, 0, n));
      n = byteMsg.readBytes(buffer);
   }
   ProxyAssertSupport.assertEquals("ActiveMQ", sb.toString());
}
 
Example 9
Source File: StressTestClient.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void validateReceivedMessageContent(byte[] sentBytes,
        BytesMessage msg, boolean random, int messageSize) throws JMSException
{
    Long length = msg.getBodyLength();

    if(length != messageSize)
    {
        throw new RuntimeException("Incorrect number of bytes received");
    }

    byte[] recievedBytes = new byte[length.intValue()];
    msg.readBytes(recievedBytes);

    if(random)
    {
        if(!Arrays.equals(sentBytes, recievedBytes))
        {
            throw new RuntimeException("Incorrect value of bytes received");
        }
    }
    else
    {
        for(int r = 0 ; r < messageSize ; r++)
        {
            if(! (recievedBytes[r] == (byte) (48 + (r % 10))))
            {
                throw new RuntimeException("Incorrect value of bytes received");
            }
        }
    }
}
 
Example 10
Source File: BinaryMessageConverter.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public Object fromMessage(Message message) throws JMSException, MessageConversionException {

    Enumeration<String> names = message.getPropertyNames();
    messageProperties = new HashMap<String, String>();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        messageProperties.put(name, message.getStringProperty(name));
    }

    BytesMessage bm = (BytesMessage) message;
    byte[] transfer = new byte[(int) bm.getBodyLength()];
    bm.readBytes(transfer);
    return new String(transfer);
}
 
Example 11
Source File: MQBytesMessageConverter.java    From Thunder with Apache License 2.0 5 votes vote down vote up
@Override
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
    if (!(message instanceof BytesMessage)) {
        LOG.error("Message should be instance of BytesMessage");

        return null;
    }

    BytesMessage bytesMessage = (BytesMessage) message;
    int length = (int) bytesMessage.getBodyLength();
    byte[] bytes = new byte[length];
    bytesMessage.readBytes(bytes);

    return SerializerExecutor.deserialize(bytes);
}
 
Example 12
Source File: BaseTest.java    From a with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutBytesQueue() throws Exception {
	String cmdLine = getConnectCommand() + "-" + CMD_PUT + " \"test\" -" + CMD_TYPE + " " + TYPE_BYTES + " TEST.QUEUE";
	System.out.println("Testing cmd: " + cmdLine);
	a.run(cmdLine.split(" "));

	MessageConsumer mc = session.createConsumer(testQueue);
    BytesMessage msg = (BytesMessage)mc.receive(TEST_TIMEOUT);
    byte[] bytes = new byte[(int) msg.getBodyLength()];
    msg.readBytes(bytes);
    assertEquals("test",new String(bytes, StandardCharsets.UTF_8));

}
 
Example 13
Source File: JmsFactory.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private static byte[] getMessageBytes(BytesMessage message) throws JMSException {
    final long byteCount = message.getBodyLength();
    if (byteCount > Integer.MAX_VALUE) {
        throw new JMSException("Incoming message cannot be written to a FlowFile because its size is "
                + byteCount
                + " bytes, and the maximum size that this processor can handle is "
                + Integer.MAX_VALUE);
    }

    byte[] bytes = new byte[(int) byteCount];
    message.readBytes(bytes);

    return bytes;
}
 
Example 14
Source File: MessageUtils.java    From AuTe-Framework with Apache License 2.0 4 votes vote down vote up
public static String extractByteMessageBody(BytesMessage message) throws JMSException {
    byte[] byteData = new byte[(int) message.getBodyLength()];
    message.readBytes(byteData);
    return extractBodyFromByte(byteData);
}
 
Example 15
Source File: MessageDumpWriter.java    From a with Apache License 2.0 4 votes vote down vote up
public MessageDump toDumpMessage(Message msg) throws JMSException{
	
	MessageDump dump = new MessageDump();
	dump.JMSCorrelationID = msg.getJMSCorrelationID();
	dump.JMSMessageID = msg.getJMSMessageID();
	dump.JMSType = msg.getJMSType();
	dump.JMSDeliveryMode =  msg.getJMSDeliveryMode();
	dump.JMSExpiration = msg.getJMSExpiration();
	dump.JMSRedelivered = msg.getJMSRedelivered();
	dump.JMSTimestamp =  msg.getJMSTimestamp();
	dump.JMSPriority = msg.getJMSPriority();
	
	@SuppressWarnings("rawtypes")
	Enumeration propertyNames = msg.getPropertyNames();
	while(propertyNames.hasMoreElements()){
		String property = (String) propertyNames.nextElement();
		Object propertyValue = msg.getObjectProperty(property);
		if( propertyValue instanceof String){
			dump.stringProperties.put(property, (String)propertyValue);
		} else if ( propertyValue instanceof Integer ){
			dump.intProperties.put(property, (Integer)propertyValue);
		} else if ( propertyValue instanceof Long) {
			dump.longProperties.put(property, (Long)propertyValue);
		} else if( propertyValue instanceof Double) {
			dump.doubleProperties.put(property, (Double) propertyValue);
		} else if (propertyValue instanceof Short) {
			dump.shortProperties.put(property, (Short)propertyValue);
		} else if (propertyValue instanceof Float) {
			dump.floatProperties.put(property, (Float) propertyValue);
		} else if (propertyValue instanceof Byte) {
			dump.byteProperties.put(property, (Byte)propertyValue);
		} else if (propertyValue instanceof Boolean) {
			dump.boolProperties.put(property, (Boolean)propertyValue);
		} else if (propertyValue instanceof Serializable){
			// Object property.. if it's on Classpath and Serializable
			byte[] propBytes = SerializationUtils.serialize((Serializable) propertyValue);
			dump.objectProperties.put(property, Base64.encodeBase64String(propBytes));
		} else {
			// Corner case.
			throw new IllegalArgumentException("Property of key '"+ property +"' is not serializable. Type is: " + propertyValue.getClass().getCanonicalName());
		}
	}
	
	dump.body = "";
	dump.type = "";
	
	if (msg instanceof TextMessage) {
		dump.body = ((TextMessage)msg).getText();
		dump.type = "TextMessage";
	} else if (msg instanceof BytesMessage) {
		BytesMessage bm = (BytesMessage)msg;
		byte[] bytes = new byte[(int) bm.getBodyLength()];
		bm.readBytes(bytes);
		dump.body = Base64.encodeBase64String(bytes);
		dump.type = "BytesMessage";
	} else if (msg instanceof ObjectMessage) {
		ObjectMessage om = (ObjectMessage)msg;
		byte[] objectBytes = SerializationUtils.serialize(om.getObject());
		dump.body = Base64.encodeBase64String(objectBytes);
		dump.type = "ObjectMessage";
	}
	return dump;
}
 
Example 16
Source File: BytesMessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doReceiveBasicBytesMessageUsingDataSectionTestImpl(Symbol contentType, boolean typeAnnotation) 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(contentType);

        MessageAnnotationsDescribedType msgAnnotations = null;
        if (typeAnnotation) {
            msgAnnotations = new MessageAnnotationsDescribedType();
            msgAnnotations.setSymbolKeyedAnnotation(AmqpMessageSupport.JMS_MSG_TYPE.toString(), AmqpMessageSupport.JMS_BYTES_MESSAGE);
        }

        final byte[] expectedContent = "expectedContent".getBytes();
        DescribedType dataContent = new DataDescribedType(new Binary(expectedContent));

        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 BytesMessage);
        BytesMessage bytesMessage = (BytesMessage) receivedMessage;
        assertEquals(expectedContent.length, bytesMessage.getBodyLength());
        byte[] recievedContent = new byte[expectedContent.length];
        int readBytes = bytesMessage.readBytes(recievedContent);
        assertEquals(recievedContent.length, readBytes);
        assertTrue(Arrays.equals(expectedContent, recievedContent));

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

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 17
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testCompression() throws Exception {

   Connection cconnection = null;
   Connection connection = null;
   try {
      ActiveMQConnectionFactory cfactory = new ActiveMQConnectionFactory("tcp://" + OWHOST + ":" + OWPORT + "");
      cconnection = cfactory.createConnection();
      cconnection.start();
      Session csession = cconnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue cQueue = csession.createQueue(queueName);
      MessageConsumer consumer = csession.createConsumer(cQueue);

      ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + OWHOST + ":" + OWPORT + "?jms.useCompression=true");
      connection = factory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue queue = session.createQueue(queueName);

      MessageProducer producer = session.createProducer(queue);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);

      //text
      TextMessage textMessage = session.createTextMessage();
      textMessage.setText(testString);
      TextMessage receivedMessage = sendAndReceive(textMessage, producer, consumer);

      String receivedText = receivedMessage.getText();
      assertEquals(testString, receivedText);

      //MapMessage
      MapMessage mapMessage = session.createMapMessage();
      mapMessage.setString(testProp, propValue);
      MapMessage receivedMapMessage = sendAndReceive(mapMessage, producer, consumer);
      String value = receivedMapMessage.getString(testProp);
      assertEquals(propValue, value);

      //Object
      ObjectMessage objMessage = session.createObjectMessage();
      objMessage.setObject(testString);
      ObjectMessage receivedObjMessage = sendAndReceive(objMessage, producer, consumer);
      String receivedObj = (String) receivedObjMessage.getObject();
      assertEquals(testString, receivedObj);

      //Stream
      StreamMessage streamMessage = session.createStreamMessage();
      streamMessage.writeString(testString);
      StreamMessage receivedStreamMessage = sendAndReceive(streamMessage, producer, consumer);
      String streamValue = receivedStreamMessage.readString();
      assertEquals(testString, streamValue);

      //byte
      BytesMessage byteMessage = session.createBytesMessage();
      byte[] bytes = testString.getBytes();
      byteMessage.writeBytes(bytes);

      BytesMessage receivedByteMessage = sendAndReceive(byteMessage, producer, consumer);
      long receivedBodylength = receivedByteMessage.getBodyLength();

      assertEquals("bodylength Correct", bytes.length, receivedBodylength);

      byte[] receivedBytes = new byte[(int) receivedBodylength];
      receivedByteMessage.readBytes(receivedBytes);

      String receivedString = new String(receivedBytes);
      assertEquals(testString, receivedString);

      //Message
      Message m = session.createMessage();
      sendAndReceive(m, producer, consumer);
   } finally {
      if (cconnection != null) {
         connection.close();
      }
      if (connection != null) {
         cconnection.close();
      }
   }

}
 
Example 18
Source File: MarshallingMessageConverter.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Unmarshal the given {@link BytesMessage} into an object.
 * @param message the message
 * @param unmarshaller the unmarshaller to use
 * @return the unmarshalled object
 * @throws JMSException if thrown by JMS methods
 * @throws IOException in case of I/O errors
 * @throws XmlMappingException in case of OXM mapping errors
 * @see Unmarshaller#unmarshal(Source)
 */
protected Object unmarshalFromBytesMessage(BytesMessage message, Unmarshaller unmarshaller)
		throws JMSException, IOException, XmlMappingException {

	byte[] bytes = new byte[(int) message.getBodyLength()];
	message.readBytes(bytes);
	ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
	StreamSource source = new StreamSource(bis);
	return unmarshaller.unmarshal(source);
}
 
Example 19
Source File: JMSLargeMessageTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testSimpleLargeMessage2() throws Exception {
   conn = cf.createConnection();

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

   MessageProducer prod = session.createProducer(queue1);

   BytesMessage m = session.createBytesMessage();

   m.setObjectProperty("JMS_AMQ_InputStream", ActiveMQTestBase.createFakeLargeStream(10));

   prod.send(m);

   conn.close();

   conn = cf.createConnection();

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

   MessageConsumer cons = session.createConsumer(queue1);

   conn.start();

   BytesMessage rm = (BytesMessage) cons.receive(10000);

   byte[] data = new byte[1024];

   int numberOfBytes = rm.readBytes(data);
   Assert.assertEquals(10, numberOfBytes);
   for (int j = 0; j < numberOfBytes; j++) {
      Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), data[j]);
   }

   Assert.assertNotNull(rm);
}
 
Example 20
Source File: SimpleMessageConverter.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Extract a byte array from the given {@link BytesMessage}.
 * @param message the message to convert
 * @return the resulting byte array
 * @throws JMSException if thrown by JMS methods
 */
protected byte[] extractByteArrayFromMessage(BytesMessage message) throws JMSException {
	byte[] bytes = new byte[(int) message.getBodyLength()];
	message.readBytes(bytes);
	return bytes;
}