Example usage for javax.jms Session createTextMessage

List of usage examples for javax.jms Session createTextMessage

Introduction

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

Prototype


TextMessage createTextMessage() throws JMSException;

Source Link

Document

Creates a TextMessage object.

Usage

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 ww. j a  v a  2 s  .  co m*/

    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.storm.jms.spout.JmsSpoutTest.java

public Message sendMessage(ConnectionFactory connectionFactory, Destination destination) throws JMSException {
    Session mySess = connectionFactory.createConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageProducer producer = mySess.createProducer(destination);
    TextMessage msg = mySess.createTextMessage();
    msg.setText("Hello World");
    log.debug("Sending Message: " + msg.getText());
    producer.send(msg);/*from w w  w. ja  v a  2 s.  c  o  m*/
    return msg;
}

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

/**
 * Create a JMS Message from the given MessageContext and using the given
 * session/*w ww .  ja v a 2s .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.exist.messaging.JmsMessageSender.java

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

    Message message = null;// w w w  . ja  va  2s .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;
}

From source file:org.firstopen.singularity.util.JMSUtil.java

public static void deliverMessageToTopic(String host, String topicName, String xml) {
    log.debug("IntegrationMod.deliverMessageToQueue queueName = " + topicName + " and doc = " + xml);

    char test = topicName.charAt(0);

    if (test == '/')
        topicName = topicName.substring(1);

    try {/*from   ww  w  .jav  a2s.c om*/

        InitialContext context = JNDIUtil.getInitialContext(host);

        Connection connection = null;
        Session session = null;
        MessageProducer publisher = null;
        ConnectionFactory tcf = (ConnectionFactory) context.lookup("ConnectionFactory");

        Topic topic = (Topic) context.lookup(topicName);

        connection = tcf.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        publisher = session.createProducer(topic);

        TextMessage message = session.createTextMessage();

        log.debug("message value is -> " + xml);

        message.setText(xml);

        publisher.send(message);

    } catch (Exception e) {
        log.error("unable to send message on topic", e);
    } finally {

    }
}

From source file:org.firstopen.singularity.util.JMSUtil.java

public static void deliverMessageToQueue(String host, String queueName, String xml) {
    log.debug("IntegrationMod.deliverMessageToQueue queueName = " + queueName + " and doc = " + xml);
    MessageProducer m_sender = null;/* w  ww  .ja v  a  2s  .  c o  m*/
    Session m_session = null;
    Connection connection = null;

    char test = queueName.charAt(0);

    if (test == '/')
        queueName = queueName.substring(1);

    try {

        InitialContext context = JNDIUtil.getInitialContext(host);

        ConnectionFactory qcf = (ConnectionFactory) context.lookup("ConnectionFactory");

        Queue queue = (Queue) context.lookup("queue/" + queueName);

        connection = qcf.createConnection();

        m_session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        m_sender = m_session.createProducer(queue);

        TextMessage message = m_session.createTextMessage();

        log.debug("message value is -> " + xml);

        message.setText(xml);

        m_sender.send(message);

    } catch (Exception e) {
        log.error("IntegrationMod.deliverMessageToQueue() Exception = ", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                log.error("unable ot close JMS Connection", e);
            }
        }
    }
}

From source file:org.openadaptor.auxil.connector.jms.DefaultMessageGenerator.java

public Message createMessage(Object messageRecord, Session session) throws JMSException {
    Message msg;/* w  w w  .j a  v  a  2s  .  c o  m*/
    if (messageRecord instanceof String) {
        TextMessage textMsg = session.createTextMessage();
        textMsg.setText((String) messageRecord);
        msg = textMsg;
    } else if (messageRecord instanceof Serializable) {
        ObjectMessage objectMsg = session.createObjectMessage();
        objectMsg.setObject((Serializable) messageRecord);
        msg = objectMsg;
    } else {
        // We have not needed more message types in practice.
        // If we do need them in future this is where they go.
        throw new RecordFormatException(
                "Undeliverable record type [" + messageRecord.getClass().getName() + "]");
    }
    setMessageProperties(msg);
    return msg;
}

From source file:org.openanzo.combus.realtime.RealtimeUpdatePublisher.java

/**
 * Reset cache the cache of acls//from w w w.j  av a  2s  .co  m
 * 
 * @param session
 *            session
 * @throws AnzoException
 */
public void reset(Session session) throws AnzoException {
    synchronized (datasetTrackers) {
        datasetTrackers.clear();
    }
    userRolesCache.clear();
    graphRolesCache.clear();
    registeredSysadmins.clear();
    trackers.clear();
    namedGraphTrackers.clear();
    try {
        // Now send a transaction complete to all users
        TextMessage endMessage = session.createTextMessage();
        endMessage.setStringProperty(SerializationConstants.operation, SerializationConstants.reset);
        endMessage.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION);
        for (Map.Entry<URI, Collection<Destination>> entry : userDestinations.entrySet()) {
            Collection<Destination> destinations = entry.getValue();
            for (Destination destination : destinations) {
                try {
                    getProducer().send(destination, endMessage);
                } catch (JMSException jmex) {
                    log.debug(LogUtils.COMBUS_MARKER, "Error sending reset message", jmex);
                    cleanupDestination(entry.getKey(), destination);
                }
            }
        }
    } catch (JMSException jmse) {
        throw new AnzoException(ExceptionConstants.COMBUS.PROCESS_UPDATE_FAILED, jmse);
    }
    //currentServerId = serviceContainer.getInstanceURI().toString();
}

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 www.j a  v a 2 s .c o  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.integration.test.client.JMSPublisherClient.java

/**
 * Each message will be divided into groups and create the map message
 *
 * @param producer     Used for sending messages to a destination
 * @param session      Used to produce the messages to be sent
 * @param messagesList List of messages to be sent
 *
 *//*ww w.  j a va2s.c  o  m*/
public static void publishTextMessage(MessageProducer producer, Session session, List<String> messagesList)
        throws JMSException {
    for (String message : messagesList) {
        TextMessage jmsTextMessage = session.createTextMessage();
        jmsTextMessage.setText(message);
        producer.send(jmsTextMessage);
    }
}