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.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private void sendMessage(String queueName, int count, boolean transacted) throws JMSException {
    Connection con = connectionFactory.createConnection();
    try {/*w  ww . j a v  a  2s. c om*/
        Session session = con.createSession(transacted,
                transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        try {
            Queue destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            try {
                for (int i = 0; i < count; i++) {
                    TextMessage message = session.createTextMessage();
                    message.setIntProperty("MessageId", messageCounter);
                    message.setText("Message-" + messageCounter++);
                    producer.send(message);
                }
                if (transacted) {
                    session.commit();
                }
            } finally {
                producer.close();
            }
        } finally {
            session.close();
        }
    } finally {
        con.close();
    }
}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

protected TextMessage createTextMessage(Session session, String initText) throws Exception {
    TextMessage msg = session.createTextMessage();

    // Pad message text
    if (initText.length() < messageSize) {
        char[] data = new char[messageSize - initText.length()];
        Arrays.fill(data, '*');
        String str = new String(data);
        msg.setText(initText + str);//  w ww . ja  va  2  s  .c o m

        // Do not pad message text
    } else {
        msg.setText(initText);
    }

    return msg;
}

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 av  a  2s .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 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();//www  . j  a  v  a  2 s .  com
    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   w w  w. j  av  a  2 s  .  co  m*/
 * 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.falcon.messaging.JMSMessageConsumerTest.java

private Message getMockOozieMessage(int i, Session session, boolean isFalconWF)
        throws FalconException, JMSException {
    TextMessage message = session.createTextMessage();
    message.setStringProperty("appType", "WORKFLOW_JOB");
    if (isFalconWF) {
        message.setStringProperty("appName", "FALCON_PROCESS_DEFAULT_process1");
    } else {// w ww .j av  a  2 s  .c om
        message.setStringProperty("appName", "OozieSampleShellWF");
    }
    message.setStringProperty("user", "falcon");
    switch (i % 4) {
    case 0:
        message.setText("{\"status\":\"RUNNING\",\"id\":\"0000042-130618221729631-oozie-oozi-W\""
                + ",\"startTime\":1342915200000}");
        break;
    case 1:
        message.setText("{\"status\":\"FAILED\",\"errorCode\":\"EL_ERROR\","
                + "\"errorMessage\":\"variable [dummyvalue] cannot be resolved\","
                + "\"id\":\"0000042-130618221729631-oozie-oozi-W\",\"startTime\":1342915200000,"
                + "\"endTime\":1366672183543}");
        break;
    case 2:
        message.setText("{\"status\":\"SUCCEEDED\",\"id\":\"0000039-130618221729631-oozie-oozi-W\""
                + ",\"startTime\":1342915200000,"
                + "\"parentId\":\"0000025-130618221729631-oozie-oozi-C@1\",\"endTime\":1366676224154}");
        break;
    case 3:
        message.setText("{\"status\":\"SUSPENDED\",\"id\":\"0000039-130618221729631-oozie-oozi-W\","
                + "\"startTime\":1342915200000,\"parentId\":\"0000025-130618221729631-oozie-oozi-C@1\"}");
        break;
    default:
    }
    return message;
}

From source file:org.apache.falcon.messaging.JMSMessageConsumerTest.java

private Message getMockOozieCoordMessage(int i, Session session, boolean isFalconWF)
        throws FalconException, JMSException {
    TextMessage message = session.createTextMessage();
    message.setStringProperty("appType", "COORDINATOR_ACTION");
    if (isFalconWF) {
        message.setStringProperty("appName", "FALCON_PROCESS_DEFAULT_process1");
    } else {/*from w  w  w  .j  av  a 2 s  .co  m*/
        message.setStringProperty("appName", "OozieSampleShellWF");
    }
    message.setStringProperty("user", "falcon");
    switch (i % 5) {
    case 0:
        message.setText("{\"status\":\"WAITING\",\"nominalTime\":1310342400000,\"missingDependency\""
                + ":\"hdfs://gsbl90107.blue.com:8020/user/john/dir1/file1\","
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\",\"startTime\":1342915200000,"
                + "\"parentId\":\"0000025-130618221729631-oozie-oozi-C\"}");
        message.setStringProperty("eventStatus", "WAITING");
        break;
    case 1:
        message.setText("{\"status\":\"RUNNING\",\"nominalTime\":1310342400000,"
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\","
                + "\"startTime\":1342915200000,\"parentId\":\"0000025-130618221729631-oozie-oozi-C\"}");
        message.setStringProperty("eventStatus", "STARTED");
        break;
    case 2:
        message.setText("{\"status\":\"SUCCEEDED\",\"nominalTime\":1310342400000,"
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\","
                + "\"startTime\":1342915200000,\"parentId\":\"0000025-130618221729631-oozie-oozi-C\","
                + "\"endTime\":1366677082799}");
        message.setStringProperty("eventStatus", "SUCCESS");
        break;
    case 3:
        message.setText("{\"status\":\"FAILED\",\"errorCode\":\"E0101\",\"errorMessage\":"
                + "\"dummyError\",\"nominalTime\":1310342400000,"
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\",\"startTime\":1342915200000,"
                + "\"parentId\":\"0000025-130618221729631-oozie-oozi-C\",\"endTime\":1366677140818}");
        message.setStringProperty("eventStatus", "FAILURE");
        break;
    case 4:
        message.setText("{\"status\":\"TIMEDOUT\",\"nominalTime\":1310342400000,"
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\",\"startTime\":1342915200000,"
                + "\"parentId\":\"0000025-130618221729631-oozie-oozi-C\",\"endTime\":1366677140818}");
        message.setStringProperty("eventStatus", "FAILURE");
    default:
    }
    return message;
}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putQueue(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();// w w w.  j ava 2  s  . co m

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putTopic(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();//from  w  ww  .ja  v a2  s.  com

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.apache.qpid.disttest.client.MessageProvider.java

protected Message createTextMessage(Session ssn, final CreateProducerCommand command) throws JMSException {
    String payload = getMessagePayload(command);

    TextMessage msg = null;/*from   w  ww .  j  a va2s.  c o m*/
    synchronized (ssn) {
        msg = ssn.createTextMessage();
    }
    msg.setText(payload);

    return msg;
}