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:com.chinamobile.bcbsp.comm.ProducerTool.java

/**
 * Send message into messageQueue, update information with serialize method.
 * @param session/*from  w ww  .  j  a v a 2 s .c  om*/
 * @param producer
 * @throws Exception
 *         e
 */
private void sendLoopOptimistic(final Session session, final MessageProducer producer) throws Exception {
    try {
        BSPMessage msg;
        int count = 0;
        int packCounts = messageQueue.size() / this.packSize;
        // LOG.info("send packSize = "+ this.packSize);
        int packCount = 0;
        while (packCount < packCounts) {
            BytesMessage message = session.createBytesMessage();
            long start = System.currentTimeMillis();
            /* Clock */
            message.writeInt(this.packSize);
            count = 0;
            while (count < this.packSize) {
                msg = (BSPMessage) messageQueue.poll();
                // LOG.info(msg.intoString());
                // message.setInt("dstPartition", msg.getDstPartition());
                message.writeInt(msg.getDstPartition());
                // message.writeUTF(msg.getSrcVertexID());
                // message.setString("dstVertexID", msg.getDstVertexID());
                message.writeUTF(msg.getDstVertexID());
                // message.setBytes("tag", msg.getTag());
                message.writeInt(msg.getTag().length);
                message.writeBytes(msg.getTag());
                // message.setBytes("data", msg.getData());
                message.writeInt(msg.getData().length);
                message.writeBytes(msg.getData());
                count++;
                this.messageCount++;
            }
            this.serializeTime += (System.currentTimeMillis() - start);
            /* Clock */
            start = System.currentTimeMillis();
            /* Clock */
            producer.send(message);
            this.sendTime += (System.currentTimeMillis() - start);
            /* Clock */
            packCount++;
            // if (messageCount % 100000 == 0 ){
            // LOG.info("send " + messageCount);
            // }
        }
        // send remaining messags
        int sendSize = messageQueue.size();
        if (sendSize != 0) {
            BytesMessage message = session.createBytesMessage();
            long start = System.currentTimeMillis();
            /* Clock */
            // message.setInt("packSize", sendSize);
            message.writeInt(sendSize);
            while ((msg = (BSPMessage) messageQueue.poll()) != null) {
                // message.setInt("dstPartition", msg.getDstPartition());
                message.writeInt(msg.getDstPartition());
                // message.setString("dstVertexID", msg.getDstVertexID());
                message.writeUTF(msg.getDstVertexID());
                // message.setBytes("tag", msg.getTag());
                message.writeInt(msg.getTag().length);
                message.writeBytes(msg.getTag());
                // message.setBytes("data", msg.getData());
                message.writeInt(msg.getData().length);
                message.writeBytes(msg.getData());
                this.messageCount++;
            }
            this.serializeTime += (System.currentTimeMillis() - start);
            /* Clock */
            start = System.currentTimeMillis();
            /* Clock */
            producer.send(message);
            this.sendTime += (System.currentTimeMillis() - start);
            /* Clock */
        }
    } catch (Exception e) {
        LOG.error("[ProducerTool] send loop ", e);
    }
}

From source file:gov.medicaid.services.impl.ProviderEnrollmentServiceBean.java

/**
 * Sends the given provider for export to the message queue.
 * @param ticketId the ticket id/*from w  ww  . j av a  2 s. c  om*/
 */
@Override
public void sendSyncronizationRequest(long ticketId) {
    Session session = null;
    Connection connection = null;

    try {
        connection = mqConnectionFactory.createConnection();
        session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        MessageProducer sender = session.createProducer(dataSyncQueue);
        BytesMessage message = session.createBytesMessage();
        byte[] content = exportAsFlatFile(ticketId);
        getLog().log(Level.INFO, "Sending data sync request:" + new String(content));
        message.writeBytes(content);
        sender.send(message);
    } catch (PortalServiceException e) {
        getLog().log(Level.ERROR, e);
        throw new PortalServiceRuntimeException("While attempting to synchronize data", e);
    } catch (JMSException e) {
        getLog().log(Level.ERROR, e);
        throw new PortalServiceRuntimeException("While attempting to synchronize data", e);
    }
}

