Example usage for javax.jms QueueSession createTextMessage

List of usage examples for javax.jms QueueSession createTextMessage

Introduction

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

Prototype


TextMessage createTextMessage() throws JMSException;

Source Link

Document

Creates a TextMessage object.

Usage

From source file:io.datalayer.activemq.producer.SimpleQueueSender.java

/**
 * Main method.//from w  ww . j  av  a 2  s.  c om
 * 
 * @param args the queue used by the example and, optionally, the number of
 *                messages to send
 */
public static void main(String... args) {
    String queueName = null;
    Context jndiContext = null;
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
    QueueSender queueSender = null;
    TextMessage message = null;
    final int numMsgs;

    if ((args.length < 1) || (args.length > 2)) {
        LOG.info("Usage: java SimpleQueueSender " + "<queue-name> [<number-of-messages>]");
        System.exit(1);
    }
    queueName = args[0];
    LOG.info("Queue name is " + queueName);
    if (args.length == 2) {
        numMsgs = (new Integer(args[1])).intValue();
    } else {
        numMsgs = 1;
    }

    /*
     * Create a JNDI API InitialContext object if none exists yet.
     */
    try {
        jndiContext = new InitialContext();
    } catch (NamingException e) {
        LOG.info("Could not create JNDI API context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and queue. If either does not exist, exit.
     */
    try {
        queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
        queue = (Queue) jndiContext.lookup(queueName);
    } catch (NamingException e) {
        LOG.info("JNDI API lookup failed: " + e);
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create sender and text message. Send
     * messages, varying text slightly. Send end-of-messages message.
     * Finally, close connection.
     */
    try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        message = queueSession.createTextMessage();
        for (int i = 0; i < numMsgs; i++) {
            message.setText("This is message " + (i + 1));
            LOG.info("Sending message: " + message.getText());
            queueSender.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        queueSender.send(queueSession.createMessage());
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e.toString());
    } finally {
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:nl.nn.adapterframework.extensions.ifsa.jms.IfsaFacade.java

/**
 * Sends a message,and if transacted, the queueSession is committed.
 * <p>This method is intended for <b>clients</b>, as <b>server</b>s
 * will use the <code>sendReply</code>.
 * @return the correlationID of the sent message
 *///from   w ww  .j av a 2  s. c o m
public TextMessage sendMessage(QueueSession session, QueueSender sender, String message, Map udzMap,
        String bifName, byte btcData[]) throws IfsaException {

    try {
        if (!isRequestor()) {
            throw new IfsaException(getLogPrefix() + "Provider cannot use sendMessage, should use sendReply");
        }
        IFSATextMessage msg = (IFSATextMessage) session.createTextMessage();
        msg.setText(message);
        if (udzMap != null && msg instanceof IFSAMessage) {
            // Handle UDZs
            log.debug(getLogPrefix() + "add UDZ map to IFSAMessage");
            // process the udzMap
            Map udzObject = (Map) ((IFSAMessage) msg).getOutgoingUDZObject();
            udzObject.putAll(udzMap);
        }
        String replyToQueueName = "-";
        //Client side
        if (messageProtocol.equals(IfsaMessageProtocolEnum.REQUEST_REPLY)) {
            // set reply-to address
            Queue replyTo = getMessagingSource().getClientReplyQueue(session);
            msg.setJMSReplyTo(replyTo);
            replyToQueueName = replyTo.getQueueName();
        }
        if (messageProtocol.equals(IfsaMessageProtocolEnum.FIRE_AND_FORGET)) {
            // not applicable
        }
        if (StringUtils.isNotEmpty(bifName)) {
            msg.setBifName(bifName);
        }
        if (btcData != null && btcData.length > 0) {
            msg.setBtcData(btcData);
        }

        if (log.isDebugEnabled()) {
            log.debug(getLogPrefix() + " messageProtocol [" + messageProtocol + "] replyToQueueName ["
                    + replyToQueueName + "] sending message [" + message + "]");
        } else {
            if (log.isInfoEnabled()) {
                log.info(getLogPrefix() + " messageProtocol [" + messageProtocol + "] replyToQueueName ["
                        + replyToQueueName + "] sending message");
            }
        }

        // send the message
        sender.send(msg);

        // perform commit
        if (isJmsTransacted() && !(messagingSource.isXaEnabledForSure() && JtaUtil.inTransaction())) {
            session.commit();
            log.debug(getLogPrefix() + "committing (send) transaction");
        }

        return msg;

    } catch (Exception e) {
        throw new IfsaException(e);
    }
}

From source file:nl.nn.adapterframework.extensions.ifsa.jms.IfsaFacade.java

/**
 * Intended for server-side reponse sending and implies that the received
 * message *always* contains a reply-to address.
 *//*from w  w w. j a  va  2s .  co  m*/
public void sendReply(QueueSession session, Message received_message, String response) throws IfsaException {
    QueueSender tqs = null;
    try {
        TextMessage answer = session.createTextMessage();
        answer.setText(response);
        Queue replyQueue = (Queue) received_message.getJMSReplyTo();
        tqs = session.createSender(replyQueue);
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "sending reply to [" + received_message.getJMSReplyTo() + "]");
        ((IFSAServerQueueSender) tqs).sendReply(received_message, answer);
    } catch (Throwable t) {
        throw new IfsaException(t);
    } finally {
        if (tqs != null) {
            try {
                tqs.close();
            } catch (JMSException e) {
                log.warn(getLogPrefix() + "exception closing reply queue sender", e);
            }
        }
    }
}

From source file:org.apache.activemq.demo.SimpleQueueSender.java

/**
 * Main method./*from ww  w  .  j  ava 2  s .c  o  m*/
 *
 * @param args the queue used by the example and, optionally, the number of
 *                messages to send
 */
public static void main(String[] args) {
    String queueName = null;
    Context jndiContext = null;
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
    QueueSender queueSender = null;
    TextMessage message = null;
    final int numMsgs;

    if ((args.length < 1) || (args.length > 2)) {
        LOG.info("Usage: java SimpleQueueSender " + "<queue-name> [<number-of-messages>]");
        System.exit(1);
    }
    queueName = args[0];
    LOG.info("Queue name is " + queueName);
    if (args.length == 2) {
        numMsgs = (new Integer(args[1])).intValue();
    } else {
        numMsgs = 1;
    }

    /*
     * Create a JNDI API InitialContext object if none exists yet.
     */
    try {
        jndiContext = new InitialContext();
    } catch (NamingException e) {
        LOG.info("Could not create JNDI API context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and queue. If either does not exist, exit.
     */
    try {
        queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
        queue = (Queue) jndiContext.lookup(queueName);
    } catch (NamingException e) {
        LOG.info("JNDI API lookup failed: " + e);
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create sender and text message. Send
     * messages, varying text slightly. Send end-of-messages message.
     * Finally, close connection.
     */
    try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        message = queueSession.createTextMessage();
        for (int i = 0; i < numMsgs; i++) {
            message.setText("This is message " + (i + 1));
            LOG.info("Sending message: " + message.getText());
            queueSender.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        queueSender.send(queueSession.createMessage());
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e.toString());
    } finally {
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:org.easybatch.jms.JmsIntegrationTest.java

@Test
public void testJmsSupport() throws Exception {
    Context jndiContext = getJndiContext();
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
            .lookup("QueueConnectionFactory");
    Queue queue = (Queue) jndiContext.lookup("q");

    QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
    QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    QueueSender queueSender = queueSession.createSender(queue);
    queueConnection.start();//from   ww  w .j a va 2 s  .  co  m

    //send a regular message to the queue
    TextMessage message = queueSession.createTextMessage();
    message.setText(MESSAGE_TEXT);
    queueSender.send(message);

    //send a poison record to the queue
    queueSender.send(new JmsPoisonMessage());

    Job job = aNewJob().reader(new JmsQueueRecordReader(queueConnectionFactory, queue))
            .filter(new JmsPoisonRecordFilter()).processor(new RecordCollector())
            .jobListener(new JmsQueueSessionListener(queueSession))
            .jobListener(new JmsQueueConnectionListener(queueConnection)).build();

    JobReport jobReport = JobExecutor.execute(job);

    assertThat(jobReport).isNotNull();
    assertThat(jobReport.getParameters().getDataSource()).isEqualTo(EXPECTED_DATA_SOURCE_NAME);
    assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(2);
    assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(1);
    assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(1);

    List<JmsRecord> records = (List<JmsRecord>) jobReport.getResult();

    assertThat(records).isNotNull().isNotEmpty().hasSize(1);

    JmsRecord jmsRecord = records.get(0);
    Header header = jmsRecord.getHeader();
    assertThat(header).isNotNull();
    assertThat(header.getNumber()).isEqualTo(1);
    assertThat(header.getSource()).isEqualTo(EXPECTED_DATA_SOURCE_NAME);

    Message payload = jmsRecord.getPayload();
    assertThat(payload).isNotNull().isInstanceOf(TextMessage.class);

    TextMessage textMessage = (TextMessage) payload;
    assertThat(textMessage.getText()).isNotNull().isEqualTo(MESSAGE_TEXT);

}

From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java

/**
 * Publish message to given JMS queue/*w  w w. ja v a 2 s. c  o m*/
 *
 * @param nameOfQueue queue name
 * @param userName username
 * @param accessKey access key
 * @param jmsType jms type
 * @param jmsCorrelationID message correlation id
 * @param numberOfMessages number of messages to publish
 * @param message message body
 * @param deliveryMode delivery mode
 * @param priority message priority
 * @param expireTime message expire time
 * @throws QueueManagerException
 */
private void send(String nameOfQueue, String userName, String accessKey, String jmsType,
        String jmsCorrelationID, int numberOfMessages, String message, int deliveryMode, int priority,
        long expireTime) throws QueueManagerException {
    QueueConnectionFactory connFactory;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    QueueSender queueSender = null;
    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, Utils.getTCPConnectionURL(userName, accessKey));
        properties.put(QUEUE_NAME_PREFIX + nameOfQueue, nameOfQueue);
        properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
        InitialContext ctx = new InitialContext(properties);
        connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        Queue queue = (Queue) ctx.lookup(nameOfQueue);
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        queueConnection.start();
        TextMessage textMessage = queueSession.createTextMessage();
        if (queueSender != null && textMessage != null) {
            if (jmsType != null) {
                textMessage.setJMSType(jmsType);
            }
            if (jmsCorrelationID != null) {
                textMessage.setJMSCorrelationID(jmsCorrelationID);
            }

            if (message != null) {
                textMessage.setText(message);
            } else {
                textMessage.setText("Type message here..");
            }

            for (int i = 0; i < numberOfMessages; i++) {
                queueSender.send(textMessage, deliveryMode, priority, expireTime);
            }
        }
    } catch (FileNotFoundException | NamingException | UnknownHostException | XMLStreamException
            | JMSException e) {
        throw new QueueManagerException("Unable to send message.", e);
    } finally {
        try {
            if (queueConnection != null) {
                queueConnection.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue connection", e);
        }
        try {
            if (queueSession != null) {
                queueSession.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue session", e);
        }
        try {
            if (queueSender != null) {
                queueSender.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue sender", e);
        }
    }
}