Example usage for javax.jms BytesMessage reset

List of usage examples for javax.jms BytesMessage reset

Introduction

In this page you can find the example usage for javax.jms BytesMessage reset.

Prototype


void reset() throws JMSException;

Source Link

Document

Puts the message body in read-only mode and repositions the stream of bytes to the beginning.

Usage

From source file:org.apache.axis2.transport.jms.LogAspect.java

@Before("(call(void javax.jms.MessageProducer.send(javax.jms.Message)) ||"
        + " call(void javax.jms.TopicPublisher.publish(javax.jms.Message))) && args(message)")
public void beforeSend(Message message) {
    try {//from  w  w  w.  j a  v a  2 s.  c o  m
        OutputStream out = LogManager.INSTANCE.createLog("jms");
        try {
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out), false);
            pw.println("Type: " + message.getClass().getName());
            pw.println("JMS message ID: " + message.getJMSMessageID());
            pw.println("JMS correlation ID: " + message.getJMSCorrelationID());
            pw.println("JMS reply to: " + message.getJMSReplyTo());
            for (Enumeration<?> e = message.getPropertyNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                pw.print(name);
                pw.print(": ");
                pw.println(message.getStringProperty(name));
            }
            pw.println();
            pw.flush();
            if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                bytesMessage.reset();
                IOUtils.copy(new BytesMessageInputStream(bytesMessage), out);
            } else if (message instanceof TextMessage) {
                pw.print(((TextMessage) message).getText());
                pw.flush();
            }
        } finally {
            out.close();
        }
    } catch (Throwable ex) {
        log.error("Failed to dump JMS message", ex);
    }
}

From source file:org.apache.synapse.transport.jms.JMSUtils.java

public byte[] getMessageBinaryPayload(Object message) {

    if (message instanceof BytesMessage) {
        BytesMessage bytesMessage = (BytesMessage) message;

        try {/* w  ww .  jav a  2  s  .c  o  m*/
            bytesMessage.reset();

            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            for (int bytesRead = bytesMessage.readBytes(buffer); bytesRead != -1; bytesRead = bytesMessage
                    .readBytes(buffer)) {
                out.write(buffer, 0, bytesRead);
            }
            return out.toByteArray();

        } catch (JMSException e) {
            handleException("Error reading JMS binary message payload", e);
        }
    }
    return null;
}

From source file:org.mule.transport.jms.integration.JmsTransformersTestCase.java

@Test
public void testCompressedBytesMessage() throws Exception {
    RequestContext.setEvent(getTestEvent("test"));

    // use GZIP/*  www  . ja v a2  s.co  m*/
    CompressionStrategy compressor = new GZipCompression();

    // create compressible data
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (int i = 0; i < 5000; i++) {
        baos.write(i);
    }

    byte[] originalBytes = baos.toByteArray();
    byte[] compressedBytes = compressor.compressByteArray(originalBytes);
    assertTrue("Source compressedBytes should be compressed", compressor.isCompressed(compressedBytes));

    // now create a BytesMessage from the compressed byte[]
    AbstractJmsTransformer trans = new SessionEnabledObjectToJMSMessage(session);
    trans.setReturnDataType(DataTypeFactory.create(BytesMessage.class));
    initialiseObject(trans);
    Object result2 = trans.transform(compressedBytes);
    assertTrue("Transformed object should be a Bytes message", result2 instanceof BytesMessage);

    // check whether the BytesMessage contains the compressed bytes
    BytesMessage intermediate = (BytesMessage) result2;
    intermediate.reset();
    byte[] intermediateBytes = new byte[(int) (intermediate.getBodyLength())];
    int intermediateSize = intermediate.readBytes(intermediateBytes);
    assertTrue("Intermediate bytes must be compressed", compressor.isCompressed(intermediateBytes));
    assertTrue("Intermediate bytes must be equal to compressed source",
            Arrays.equals(compressedBytes, intermediateBytes));
    assertEquals("Intermediate bytes and compressed source must have same size", compressedBytes.length,
            intermediateSize);

    // now test the other way around: getting the byte[] from a manually created
    // BytesMessage
    AbstractJmsTransformer trans2 = createObject(JMSMessageToObject.class);
    trans2.setReturnDataType(DataTypeFactory.BYTE_ARRAY);
    BytesMessage bMsg = session.createBytesMessage();
    bMsg.writeBytes(compressedBytes);
    Object result = trans2.transform(bMsg);
    assertTrue("Transformed object should be a byte[]", result instanceof byte[]);
    assertTrue("Result should be compressed", compressor.isCompressed((byte[]) result));
    assertTrue("Source and result should be equal", Arrays.equals(compressedBytes, (byte[]) result));
}