From source file:org.apache.activemq.bugs.AMQ6133PersistJMSRedeliveryTest.java

private void sendMessages() throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination queue = session.createQueue(QUEUE_NAME);
    Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain");
    MessageProducer producer = session.createProducer(null);

    final byte[] payload = new byte[1000];
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);//from  w  w  w .  j av  a 2 s. co  m

    // Build up a set of messages that will be redelivered and updated later.
    while (getLogFileCount() < 3) {
        producer.send(queue, message);
    }

    // Now create some space for files that are retained during the test.
    while (getLogFileCount() < 6) {
        producer.send(retainQueue, message);
    }

    connection.close();
}

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

/**
 * Create a JMS Message from the given MessageContext and using the given
 * session/* w  w w. j  a 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 msgContext, Session session, String contentTypeProperty)
        throws JMSException, AxisFault {

    Message message = null;
    String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE);

    // check the first element of the SOAP body, do we have content wrapped using the
    // default wrapper elements for binary (BaseConstants.DEFAULT_BINARY_WRAPPER) or
    // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP messages
    // for JMS but just get the payload in its native format
    String jmsPayloadType = guessMessageType(msgContext);

    if (jmsPayloadType == null) {

        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = TransportUtils.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) {
                handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
                return null;
            }
        }

        try {
            messageFormatter.writeTo(msgContext, format, out, true);
            out.close();
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        }

        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) {
                    handleException("Error serializing binary content of element : "
                            + BaseConstants.DEFAULT_BINARY_WRAPPER, e);
                }
            }
        }

    } 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());
    }

    // set the JMS correlation ID if specified
    String correlationId = getProperty(msgContext, JMSConstants.JMS_COORELATION_ID);
    if (correlationId == null && msgContext.getRelatesTo() != null) {
        correlationId = msgContext.getRelatesTo().getValue();
    }

    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.apache.axis2.transport.jms.MockEchoEndpoint.java

@Setup
@SuppressWarnings("unused")
private void setUp(JMSTestEnvironment env, JMSRequestResponseChannel channel) throws Exception {
    Destination destination = channel.getDestination();
    Destination replyDestination = channel.getReplyDestination();
    connection = env.getConnectionFactory().createConnection();
    connection.setExceptionListener(this);
    connection.start();//  ww  w .ja  v a2  s .  c  o  m
    replyConnection = env.getConnectionFactory().createConnection();
    replyConnection.setExceptionListener(this);
    final Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final MessageProducer producer = replySession.createProducer(replyDestination);
    MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)
            .createConsumer(destination);
    consumer.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            try {
                log.info("Message received: ID = " + message.getJMSMessageID());
                Message reply;
                if (message instanceof BytesMessage) {
                    reply = replySession.createBytesMessage();
                    IOUtils.copy(new BytesMessageInputStream((BytesMessage) message),
                            new BytesMessageOutputStream((BytesMessage) reply));
                } else if (message instanceof TextMessage) {
                    reply = replySession.createTextMessage();
                    ((TextMessage) reply).setText(((TextMessage) message).getText());
                } else {
                    // TODO
                    throw new UnsupportedOperationException("Unsupported message type");
                }
                reply.setJMSCorrelationID(message.getJMSMessageID());
                reply.setStringProperty(BaseConstants.CONTENT_TYPE,
                        message.getStringProperty(BaseConstants.CONTENT_TYPE));
                producer.send(reply);
                log.info("Message sent: ID = " + reply.getJMSMessageID());
            } catch (Throwable ex) {
                fireEndpointError(ex);
            }
        }
    });
}

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

/**
 * /*from  ww w.  j av  a2s .  com*/
 * Create the {@link Message} 
 * 
 * @return jmsMessage or null if the mapping was not successfully
 */
