Example usage for javax.jms BytesMessage getBodyLength

List of usage examples for javax.jms BytesMessage getBodyLength

Introduction

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

Prototype


long getBodyLength() throws JMSException;

Source Link

Document

Gets the number of bytes of the message body when the message is in read-only mode.

Usage

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

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

    // use GZIP/*from   ww w  . ja va  2s  .com*/
    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
 *//*ww w.  j  av a 2s.c  om*/
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 testByteMessageNullContentInJmsVersion_1_1() throws Exception {
    BytesMessage mockMessage2 = mock(BytesMessage.class);
    when(mockMessage2.getBodyLength()).thenReturn(Long.valueOf(0));

    byte[] result2 = JmsMessageUtils.toByteArray(mockMessage2, JmsConstants.JMS_SPECIFICATION_11, ENCODING);
    assertNotNull(result2);/* ww w .  ja v a 2  s.  co m*/
    assertEquals("Should return an empty byte array.", 0, result2.length);
    verify(mockMessage2).reset();
}

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();/*from  w  w  w.ja  v  a2  s . co m*/
    byte[] bytesArrayResult = new byte[(int) message.getBodyLength()];
    int length = message.readBytes(bytesArrayResult);
    assertEquals(2, length);
    assertEquals(bytesArray[0], bytesArrayResult[0]);
    assertEquals(bytesArray[1], bytesArrayResult[1]);
}

From source file:org.opencastproject.message.broker.impl.MessageReceiverImpl.java

/**
 * @param destinationId//from w w  w .j  ava2s  .c om
 *          The id of the destination queue to listen to.
 * @param type
 *          The type of the destination either queue or topic.
 * @return Receive a JMS ByteMessage from an ActiveMQ Message Broker.
 */
protected byte[] getByteArray(String destinationId, DestinationType type) {
    Option<byte[]> receivedBytes = Option.<byte[]>none();
    do {
        // Wait for a message
        Option<Message> message = waitForMessage(destinationId, type);
        try {
            if (isValidByteMessage(message)) {
                BytesMessage bytesMessage = (BytesMessage) message.get();
                byte[] payload;
                payload = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(payload);
                receivedBytes = Option.option(payload);
            } else {
                logger.debug("Skipping invalid message:" + message);
                receivedBytes = Option.<byte[]>none();
            }
        } catch (JMSException e) {
            logger.error("Unable to get message {} because {}", message, ExceptionUtils.getStackTrace(e));
            receivedBytes = Option.<byte[]>none();
        }
    } while (receivedBytes.isNone());
    return receivedBytes.get();
}

From source file:org.oxymores.chronix.engine.Runner.java

@Override
public void onMessage(Message msg) {
    if (msg instanceof ObjectMessage) {
        ObjectMessage omsg = (ObjectMessage) msg;
        try {// w  w  w  .j  a v  a 2  s  .  c o  m
            Object o = omsg.getObject();
            if (o instanceof PipelineJob) {
                PipelineJob pj = (PipelineJob) o;
                log.debug(String.format("Job execution %s request was received", pj.getId()));
                recvPJ(pj);
                jmsCommit();
                return;
            } else if (o instanceof RunResult) {
                RunResult rr = (RunResult) o;
                recvRR(rr);
                jmsCommit();
                return;
            } else {
                log.warn(
                        "An object was received by the Runner that was not of a valid type. It will be ignored.");
                jmsCommit();
                return;
            }

        } catch (JMSException e) {
            log.error(
                    "An error occurred during job reception. Message will stay in queue and will be analysed later",
                    e);
            jmsRollback();
            return;
        }
    } else if (msg instanceof TextMessage) {
        TextMessage tmsg = (TextMessage) msg;
        try {
            recvTextMessage(tmsg);
            jmsCommit();
        } catch (JMSException e) {
            log.error("An error occurred during parameter resolution", e);
            jmsRollback();
            return;
        }
    } else if (msg instanceof BytesMessage) {
        // log file reception
        BytesMessage bmsg = (BytesMessage) msg;
        String fn = "dump.txt";
        try {
            fn = bmsg.getStringProperty("FileName");
        } catch (JMSException e) {
            log.error(
                    "An log file was sent without a FileName property. It will be lost. Will not impact the scheduler itself.",
                    e);
            jmsCommit();
        }

        try {
            int l = (int) bmsg.getBodyLength();
            byte[] r = new byte[l];
            bmsg.readBytes(r);
            IOUtils.write(r, new FileOutputStream(new File(FilenameUtils.concat(this.logDbPath, fn))));
            jmsCommit();
        } catch (Exception e) {
            log.error(
                    "An error has occured while receiving a log file. It will be lost. Will not impact the scheduler itself.",
                    e);
            jmsCommit();
        }
    }
}

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();/*from ww  w .j  a  v  a  2 s  .  co m*/

    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();/* w w  w .  ja  v a2s.  c  o m*/
    for (int count = 0; count < message.getBodyLength();) {
        byte[] buffer = new byte[10240];
        int numRead = message.readBytes(buffer);
        writeBytes(buffer, 0, numRead);
        count += numRead;
    }
}

From source file:org.springframework.jms.support.converter.obm.MarshallingMessageConverter.java

protected Object unmarshalFromBytesMessage(Class clzz, BytesMessage message,
        org.springframework.obm.Unmarshaller unmarshaller)
        throws JMSException, IOException, XmlMappingException {
    try {/*from  ww  w  . j  ava2 s  . c  o  m*/
        byte[] bytes = new byte[(int) message.getBodyLength()];
        message.readBytes(bytes);
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Object result = unmarshaller.unmarshal(clzz, bis);
        Assert.notNull(result, "the result from the queue is null");
        if (log.isDebugEnabled()) {
            log.debug("received: " + result);
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.carbon.event.input.adapter.jms.internal.util.JMSMessageListener.java

public void onMessage(Message message) {
    try {//from   w w w .jav  a 2s. c om
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        if (message != null) {

            if (log.isDebugEnabled()) {
                log.debug("Event received in JMS Event Adaptor - " + message);
            }

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                // Send the text of the message. Conversion to any type (XML,JSON) should
                // not happen here since this message will be built later.
                try {
                    String msgText = textMessage.getText();
                    eventAdaptorListener.onEvent(msgText);
                } catch (JMSException e) {
                    if (log.isErrorEnabled()) {
                        log.error("Failed to get text from " + textMessage, e);
                    }
                } catch (InputEventAdapterRuntimeException e) {
                    if (log.isErrorEnabled()) {
                        log.error(e);
                    }
                }
            } else if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                Map event = new HashMap();
                try {
                    Enumeration names = mapMessage.getMapNames();
                    Object name;
                    while (names.hasMoreElements()) {
                        name = names.nextElement();
                        event.put(name, mapMessage.getObject((String) name));
                    }
                    eventAdaptorListener.onEvent(event);

                } catch (JMSException e) {
                    log.error("Can not read the map message ", e);
                } catch (InputEventAdapterRuntimeException e) {
                    log.error("Can not send the message to broker ", e);
                }
            } else if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                byte[] bytes;
                bytes = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(bytes);
                eventAdaptorListener.onEvent(new String(bytes, "UTF-8"));
            } else {
                log.warn("Event dropped due to unsupported message type");
            }
        } else {
            log.warn("Dropping the empty/null event received through jms adaptor");
        }
    } catch (JMSException e) {
        log.error(e);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (Throwable t) {
        log.error(t);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}