From source file:org.mule.transport.jms.JmsMessageUtils.java

/**
 * @param message the message to receive the bytes from. Note this only works for
 *                TextMessge, ObjectMessage, StreamMessage and BytesMessage.
 * @param jmsSpec indicates the JMS API version, either
 *                {@link JmsConstants#JMS_SPECIFICATION_102B} or
 *                {@link JmsConstants#JMS_SPECIFICATION_11}. Any other value
 *                including <code>null</code> is treated as fallback to
 *                {@link JmsConstants#JMS_SPECIFICATION_102B}.
 * @return a byte array corresponding with the message payload
 * @throws JMSException        if the message can't be read or if the message passed is
 *                             a MapMessage
 * @throws java.io.IOException if a failure occurs while reading the stream and
 *                             converting the message data
 *///from   ww w .  j a  v a  2s . c  o  m
public static byte[] toByteArray(Message message, String jmsSpec, String encoding)
        throws JMSException, IOException {
    if (message instanceof BytesMessage) {
        BytesMessage bMsg = (BytesMessage) message;
        bMsg.reset();

        if (JmsConstants.JMS_SPECIFICATION_11.equals(jmsSpec)) {
            long bmBodyLength = bMsg.getBodyLength();
            if (bmBodyLength > Integer.MAX_VALUE) {
                throw new JMSException("Size of BytesMessage exceeds Integer.MAX_VALUE; "
                        + "please consider using JMS StreamMessage instead");
            }

            if (bmBodyLength > 0) {
                byte[] bytes = new byte[(int) bmBodyLength];
                bMsg.readBytes(bytes);
                return bytes;
            } else {
                return ArrayUtils.EMPTY_BYTE_ARRAY;
            }
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
            byte[] buffer = new byte[4096];
            int len;

            while ((len = bMsg.readBytes(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            if (baos.size() > 0) {
                return baos.toByteArray();
            } else {
                return ArrayUtils.EMPTY_BYTE_ARRAY;
            }
        }
    } else if (message instanceof StreamMessage) {
        StreamMessage sMsg = (StreamMessage) message;
        sMsg.reset();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
        byte[] buffer = new byte[4096];
        int len;

        while ((len = sMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }

        return baos.toByteArray();
    } else if (message instanceof ObjectMessage) {
        ObjectMessage oMsg = (ObjectMessage) message;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(oMsg.getObject());
        os.flush();
        os.close();
        return baos.toByteArray();
    } else if (message instanceof TextMessage) {
        TextMessage tMsg = (TextMessage) message;
        String tMsgText = tMsg.getText();

        if (null == tMsgText) {
            // Avoid creating new instances of byte arrays, even empty ones. The
            // load on this part of the code can be high.
            return ArrayUtils.EMPTY_BYTE_ARRAY;
        } else {
            return tMsgText.getBytes(encoding);
        }
    } else {
        throw new JMSException("Cannot get bytes from Map Message");
    }
}

From source file:org.mule.transport.jms.JmsMessageUtilsTestCase.java

@Test
public void testConvertingByteArrayToBytesMessage() throws JMSException {
    Session session = mock(Session.class);
    when(session.createBytesMessage()).thenReturn(new ActiveMQBytesMessage());

    byte[] bytesArray = new byte[] { 1, 2 };
    BytesMessage message = (BytesMessage) JmsMessageUtils.toMessage(bytesArray, session);

    // Makes the message readable
    message.reset();
    byte[] bytesArrayResult = new byte[(int) message.getBodyLength()];
    int length = message.readBytes(bytesArrayResult);
    assertEquals(2, length);/*from   w  ww  .  j  a v a2 s .  c o m*/
    assertEquals(bytesArray[0], bytesArrayResult[0]);
    assertEquals(bytesArray[1], bytesArrayResult[1]);
}

From source file:org.perfcake.message.sender.RequestResponseJmsSenderTest.java

@Test
public void testResponseSend() throws Exception {
    final String queueName = "queue/test";
    final String replyQueueName = "queue/test_reply";

    final JmsHelper.Wiretap wiretap = JmsHelper.wiretap(queueName, replyQueueName);
    wiretap.start();//w w  w  .java 2  s  . c om

    final Properties props = new Properties();
    props.setProperty("messagetType", "STRING");
    props.setProperty("target", queueName);
    props.setProperty("responseTarget", replyQueueName);
    props.setProperty("connectionFactory", "ConnectionFactory");
    props.setProperty("transacted", "true");
    props.setProperty("autoAck", "false");

    final RequestResponseJmsSender sender = (RequestResponseJmsSender) ObjectFactory
            .summonInstance(RequestResponseJmsSender.class.getName(), props);

    Assert.assertEquals(sender.getMessageType(), RequestResponseJmsSender.MessageType.STRING);
    Assert.assertEquals(sender.getTarget(), queueName);
    Assert.assertEquals(sender.getResponseTarget(), replyQueueName);
    Assert.assertEquals(sender.isTransacted(), true);
    Assert.assertEquals(sender.isAutoAck(), false);

    try {
        sender.init();

        // make sure the queues are empty
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queue));
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queueReply));

        // STRING
        org.perfcake.message.Message message = new org.perfcake.message.Message();
        final String payload = "Hello World!";
        message.setPayload(payload);
        sender.preSend(message, null, null);
        Serializable response = sender.send(message, null);
        sender.postSend(message);

        Assert.assertTrue(response instanceof String);
        Assert.assertEquals((String) response, payload);

        // what did the wiretap see
        Message jmsResponse = wiretap.getLastMessage();
        Assert.assertTrue(jmsResponse instanceof TextMessage);
        Assert.assertEquals(((TextMessage) jmsResponse).getText(), payload);

        // OBJECT
        sender.setMessageType(JmsSender.MessageType.OBJECT);
        message = new org.perfcake.message.Message();
        final Long payloadObject = 42L;
        message.setPayload(payloadObject);
        sender.preSend(message, null, null);
        response = sender.send(message, null);
        sender.postSend(message);

        Assert.assertTrue(response instanceof Long);
        Assert.assertEquals((Long) response, payloadObject);

        // what did the wiretap see
        jmsResponse = wiretap.getLastMessage();
        Assert.assertTrue(jmsResponse instanceof ObjectMessage);
        Assert.assertTrue(((ObjectMessage) jmsResponse).getObject() instanceof Long);
        Assert.assertEquals((Long) ((ObjectMessage) jmsResponse).getObject(), payloadObject);

        // BYTEARRAY
        sender.setMessageType(JmsSender.MessageType.BYTEARRAY);
        message = new org.perfcake.message.Message();
        message.setPayload(payload);
        sender.preSend(message, null, null);
        response = sender.send(message, null);
        sender.postSend(message);

        Assert.assertTrue(response instanceof byte[]);
        Assert.assertEquals(new String((byte[]) response, "UTF-8").trim(), payload);

        // what did the wiretap see
        jmsResponse = wiretap.getLastMessage();
        Assert.assertTrue(jmsResponse instanceof BytesMessage);
        final BytesMessage bytesMessage = (BytesMessage) jmsResponse;
        bytesMessage.reset();
        final byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
        bytesMessage.readBytes(bytes, bytes.length);
        Assert.assertEquals(new String(bytes, "UTF-8").trim(), payload);

        wiretap.stop();

        // make sure the queue is empty
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queue));
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queueReply));
    } finally {
        sender.close();
    }
}

From source file:org.skyscreamer.nevado.jms.message.NevadoBytesMessage.java

protected NevadoBytesMessage(BytesMessage message) throws JMSException {
    super(message);
    message.reset();
    for (int count = 0; count < message.getBodyLength();) {
        byte[] buffer = new byte[10240];
        int numRead = message.readBytes(buffer);
        writeBytes(buffer, 0, numRead);// www .j  a  v a  2s.co m
        count += numRead;
    }
}