Example usage for javax.jms BytesMessage readBytes

List of usage examples for javax.jms BytesMessage readBytes

Introduction

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

Prototype


int readBytes(byte[] value) throws JMSException;

Source Link

Document

Reads a byte array from the bytes message stream.

Usage

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

public byte[] getMessageBinaryPayload(Object message) {

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

        try {//from  w w  w .j  a  v  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.exist.replication.jms.obsolete.FileSystemListener.java

private eXistMessage convertMessage(BytesMessage bm) {
    eXistMessage em = new eXistMessage();

    try {/*  ww w .  j  a  v a  2  s  .  c o  m*/
        Enumeration e = bm.getPropertyNames();
        while (e.hasMoreElements()) {
            Object next = e.nextElement();
            if (next instanceof String) {
                em.getMetadata().put((String) next, bm.getObjectProperty((String) next));
            }
        }

        String value = bm.getStringProperty(eXistMessage.EXIST_RESOURCE_TYPE);
        eXistMessage.ResourceType resourceType = eXistMessage.ResourceType.valueOf(value);
        em.setResourceType(resourceType);

        value = bm.getStringProperty(eXistMessage.EXIST_RESOURCE_OPERATION);
        eXistMessage.ResourceOperation changeType = eXistMessage.ResourceOperation.valueOf(value);
        em.setResourceOperation(changeType);

        value = bm.getStringProperty(eXistMessage.EXIST_SOURCE_PATH);
        em.setResourcePath(value);

        value = bm.getStringProperty(eXistMessage.EXIST_DESTINATION_PATH);
        em.setDestinationPath(value);

        long size = bm.getBodyLength();
        LOG.debug("actual length=" + size);

        // This is potentially memory intensive
        byte[] payload = new byte[(int) size];
        bm.readBytes(payload);
        em.setPayload(payload);

    } catch (JMSException ex) {
        LOG.error(ex);
    }

    return em;

}

From source file:org.jboss.activemq.clients.JMSConsumer.java

public static void main(String args[]) {
    Connection connection = null;

    try {//  w  ww.  j  av  a  2s .c o  m

        Options options = new Options();
        options.addOption("h", "help", false, "help:");
        options.addOption("url", true, "url for the broker to connect to");
        options.addOption("u", "username", true, "User name for connection");
        options.addOption("p", "password", true, "password for connection");
        options.addOption("d", "destination", true, "destination to send to");
        options.addOption("n", "number", true, "number of messages to send");
        options.addOption("delay", true, "delay between each send");

        CommandLineParser parser = new BasicParser();
        CommandLine commandLine = parser.parse(options, args);

        if (commandLine.hasOption("h")) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("OptionsTip", options);
            System.exit(0);
        }

        String url = commandLine.hasOption("host") ? commandLine.getOptionValue("host") : URL;

        String userName = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "admin";
        String password = commandLine.hasOption("p") ? commandLine.getOptionValue("p") : "admin";
        String destinationName = commandLine.hasOption("d") ? commandLine.getOptionValue("d")
                : DESTINATION_NAME;
        int numberOfMessages = commandLine.hasOption("n") ? Integer.parseInt(commandLine.getOptionValue("n"))
                : NUM_MESSAGES_TO_RECEIVE;
        ;

        ConnectionFactory factory = new ActiveMQConnectionFactory(userName, password, url);

        connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(destinationName);

        MessageConsumer consumer = session.createConsumer(topic);

        LOG.info("Start consuming " + numberOfMessages + " messages from " + topic.toString());

        for (int i = 0; i < numberOfMessages; i++) {
            Message message = consumer.receive();
            if (message != null) {
                if (message instanceof BytesMessage) {
                    BytesMessage bytesMessage = (BytesMessage) message;
                    int len = (int) bytesMessage.getBodyLength();
                    byte[] data = new byte[len];
                    bytesMessage.readBytes(data);
                    String value = new String(data);

                    LOG.info("Got " + value);
                } else {
                    LOG.info("Got a message " + message);
                }
            }
        }

        consumer.close();
        session.close();
    } catch (Throwable t) {
        LOG.error("Error receiving message", t);
    } finally {

        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOG.error("Error closing connection", e);
            }
        }
    }
}

