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:com.mirth.connect.connectors.jms.JmsMessageUtils.java

/**
 * @param message/*from   www  .j  ava2s .  c o  m*/
 *            the message to receive the bytes from. Note this only works
 *            for TextMessge, ObjectMessage, StreamMessage and BytesMessage.
 * @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 failiare occurs while stream and converting the message
 *             data
 */
public static byte[] getBytesFromMessage(Message message) throws JMSException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 2];
    int len;

    if (message instanceof BytesMessage) {
        BytesMessage bMsg = (BytesMessage) message;
        // put message in read-only mode
        bMsg.reset();
        while ((len = bMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
    } else if (message instanceof StreamMessage) {
        StreamMessage sMsg = (StreamMessage) message;
        sMsg.reset();
        while ((len = sMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
    } else if (message instanceof ObjectMessage) {
        ObjectMessage oMsg = (ObjectMessage) message;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(bs);
        os.writeObject(oMsg.getObject());
        os.flush();
        baos.write(bs.toByteArray());
        os.close();
        bs.close();
    } else if (message instanceof TextMessage) {
        TextMessage tMsg = (TextMessage) message;
        baos.write(tMsg.getText().getBytes());
    } else {
        throw new JMSException("Cannot get bytes from Map Message");
    }

    baos.flush();
    byte[] bytes = baos.toByteArray();
    baos.close();
    return bytes;
}

From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java

public static Object getObjectForMessage(Message source) throws JMSException {
    Object result = null;/*from   ww w  . j  ava2  s.  c  o m*/
    try {
        if (source instanceof ObjectMessage) {
            result = ((ObjectMessage) source).getObject();
        } else if (source instanceof MapMessage) {
            Hashtable map = new Hashtable();
            MapMessage m = (MapMessage) source;

            for (Enumeration e = m.getMapNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Object obj = m.getObject(name);
                map.put(name, obj);
            }

            result = map;
        } else if (source instanceof javax.jms.BytesMessage) {

            javax.jms.BytesMessage bm = (javax.jms.BytesMessage) source;
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

            byte[] buffer = new byte[1024 * 4];
            int len = 0;
            bm.reset();
            while ((len = bm.readBytes(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            result = baos.toByteArray();
            baos.close();
            if (result != null) {
                if (logger.isDebugEnabled())
                    logger.debug("JMSToObject: extracted " + ((byte[]) result).length
                            + " bytes from JMS BytesMessage");
            }
        } else if (source instanceof TextMessage) {
            result = ((TextMessage) source).getText();

        } else if (source instanceof BytesMessage) {
            byte[] bytes = getBytesFromMessage(source);
            return CompressionHelper.uncompressByteArray(bytes);
        } else if (source instanceof StreamMessage) {

            StreamMessage sm = (javax.jms.StreamMessage) source;

            result = new java.util.Vector();
            try {
                Object obj = null;
                while ((obj = sm.readObject()) != null) {
                    ((java.util.Vector) result).addElement(obj);
                }
            } catch (MessageEOFException eof) {
            } catch (Exception e) {
                throw new JMSException("Failed to extract information from JMS Stream Message: " + e);
            }
        } else {
            result = source;
        }
    } catch (Exception e) {
        throw new JMSException("Failed to transform message: " + e.getMessage());
    }
    return result;
}

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

public static String formatMessage(Message message) {
    StringBuilder sb = new StringBuilder();

    try {//www  .j a  v  a 2  s . co  m
        String headers = formatHeaders(message);
        if (headers.length() > 0) {
            sb.append("Message Headers:\n");
            sb.append(headers);
        }

        sb.append("Message Properties:\n");
        @SuppressWarnings("unchecked")
        Enumeration<String> propNames = message.getPropertyNames();
        while (propNames.hasMoreElements()) {
            String propertyName = propNames.nextElement();
            sb.append("  ");
            sb.append(propertyName);
            sb.append(": ");
            if (message.getObjectProperty(propertyName) != null) {
                sb.append(message.getObjectProperty(propertyName).toString());
            }
            sb.append("\n");
        }

        sb.append("Message Content:\n");
        if (message instanceof TextMessage) {
            sb.append(((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.put(field, mapper.convertValue(mm.getObject(field), JsonNode.class));
            }
            sb.append(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()) {
                sb.append(new String(bytes));
            }
        } else {
            sb.append("  Unhandled message type: " + message.getJMSType());
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Unable to format message:", e);
    }

    return sb.toString();
}

From source file:hermes.renderers.fix.FIXMessageRenderer.java

protected JComponent handleBytesMessage(BytesMessage bytesMessage)
        throws JMSException, IOException, ClassNotFoundException {
    try {//w  w  w. ja  va 2  s  .  com
        bytesMessage.reset();

        final byte[] bytes = MessageUtils.asBytes(bytesMessage);

        return createComponent(new QuickFIXMessage(cache, bytes));
    } finally {
        bytesMessage.reset();
    }
}

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/>/*  w w w  .  j a  v a 2  s. c o  m*/
 * 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.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java

private void addAttachment(Request request, BytesMessage bytesMessageReceive, JMSResponse jmsResponse)
        throws JMSException {
    try {//  w  w  w . ja v  a  2s.co 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.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

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

    if (check.getField().equals(MESSAGECONTENTFIELD)) {
        try {/*w ww . j  a  v  a 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:hermes.renderers.DefaultMessageRenderer.java

/**
 * Show a BytesMessage either as a java object or just a size.
 * /*from   w  w w. j a  v  a2 s . c o m*/
 * @param parent
 * 
 * @param bytesMessage
 * @return
 * @throws JMSException
 * @throws IOException
 * @throws ClassNotFoundException
 */
protected JComponent handleBytesMessage(JScrollPane parent, BytesMessage bytesMessage)
        throws JMSException, IOException, ClassNotFoundException {
    final MyConfig currentConfig = (MyConfig) getConfig();

    JTextArea textPane = new MyTextArea();

    textPane.setEditable(false);
    textPane.setWrapStyleWord(true);
    textPane.setLineWrap(true);
    bytesMessage.reset();

    if (currentConfig.isBytesIsObject()) {
        final byte[] bytes = MessageUtils.asBytes(bytesMessage);
        final ByteArrayInputStream bistream = new ByteArrayInputStream(bytes);
        final ObjectInputStream oistream = new ObjectInputStream(bistream);
        final Object o = oistream.readObject();

        textPane.setText(o.toString());
    } else if (currentConfig.isBytesIsString()) {
        try {
            String text = new String(MessageUtils.asBytes(bytesMessage), currentConfig.getBytesEncoding());
            textPane.setText(text);
            return textPane;
        } catch (JMSException e) {
            textPane.setText(e.getMessage());
        }
    } else {
        HexMessageRenderer renderer = new HexMessageRenderer();
        textPane = (JTextArea) renderer.render(parent, bytesMessage); // Hack.
    }

    textPane.setCaretPosition(0);

    return textPane;
}

From source file:hermes.impl.DefaultXMLHelper.java

public XMLMessage createXMLMessage(ObjectFactory factory, Message message)
        throws JMSException, IOException, EncoderException {
    try {//from  w w  w .j av a  2 s .c o m
        XMLMessage rval = factory.createXMLMessage();

        if (message instanceof TextMessage) {
            rval = factory.createXMLTextMessage();

            XMLTextMessage textRval = (XMLTextMessage) rval;
            TextMessage textMessage = (TextMessage) message;

            if (isBase64EncodeTextMessages()) {
                byte[] bytes = base64EncoderTL.get().encode(textMessage.getText().getBytes());
                textRval.setText(new String(bytes, "ASCII"));
                textRval.setCodec(BASE64_CODEC);
            } else {
                textRval.setText(textMessage.getText());
            }
        } else if (message instanceof MapMessage) {
            rval = factory.createXMLMapMessage();

            XMLMapMessage mapRval = (XMLMapMessage) rval;
            MapMessage mapMessage = (MapMessage) message;

            for (Enumeration iter = mapMessage.getMapNames(); iter.hasMoreElements();) {
                String propertyName = (String) iter.nextElement();
                Object propertyValue = mapMessage.getObject(propertyName);
                Property xmlProperty = factory.createProperty();

                if (propertyValue != null) {
                    xmlProperty.setValue(propertyValue.toString());
                    xmlProperty.setType(propertyValue.getClass().getName());
                }
                xmlProperty.setName(propertyName);

                mapRval.getBodyProperty().add(xmlProperty);
            }
        } else if (message instanceof BytesMessage) {
            rval = factory.createXMLBytesMessage();

            XMLBytesMessage bytesRval = (XMLBytesMessage) rval;
            BytesMessage bytesMessage = (BytesMessage) message;
            ByteArrayOutputStream bosream = new ByteArrayOutputStream();

            bytesMessage.reset();

            try {
                for (;;) {
                    bosream.write(bytesMessage.readByte());
                }
            } catch (MessageEOFException ex) {
                // NOP
            }

            bytesRval.setBytes(new String(base64EncoderTL.get().encode(bosream.toByteArray())));
        } else if (message instanceof ObjectMessage) {
            rval = factory.createXMLObjectMessage();

            XMLObjectMessage objectRval = (XMLObjectMessage) rval;
            ObjectMessage objectMessage = (ObjectMessage) message;

            ByteArrayOutputStream bostream = new ByteArrayOutputStream();
            ObjectOutputStream oostream = new ObjectOutputStream(bostream);

            oostream.writeObject(objectMessage.getObject());
            oostream.flush();
            byte b[] = base64EncoderTL.get().encode(bostream.toByteArray());
            String s = new String(b, "ASCII");
            objectRval.setObject(s);
        }

        if (message.getJMSReplyTo() != null) {
            rval.setJMSReplyTo(JMSUtils.getDestinationName(message.getJMSReplyTo()));
            rval.setJMSReplyToDomain(Domain.getDomain(message.getJMSReplyTo()).getId());
        }

        // try/catch each individually as we sometime find some JMS
        // providers
        // can barf
        try {
            rval.setJMSDeliveryMode(message.getJMSDeliveryMode());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSExpiration(message.getJMSExpiration());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSMessageID(message.getJMSMessageID());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSPriority(message.getJMSPriority());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSRedelivered(message.getJMSRedelivered());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        } catch (IllegalStateException ex) {
            // http://hermesjms.com/forum/viewtopic.php?f=4&t=346

            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSTimestamp(message.getJMSTimestamp());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSType(message.getJMSType());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSCorrelationID(message.getJMSCorrelationID());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            if (message.getJMSDestination() != null) {
                rval.setJMSDestination(JMSUtils.getDestinationName(message.getJMSDestination()));
                rval.setFromQueue(JMSUtils.isQueue(message.getJMSDestination()));
            }
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        for (final Enumeration iter = message.getPropertyNames(); iter.hasMoreElements();) {
            String propertyName = (String) iter.nextElement();

            if (!propertyName.startsWith("JMS")) {
                Object propertyValue = message.getObjectProperty(propertyName);
                Property property = factory.createProperty();

                property.setName(propertyName);

                if (propertyValue != null) {
                    property.setValue(StringEscapeUtils.escapeXml(propertyValue.toString()));
                    property.setType(propertyValue.getClass().getName());
                }

                rval.getHeaderProperty().add(property);
            }
        }

        return rval;
    } catch (Exception ex) {
        throw new HermesException(ex);
    }
}

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  ww w .ja  va 2  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;
}