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:com.bitsofproof.supernode.core.ImplementBCSAPI.java

private void addMatchScanListener() throws JMSException {
    addMessageListener("matchRequest", new MessageListener() {
        @Override// w  w w.jav  a  2 s  . c o m
        public void onMessage(Message msg) {
            BytesMessage o = (BytesMessage) msg;
            byte[] body;
            try {
                body = new byte[(int) o.getBodyLength()];
                o.readBytes(body);
                BCSAPIMessage.ExactMatchRequest request = BCSAPIMessage.ExactMatchRequest.parseFrom(body);
                final List<byte[]> match = new ArrayList<byte[]>();
                for (ByteString bs : request.getMatchList()) {
                    match.add(bs.toByteArray());
                }
                final UpdateMode mode = UpdateMode.values()[request.getMode()];
                final MessageProducer producer = session.createProducer(msg.getJMSReplyTo());
                final long after = request.hasAfter() ? request.getAfter() : 0;
                requestProcessor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            store.filterTransactions(match, mode, after, new TransactionProcessor() {
                                @Override
                                public void process(Tx tx) {
                                    if (tx != null) {
                                        Transaction transaction = toBCSAPITransaction(tx);
                                        BytesMessage m;
                                        try {
                                            m = session.createBytesMessage();
                                            m.writeBytes(transaction.toProtobuf().toByteArray());
                                            producer.send(m);
                                        } catch (JMSException e) {
                                        }
                                    } else {
                                        try {
                                            BytesMessage m = session.createBytesMessage();
                                            producer.send(m); // indicate EOF
                                            producer.close();
                                        } catch (JMSException e) {
                                        }
                                    }
                                }
                            });
                        } catch (ValidationException e) {
                            log.error("Error while scanning", e);
                        }
                    }
                });
            } catch (JMSException e) {
                log.error("invalid filter request", e);
            } catch (InvalidProtocolBufferException e) {
                log.error("invalid filter request", e);
            }
        }
    });
}

From source file:com.legstar.mq.client.AbstractCicsMQ.java

/**
 * A response is serialized as a header message part followed by data
 * message parts. This method creates a response message for the request.
 * <p/>//from   w w  w  .  j  a v a  2 s . com
 * The reply is correlated to the request by means of the JMS message ID
 * that was generated when we sent the request. That ID was attached to the
 * request object.
 * 
 * @param request the request being serviced
 * @throws RequestException if receive fails
 */
public void recvResponse(final LegStarRequest request) throws RequestException {

    MessageConsumer consumer = null;
    try {
        String selector = "JMSCorrelationID='" + new String(request.getAttachment()) + "'";
        if (_log.isDebugEnabled()) {
            _log.debug("Receiving response for Request:" + request.getID() + " on Connection:" + _connectionID
                    + ". Selector: " + selector);
        }

        consumer = getJmsQueueSession().createConsumer(getJmsReplyQueue(), selector);
        Message jmsMessage = consumer.receive(getCicsMQEndpoint().getReceiveTimeout());
        if (!(jmsMessage instanceof BytesMessage)) {
            throw new RequestException("Message received does not contain bytes");
        }
        BytesMessage message = (BytesMessage) jmsMessage;
        message.reset();

        /* Check that data length makes sense */
        long dataLength = message.getBodyLength();
        if (dataLength > Integer.MAX_VALUE) {
            throw new RequestException("Size of BytesMessage exceeds Integer.MAX_VALUE");
        }

        request.setResponseMessage(createReplyMessage(message, (int) dataLength));

        _lastUsedTime = System.currentTimeMillis();
        if (_log.isDebugEnabled()) {
            _log.debug("Received response for Request:" + request.getID() + " on Connection:" + _connectionID
                    + ". Selector: " + selector);
        }
    } catch (JMSException e) {
        throw new RequestException(e);
    } catch (HostReceiveException e) {
        throw new RequestException(e);
    } finally {
        if (consumer != null) {
            try {
                consumer.close();
            } catch (JMSException e) {
                _log.error(e);
            }
        }
    }

}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