From source file:org.jbpm.process.workitem.jms.JMSSignalReceiver.java

protected Object readData(BytesMessage message, ClassLoader cl) throws JMSException, Exception {
    Object data = null;/*ww  w .ja va2 s  .c  o  m*/
    if (message.getBodyLength() > 0) {
        byte[] reqData = new byte[(int) message.getBodyLength()];

        message.readBytes(reqData);
        if (reqData != null) {
            ObjectInputStream in = null;
            try {
                in = new ClassLoaderObjectInputStream(cl, new ByteArrayInputStream(reqData));
                data = in.readObject();
            } catch (IOException e) {
                logger.warn("Exception while serializing context data", e);

            } finally {
                if (in != null) {
                    in.close();
                }
            }
        }
    }
    return data;
}

From source file:org.mot.core.simulation.listener.SimulationMessageListener.java

@SuppressWarnings("unchecked")
@Override/* www  . j  a  v  a  2  s  . c om*/
public void onMessage(Message msg) {
    // TODO Auto-generated method stub

    BytesMessage message = (BytesMessage) msg;

    // Read in properties from file
    Configuration simulationProperties;

    byte[] bytes;
    try {
        PropertiesFactory pf = PropertiesFactory.getInstance();
        simulationProperties = new PropertiesConfiguration(pf.getConfigDir() + "/simulation.properties");
        final Double minProfit = simulationProperties.getDouble("simulation.default.db.requireMinProfit", 2.0);
        final Double txnpct = simulationProperties.getDouble("simulation.order.txncost.pct", 0.0024);

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

        SimulationRequest sr = SimulationRequest.deserialize(bytes);
        sr.setMinProfit(minProfit);
        sr.setTxnPct(txnpct);

        String className = sr.getClassName();

        Class<?> c;
        try {
            c = Class.forName(className);
            Object inst = c.newInstance();

            // Make sure the startup method is called for initialization...
            //Method m1= c.getDeclaredMethod("startup", String.class, String.class, LoadValue[].class, Boolean.class, Integer.class );
            //m1.invoke(inst, sr.getClassName(), sr.getSymbol(), lvc.convertStringToValues(sr.getLoadValues()), true, sr.getQuantity());

            // Call the backtest Processing class...
            Method m = c.getDeclaredMethod("processSimulationRequests", SimulationRequest.class);
            Object ret = m.invoke(inst, sr);
            ArrayList<SimulationResponse> simulationResponses = (ArrayList<SimulationResponse>) ret;

            // Iterate over the expressions
            Iterator<SimulationResponse> it = simulationResponses.iterator();
            while (it.hasNext()) {
                SimulationResponse u = it.next();
                this.writeToDB(u);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        msg.acknowledge();

    } catch (JMSException | ClassNotFoundException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {

    }

}

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

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

    // use GZIP//from  www . j a v a 2  s. c  o  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   w  w  w.j  av a2 s .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 testByteMessageNullContentInJmsVersion_1_0_1() throws Exception {
    BytesMessage mockMessage1 = mock(BytesMessage.class);
    when(mockMessage1.readBytes((byte[]) anyObject())).thenReturn(-1);

    byte[] result1 = JmsMessageUtils.toByteArray(mockMessage1, JmsConstants.JMS_SPECIFICATION_102B, ENCODING);
    assertNotNull(result1);//from w  w w . jav  a2s.  c o m
    assertEquals("Should return an empty byte array.", 0, result1.length);
    verify(mockMessage1).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 ww w  . jav  a2s . c  o  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   www .j  a  v  a  2  s .  co m*/
 *          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();
}