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

private void addNewColorListener() throws JMSException {
    addMessageListener("newColor", new MessageListener() {
        @Override/*from   w w  w.j ava 2 s .  c  om*/
        public void onMessage(Message arg0) {
            BytesMessage o = (BytesMessage) arg0;
            try {
                byte[] body = new byte[(int) o.getBodyLength()];
                o.readBytes(body);
                Color color = Color.fromProtobuf(BCSAPIMessage.Color.parseFrom(body));
                StoredColor sc = new StoredColor();
                sc.setFungibleName(color.getFungibleName());
                sc.setExpiryHeight(color.getExpiryHeight());
                sc.setPubkey(color.getPubkey());
                sc.setSignature(color.getSignature());
                sc.setTerms(color.getTerms());
                sc.setUnit(color.getUnit());
                sc.setTxHash(color.getTransaction());
                store.issueColor(sc);
                reply(o.getJMSReplyTo(), null);
            } catch (Exception e) {
                BCSAPIMessage.ExceptionMessage.Builder builder = BCSAPIMessage.ExceptionMessage.newBuilder();
                builder.setBcsapiversion(1);
                builder.addMessage(e.getMessage());
                try {
                    reply(o.getJMSReplyTo(), builder.build().toByteArray());
                } catch (JMSException e1) {
                    log.error("Can not send reply ", e1);
                }
            }
        }
    });
}

From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java