protected Message createJmsMessageForType(Exchange exchange, Object body, Map<String, Object> headers,
        Session session, CamelContext context, JmsMessageType type) throws JMSException {
    switch (type) {
    case Text: {
        TextMessage message = session.createTextMessage();
        String payload = context.getTypeConverter().convertTo(String.class, exchange, body);
        message.setText(payload);
        return message;
    }
    case Bytes: {
        BytesMessage message = session.createBytesMessage();
        byte[] payload = context.getTypeConverter().convertTo(byte[].class, exchange, body);
        message.writeBytes(payload);
        return message;
    }
    case Map: {
        MapMessage message = session.createMapMessage();
        Map payload = context.getTypeConverter().convertTo(Map.class, exchange, body);
        populateMapMessage(message, payload, context);
        return message;
    }
    case Object:
        Serializable payload;
        try {
            payload = context.getTypeConverter().mandatoryConvertTo(Serializable.class, exchange, body);
        } catch (NoTypeConversionAvailableException e) {
            // cannot convert to serializable then thrown an exception to avoid sending a null message
            JMSException cause = new MessageFormatException(e.getMessage());
            cause.initCause(e);
            throw cause;
        }
        return session.createObjectMessage(payload);
    default:
        break;
    }
    return null;
}

From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java

public Message createMessage(Session session, int messageSize) throws JMSException
{
    String payload = new String(new byte[messageSize]);

    Message message;// w w w.  j  ava2 s  . com

    switch (_messageType)
    {
        case BYTES:
            message = session.createBytesMessage();
            ((BytesMessage) message).writeUTF(payload);
            break;
        case MAP:
            message = session.createMapMessage();
            ((MapMessage) message).setString(CONTENT, payload);
            break;
        default: // To keep the compiler happy
        case TEXT:
            message = session.createTextMessage();
            ((TextMessage) message).setText(payload);
            break;
        case OBJECT:
            message = session.createObjectMessage();
            ((ObjectMessage) message).setObject(payload);
            break;
        case STREAM:
            message = session.createStreamMessage();
            ((StreamMessage) message).writeString(payload);
            break;
    }

    return message;
}

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

/**
 * Create a JMS Message from the given MessageContext and using the given
 * session/*from  w  w w  . j  av a2s .  co  m*/
 *
 * @param msgContext the MessageContext
 * @param session    the JMS session
 * @return a JMS message from the context and session
 * @throws JMSException on exception
 * @throws AxisFault on exception
 */
private Message createJMSMessage(MessageContext msgContext, Session session) throws JMSException, AxisFault {

    Message message = null;
    String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE);

    // check the first element of the SOAP body, do we have content wrapped using the
    // default wrapper elements for binary (BaseConstants.DEFAULT_BINARY_WRAPPER) or
    // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP messages
    // for JMS but just get the payload in its native format
    String jmsPayloadType = guessMessageType(msgContext);

    if (jmsPayloadType == null) {

        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = TransportUtils.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new JMSException("Unable to get the message formatter to use");
        }

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

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            messageFormatter.writeTo(msgContext, format, baos, true);
            baos.flush();
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        }

        if (msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType)
                || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1) {
            message = session.createBytesMessage();
            BytesMessage bytesMsg = (BytesMessage) message;
            bytesMsg.writeBytes(baos.toByteArray());
        } else {
            message = session.createTextMessage(); // default
            TextMessage txtMsg = (TextMessage) message;
            txtMsg.setText(new String(baos.toByteArray()));
        }
        message.setStringProperty(BaseConstants.CONTENT_TYPE, 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) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ((DataHandler) dh).writeTo(baos);
                } catch (IOException e) {
                    handleException("Error serializing binary content of element : "
                            + BaseConstants.DEFAULT_BINARY_WRAPPER, e);
                }
                bytesMsg.writeBytes(baos.toByteArray());
            }
        }

    } 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());
    }

    // set the JMS correlation ID if specified
    String correlationId = getProperty(msgContext, JMSConstants.JMS_COORELATION_ID);
    if (correlationId == null && msgContext.getRelatesTo() != null) {
        correlationId = msgContext.getRelatesTo().getValue();
    }

    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.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java