private boolean verify(Message message, MsgCheck check) {
    String sVal = "";

    if (check.getField().equals(MESSAGECONTENTFIELD)) {
        try {//from  w w  w  . ja v  a 2s  .  c o  m
            if (message instanceof TextMessage) {
                sVal = ((TextMessage) message).getText();
            } else if (message instanceof MapMessage) {
                MapMessage mm = (MapMessage) message;
                ObjectMapper mapper = new ObjectMapper();
                ObjectNode root = mapper.createObjectNode();

                @SuppressWarnings("unchecked")
                Enumeration<String> e = mm.getMapNames();
                while (e.hasMoreElements()) {
                    String field = e.nextElement();
                    root.set(field, mapper.convertValue(mm.getObject(field), JsonNode.class));
                }
                sVal = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
            } else if (message instanceof BytesMessage) {
                BytesMessage bm = (BytesMessage) message;
                bm.reset();
                byte[] bytes = new byte[(int) bm.getBodyLength()];
                if (bm.readBytes(bytes) == bm.getBodyLength()) {
                    sVal = new String(bytes);
                }
            }
        } catch (JMSException e) {
            return false;
        } catch (JsonProcessingException e) {
            return false;
        }
    } else {
        Enumeration<String> propNames = null;
        try {
            propNames = message.getPropertyNames();
            while (propNames.hasMoreElements()) {
                String propertyName = propNames.nextElement();
                if (propertyName.equals(check.getField())) {
                    if (message.getObjectProperty(propertyName) != null) {
                        sVal = message.getObjectProperty(propertyName).toString();
                        break;
                    }
                }
            }
        } catch (JMSException e) {
            return false;
        }
    }

    String eVal = "";
    if (check.getExpectedValue() != null) {
        eVal = check.getExpectedValue();
    }
    if (Pattern.compile(eVal).matcher(sVal).find()) {
        return true;
    }
    return false;
}

From source file:org.apache.camel.component.jms.JmsBinding.java

protected byte[] createByteArrayFromBytesMessage(BytesMessage message) throws JMSException {
    if (message.getBodyLength() > Integer.MAX_VALUE) {
        LOG.warn("Length of BytesMessage is too long: " + message.getBodyLength());
        return null;
    }//from  ww w  .j  ava  2s.  com
    byte[] result = new byte[(int) message.getBodyLength()];
    message.readBytes(result);
    return result;
}

From source file:org.apache.jmeter.protocol.jms.sampler.SubscriberSampler.java

private void extractContent(StringBuilder buffer, StringBuilder propBuffer, Message msg, boolean isLast) {
    if (msg != null) {
        try {//from w  w w  . jav  a2 s.  com
            if (msg instanceof TextMessage) {
                buffer.append(((TextMessage) msg).getText());
            } else if (msg instanceof ObjectMessage) {
                ObjectMessage objectMessage = (ObjectMessage) msg;
                if (objectMessage.getObject() != null) {
                    buffer.append(objectMessage.getObject().getClass());
                } else {
                    buffer.append("object is null");
                }
            } else if (msg instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) msg;
                buffer.append(bytesMessage.getBodyLength() + " bytes received in BytesMessage");
            } else if (msg instanceof MapMessage) {
                MapMessage mapm = (MapMessage) msg;
                @SuppressWarnings("unchecked") // MapNames are Strings
                Enumeration<String> enumb = mapm.getMapNames();
                while (enumb.hasMoreElements()) {
                    String name = enumb.nextElement();
                    Object obj = mapm.getObject(name);
                    buffer.append(name);
                    buffer.append(",");
                    buffer.append(obj.getClass().getCanonicalName());
                    buffer.append(",");
                    buffer.append(obj);
                    buffer.append("\n");
                }
            }
            Utils.messageProperties(propBuffer, msg);
            if (!isLast && !StringUtils.isEmpty(separator)) {
                propBuffer.append(separator);
                buffer.append(separator);
            }
        } catch (JMSException e) {
            log.error(e.getMessage());
        }
    }
}

From source file:org.codehaus.stomp.StompTest.java

public void testSendMessageWithContentLength() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);//www  . ja  va  2  s  .  c o  m

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    byte[] data = new byte[] { 1, 0, 0, 4 };

    frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n" + "content-length:" + data.length + "\n\n";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(frame.getBytes("UTF-8"));
    baos.write(data);
    baos.write('\0');
    baos.flush();
    sendFrame(baos.toByteArray());

    BytesMessage message = (BytesMessage) consumer.receive(10000);
    Assert.assertNotNull(message);
    assertEquals(data.length, message.getBodyLength());
    assertEquals(data[0], message.readByte());
    assertEquals(data[1], message.readByte());
    assertEquals(data[2], message.readByte());
    assertEquals(data[3], message.readByte());
}

From source file:org.exist.replication.jms.obsolete.FileSystemListener.java

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

    try {//from   ww  w .  j a v  a  2s  . 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 a v  a  2 s  . c  om*/

        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;//w w  w.  j  av a2  s  .c om
    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//from   w  w  w. ja va2 s.co  m
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 {

    }

}