Example usage for javax.jms Session createBytesMessage

List of usage examples for javax.jms Session createBytesMessage

Introduction

In this page you can find the example usage for javax.jms Session createBytesMessage.

Prototype

BytesMessage createBytesMessage() throws JMSException;

Source Link

Document

Creates a BytesMessage object.

Usage

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

protected BytesMessage marshalToBytesMessage(Object object, Session session,
        org.springframework.obm.Marshaller marshaller) throws JMSException, IOException, XmlMappingException {
    Assert.notNull(object);/* w w  w .  java 2s .co m*/
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    BytesMessage message;
    try {

        marshaller.marshal(object, bos);

        message = session.createBytesMessage();
        message.writeBytes(bos.toByteArray());

        if (log.isDebugEnabled()) {
            log.debug("sent:" + object);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return message;
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSReplySender.java

/**
 * Create a JMS Message from the given MessageContext and using the given
 * session//from w ww  . ja v  a  2  s.  co  m
 * 
 * @param msgContext
 *            the MessageContext
 * @param session
 *            the JMS session
 * @param contentTypeProperty
 *            the message property to be used to store the content type
 * @return a JMS message from the context and session
 * @throws JMSException
 *             on exception
 * @throws AxisFault
 *             on exception
 */
private Message createJMSMessage(MessageContext synCtx, Session session, String contentTypeProperty)
        throws JMSException {

    Message message = null;
    org.apache.axis2.context.MessageContext msgContext = ((Axis2MessageContext) synCtx)
            .getAxis2MessageContext();
    String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE);
    String jmsPayloadType = guessMessageType(msgContext);
    if (jmsPayloadType == null) {
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new JMSException("Unable to get the message formatter to use");
        }

        String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction());

        boolean useBytesMessage = msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType)
                || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1;

        OutputStream out;
        StringWriter sw;
        if (useBytesMessage) {
            BytesMessage bytesMsg = session.createBytesMessage();
            sw = null;
            out = new BytesMessageOutputStream(bytesMsg);
            message = bytesMsg;
        } else {
            sw = new StringWriter();
            try {
                out = new WriterOutputStream(sw, format.getCharSetEncoding());
            } catch (UnsupportedCharsetException ex) {
                log.error("Unsupported encoding " + format.getCharSetEncoding(), ex);
                throw new JMSException("Unsupported encoding " + format.getCharSetEncoding());
            }
        }

        try {
            messageFormatter.writeTo(msgContext, format, out, true);
            out.close();
        } catch (IOException e) {
            log.error("IO Error while creating BytesMessage", e);
            throw new JMSException("IO Error while creating BytesMessage");
        }
        if (!useBytesMessage) {
            TextMessage txtMsg = session.createTextMessage();
            txtMsg.setText(sw.toString());
            message = txtMsg;
        }
        if (contentTypeProperty != null) {
            message.setStringProperty(contentTypeProperty, contentType);
        }

    } else if (JMSConstants.JMS_BYTE_MESSAGE.equals(jmsPayloadType)) {
        message = session.createBytesMessage();
        BytesMessage bytesMsg = (BytesMessage) message;
        OMElement wrapper = msgContext.getEnvelope().getBody()
                .getFirstChildWithName(BaseConstants.DEFAULT_BINARY_WRAPPER);
        OMNode omNode = wrapper.getFirstOMChild();
        if (omNode != null && omNode instanceof OMText) {
            Object dh = ((OMText) omNode).getDataHandler();
            if (dh != null && dh instanceof DataHandler) {
                try {
                    ((DataHandler) dh).writeTo(new BytesMessageOutputStream(bytesMsg));
                } catch (IOException e) {
                    log.error("Error serializing binary content of element : "
                            + BaseConstants.DEFAULT_BINARY_WRAPPER, e);
                    throw new JMSException("Error serializing binary content of element : "
                            + BaseConstants.DEFAULT_BINARY_WRAPPER);
                }
            }
        }

    } else if (JMSConstants.JMS_TEXT_MESSAGE.equals(jmsPayloadType)) {
        message = session.createTextMessage();
        TextMessage txtMsg = (TextMessage) message;
        txtMsg.setText(msgContext.getEnvelope().getBody()
                .getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText());
    } else if (JMSConstants.JMS_MAP_MESSAGE.equalsIgnoreCase(jmsPayloadType)) {
        message = session.createMapMessage();
        JMSUtils.convertXMLtoJMSMap(
                msgContext.getEnvelope().getBody().getFirstChildWithName(JMSConstants.JMS_MAP_QNAME),
                (MapMessage) message);
    }

    // set the JMS correlation ID if specified
    String correlationId = (String) synCtx.getProperty(JMSConstants.JMS_COORELATION_ID);
    if (correlationId != null) {
        message.setJMSCorrelationID(correlationId);
    }

    if (msgContext.isServerSide()) {
        // set SOAP Action as a property on the JMS message
        setProperty(message, msgContext, BaseConstants.SOAPACTION);
    } else {
        String action = msgContext.getOptions().getAction();
        if (action != null) {
            message.setStringProperty(BaseConstants.SOAPACTION, action);
        }
    }

    JMSUtils.setTransportHeaders(msgContext, message);
    return message;
}

From source file:org.wso2.carbon.registry.caching.invalidator.connection.JMSNotification.java

@Override
public void publish(Object message) {
    Session pubSession = null;
    try {//w  ww  . j  a  va 2s .c  o m
        if (connection != null) {
            pubSession = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE);
            MessageProducer publisher = pubSession.createProducer(destination);
            BytesMessage bytesMessage = pubSession.createBytesMessage();
            bytesMessage.writeBytes((byte[]) message);
            publisher.send(bytesMessage);
        }
    } catch (JMSException e) {
        log.error("Global cache invalidation: Error in publishing the message", e);
    } finally {
        if (pubSession != null) {
            try {
                pubSession.close();
            } catch (JMSException e) {
                log.error("Global cache invalidation: Error in publishing the message", e);
            }
        }
    }
}

From source file:tools.ProducerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;
    try {//from  w  w  w  . ja v  a  2s . c o m
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        MessageProducer producer = session.createProducer(destination);
        if (durable) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages;

        for (int i = 0; i < numMessagesToSend; i++) {
            String messageText = "Message " + i + " at " + new Date();
            if (bytesLength > -1) {
                byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8);
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(messageTextBytes);
                if (messageTextBytes.length < bytesLength) {
                    byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length];
                    bytesMessage.writeBytes(paddingBytes);
                }
                if (messageGroupId != null) {
                    bytesMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending bytes message");
                producer.send(bytesMessage);
            } else {
                TextMessage textMessage = session.createTextMessage(messageText);
                if (messageGroupId != null) {
                    textMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending text message: " + messageText);
                producer.send(textMessage);
            }

            if (perMessageSleepMS > 0) {
                Thread.sleep(perMessageSleepMS);
            }
            if (transacted) {
                if ((i + 1) % batchSize == 0) {
                    session.commit();
                }
            }
        }
        if (useFinalControlMessage) {
            Message message = session.createMessage();
            if (messageGroupId != null) {
                message.setStringProperty("JMSXGroupID", messageGroupId);
            }
            LOGGER.info("Sending message");
            producer.send(message);
            if (transacted) {
                session.commit();
            }
        }
        producer.close();
    } catch (Exception ex) {
        LOGGER.error("ProducerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
    }
}