private void addBloomFilterListener() throws JMSException {
    addMessageListener("filterRequest", new MessageListener() {
        @Override//from  w  w w  . java  2 s.  c  om
        public void onMessage(Message msg) {
            BytesMessage o = (BytesMessage) msg;
            byte[] body;
            try {
                body = new byte[(int) o.getBodyLength()];
                o.readBytes(body);
                BCSAPIMessage.FilterRequest request = BCSAPIMessage.FilterRequest.parseFrom(body);
                byte[] data = request.getFilter().toByteArray();
                long hashFunctions = request.getHashFunctions();
                long tweak = request.getTweak();
                UpdateMode updateMode = UpdateMode.values()[request.getMode()];
                BloomFilter filter = new BloomFilter(data, hashFunctions, tweak, updateMode);
                synchronized (correlationBloomFilter) {
                    if (!correlationProducer.containsKey(o.getJMSCorrelationID())) {
                        MessageProducer producer = session.createProducer(msg.getJMSReplyTo());
                        correlationProducer.put(o.getJMSCorrelationID(), producer);
                    }
                    correlationBloomFilter.put(o.getJMSCorrelationID(), filter);
                }
            } catch (JMSException e) {
                log.error("invalid filter request", e);
            } catch (InvalidProtocolBufferException e) {
                log.error("invalid filter request", e);
            }
        }
    });
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java

private void addAttachment(Request request, BytesMessage bytesMessageReceive, JMSResponse jmsResponse)
        throws JMSException {
    try {//from   w w w .  ja v a 2s  .c  o  m
        byte[] buff = new byte[1];
        File temp = File.createTempFile("bytesmessage", ".tmp");
        OutputStream out = new FileOutputStream(temp);
        bytesMessageReceive.reset();
        while (bytesMessageReceive.readBytes(buff) != -1) {
            out.write(buff);
        }
        out.close();
        Attachment[] attachments = new Attachment[] {
                new RequestFileAttachment(temp, false, (AbstractHttpRequest<?>) request) };
        jmsResponse.setAttachments(attachments);
    } catch (IOException e) {
        SoapUI.logError(e);
    }
}

From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java

private void addBloomScanListener() throws JMSException {
    addMessageListener("scanRequest", new MessageListener() {
        @Override//from   w  w  w. j av  a  2 s  .  co  m
        public void onMessage(Message msg) {
            BytesMessage o = (BytesMessage) msg;
            byte[] body;
            try {
                body = new byte[(int) o.getBodyLength()];
                o.readBytes(body);
                BCSAPIMessage.FilterRequest request = BCSAPIMessage.FilterRequest.parseFrom(body);
                byte[] data = request.getFilter().toByteArray();
                long hashFunctions = request.getHashFunctions();
                long tweak = request.getTweak();
                UpdateMode updateMode = UpdateMode.values()[request.getMode()];
                final BloomFilter filter = new BloomFilter(data, hashFunctions, tweak, updateMode);
                final MessageProducer producer = session.createProducer(msg.getJMSReplyTo());
                requestProcessor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            store.scan(filter, 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.bitsofproof.supernode.core.ImplementBCSAPI.java

private void addMatchScanListener() throws JMSException {
    addMessageListener("matchRequest", new MessageListener() {
        @Override//  w  ww.j ava 2 s  .co  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.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

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

    if (check.getField().equals(MESSAGECONTENTFIELD)) {
        try {//ww w.j  ava 2 s . 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:com.chinamobile.bcbsp.comm.ConsumerTool.java

/**
 * Put message into messageQueue with serialize method.
 *///from  w ww  . java  2s.c om
public void onMessageOptimistic(Message message) throws IOException {
    messagesReceived++;
    try {
        if (message instanceof BytesMessage) {
            BytesMessage mapMsg = (BytesMessage) message;
            BSPMessage bspMsg;
            int packSize = mapMsg.readInt();
            int count = 0;
            int partitionID;
            String srcVertexID;
            String dstVertexID;
            byte[] tag;
            byte[] data;
            int tagLen;
            int dataLen;
            while (count < packSize) {
                partitionID = mapMsg.readInt();
                dstVertexID = mapMsg.readUTF();
                tagLen = mapMsg.readInt();
                tag = new byte[tagLen];
                mapMsg.readBytes(tag);
                dataLen = mapMsg.readInt();
                data = new byte[dataLen];
                mapMsg.readBytes(data);
                // bspMsg = new BSPMessage(partitionID, dstVertexID, tag, data);
                // dst is message if it is not null.
                bspMsg = new BSPMessage(partitionID, dstVertexID, tag, data);
                this.messageQueues.incomeAMessage(dstVertexID, bspMsg);
                this.messageCount++;
                this.messageBytesCount += bspMsg.size();
                count++;
            }
        } else {
            // Message received is not ObjectMessage.
            LOG.error("[ConsumerTool] Message received is not BytesMessage!");
        }
        if (message.getJMSReplyTo() != null) {
            replyProducer.send(message.getJMSReplyTo(),
                    session.createTextMessage("Reply: " + message.getJMSMessageID()));
        }
        if (transacted) {
            if ((messagesReceived % batch) == 0) {
                LOG.info("Commiting transaction for last " + batch + " messages; messages so far = "
                        + messagesReceived);
                session.commit();
            }
        } else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
            if ((messagesReceived % batch) == 0) {
                LOG.info("Acknowledging last " + batch + " messages; messages so far = " + messagesReceived);
                message.acknowledge();
            }
        }
    } catch (JMSException e) {
        LOG.error("[ConsumerTool] caught: ", e);
    } finally {
        if (sleepTime > 0) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                LOG.error("[ConsumerTool] caught: ", e);
            }
        }
    }
}

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

/**
 * Return the body length in bytes for a bytes message
 * @param bMsg the JMS BytesMessage//from   w ww  .j  av  a2 s  . c o  m
 * @return length of body in bytes
 */
public static long getBodyLength(BytesMessage bMsg) {
    try {
        Method mtd = bMsg.getClass().getMethod("getBodyLength", NOARGS);
        if (mtd != null) {
            return (Long) mtd.invoke(bMsg, NOPARMS);
        }
    } catch (Exception e) {
        // JMS 1.0
        if (log.isDebugEnabled()) {
            log.debug("Error trying to determine JMS BytesMessage body length", e);
        }
    }

    // if JMS 1.0
    long length = 0;
    try {
        byte[] buffer = new byte[2048];
        bMsg.reset();
        for (int bytesRead = bMsg.readBytes(buffer); bytesRead != -1; bytesRead = bMsg.readBytes(buffer)) {
            length += bytesRead;
        }
    } catch (JMSException ignore) {
    }
    return length;
}

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  w  w w.  j  a  v  a 2s .  c  o m*/
    byte[] result = new byte[(int) message.getBodyLength()];
    message.readBytes(result);
    return result;
}

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

/**
 * Get an InputStream to the JMS message payload
 *
 * @param message the JMS message//from  w w w  . ja  v  a 2 s  . c o m
 * @return an InputStream to the payload
 */
public InputStream getInputStream(Object message) {

    try {
        if (message instanceof BytesMessage) {
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            BytesMessage byteMsg = (BytesMessage) message;
            for (int bytesRead = byteMsg.readBytes(buffer); bytesRead != -1; bytesRead = byteMsg
                    .readBytes(buffer)) {
                out.write(buffer, 0, bytesRead);
            }
            return new ByteArrayInputStream(out.toByteArray());

        } else if (message instanceof TextMessage) {
            TextMessage txtMsg = (TextMessage) message;
            String contentType = getProperty(txtMsg, BaseConstants.CONTENT_TYPE);

            if (contentType != null) {
                return new ByteArrayInputStream(
                        txtMsg.getText().getBytes(BuilderUtil.getCharSetEncoding(contentType)));
            } else {
                return new ByteArrayInputStream(txtMsg.getText().getBytes());
            }

        } else {
            handleException("Unsupported JMS message type : " + message.getClass().getName());
        }

    } catch (JMSException e) {
        handleException("JMS Exception reading message payload", e);
    } catch (UnsupportedEncodingException e) {
        handleException("Encoding exception getting InputStream into message", e);
    }
    return null;
}