/**
 * Creates message.//from w  w  w. j a  va 2s . co  m
 * 
 * @param config
 *          the config
 * @param record
 *          the record
 * @param messageProperties
 *          the jms message properties
 * @param session
 *          the session
 * 
 * @return the message
 * 
 * @throws JMSException
 *           the JMS exception
 */
private Message createMessage(final SendType config, final Record record, final Properties messageProperties,
        final Session session) throws JMSException {
    final BytesMessage message = session.createBytesMessage();

    // set dynamic message properties
    if (messageProperties != null) {
        final Enumeration<?> propertyNames = messageProperties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            final String name = (String) propertyNames.nextElement();
            message.setStringProperty(name, messageProperties.getProperty(name));
        }
    }

    // get static properties of config file
    for (final PropertyType property : config.getSetProperty()) {
        message.setStringProperty(property.getName(), property.getValue());
    }

    final byte[] serialized = XmlSerializationUtils.serialize2byteArray(record);
    message.writeBytes(serialized);
    return message;
}

From source file:org.exist.messaging.JmsMessageSender.java

private Message createMessage(Session session, Item item, MessagingMetadata mdd, XQueryContext xqcontext)
        throws JMSException, XPathException {

    Message message = null;/* w ww.  jav a  2  s .  c  o m*/

    mdd.add("exist.datatype", Type.getTypeName(item.getType()));

    if (item.getType() == Type.ELEMENT || item.getType() == Type.DOCUMENT) {
        LOG.debug("Streaming element or document node");

        if (item instanceof NodeProxy) {
            NodeProxy np = (NodeProxy) item;
            String uri = np.getDocument().getBaseURI();
            LOG.debug("Document detected, adding URL " + uri);
            mdd.add("exist.document-uri", uri);
        }

        // Node provided
        Serializer serializer = xqcontext.getBroker().newSerializer();

        NodeValue node = (NodeValue) item;
        InputStream is = new NodeInputStream(serializer, node);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            IOUtils.copy(is, baos);
        } catch (IOException ex) {
            LOG.error(ex);
            throw new XPathException(ex);
        }
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(baos);

        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeBytes(baos.toByteArray());

        message = bytesMessage;

    } else if (item.getType() == Type.BASE64_BINARY || item.getType() == Type.HEX_BINARY) {
        LOG.debug("Streaming base64 binary");

        if (item instanceof Base64BinaryDocument) {
            Base64BinaryDocument b64doc = (Base64BinaryDocument) item;
            String uri = b64doc.getUrl();
            LOG.debug("Base64BinaryDocument detected, adding URL " + uri);
            mdd.add("exist.document-uri", uri);
        }

        BinaryValue binary = (BinaryValue) item;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = binary.getInputStream();

        //TODO consider using BinaryValue.getInputStream()
        //byte[] data = (byte[]) binary.toJavaObject(byte[].class);

        try {
            IOUtils.copy(is, baos);
        } catch (IOException ex) {
            LOG.error(ex);
            throw new XPathException(ex);
        }
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(baos);

        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeBytes(baos.toByteArray());

        message = bytesMessage;
    } else if (item.getType() == Type.STRING) {
        TextMessage textMessage = session.createTextMessage();
        textMessage.setText(item.getStringValue());
        message = textMessage;

    } else {
        ObjectMessage objectMessage = session.createObjectMessage();
        //objectMessage.setObject(item.toJavaObject(Object.class)); TODO hmmmm
        message = objectMessage;
    }

    return message;
}