Example usage for javax.jms QueueSender send

List of usage examples for javax.jms QueueSender send

Introduction

In this page you can find the example usage for javax.jms QueueSender send.

Prototype


void send(Message message) throws JMSException;

Source Link

Document

Sends a message to the queue.

Usage

From source file:org.apache.stratos.status.monitor.agent.clients.service.CEPServerClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.CEP);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.CEP_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        InitialContext ctx;//from ww w .ja v a  2s  . c  o m
        try {
            ctx = new InitialContext(properties);

            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_CEP + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();
            if (log.isDebugEnabled()) {
                log.debug("Message in the execute() of CEPServer Client: " + message.getText());
            }
            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send or retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "JMS Exception in inserting stats into the DB for the CEPServerClient";
            log.warn(msg, e);
        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming Exception in inserting stats into the DB for the CEPServerClient";
            log.warn(msg, e);
        }
    }
}

From source file:org.apache.stratos.status.monitor.agent.clients.service.MessageBrokerServiceClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.MESSAGING);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.MESSAGING_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        if (log.isDebugEnabled()) {
            log.debug("getTCPConnectionURL(username,password) = "
                    + getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));
        }//from  w  ww.  jav a2  s .  c o m
        try {
            InitialContext ctx = new InitialContext(properties);
            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_MB + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();

            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send and retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Exception in executing the client - "
                    + "Status Monitor Agent for MessageBrokerServiceClient";
            log.warn(msg, e);

        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming exception in executing the client - "
                    + "Status Monitor agent for MessageBrokerServiceClient";
            log.warn(msg, 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();/* w w w .  jav  a  2s.  c  o 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.grouter.common.jms.QueueListenerDestination.java

/**
 * <br>//  w w w.j a v  a 2  s .c  o  m
 */
public void sendReplyToTemporaryDestination(Message request) {
    TemporaryQueue replyQueue = null;
    QueueSender tempsender = null;
    String temporaryDestinationName = null;
    try {
        if (request.getJMSReplyTo() == null) {
            throw new IllegalStateException("The sender of this message has not entered a JMSReplyTo field - "
                    + "impossible to send reply on temporary destination!!");
        }
        temporaryDestinationName = request.getJMSReplyTo().toString();
        request.setJMSCorrelationID(temporaryDestinationName);
        replyQueue = (TemporaryQueue) request.getJMSReplyTo();
        tempsender = queueSession.createSender(replyQueue);
        tempsender.send(request);
        logger.debug("Created a tempsender and sent reply to " + replyQueue);
    } catch (JMSException ex) {
        //ignore
        logger.warn("Failed sending reply on temporary destination : " + temporaryDestinationName);
    } finally {
        try {
            if (tempsender != null) {
                tempsender.close();
            }
            if (replyQueue != null) {
                replyQueue.delete();
            }
        } catch (JMSException ex1) {
            //ignore
        }
    }
}

From source file:org.sample.jms.SampleQueueSender.java

public void sendMessages() throws NamingException, JMSException {

    PropertyConfigurator.configure("log4j.properties");
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
    properties.put(QUEUE_NAME_PREFIX + queueName, queueName);
    InitialContext ctx = new InitialContext(properties);
    // Lookup connection factory
    QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
    queueConnection = connFactory.createQueueConnection();
    queueConnection.start();//from  w ww  .  ja  v  a  2s. co  m
    queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    Queue queue = (Queue) ctx.lookup(queueName);
    QueueSender queueSender = queueSession.createSender(queue);
    TextMessage textMessage;

    for (long i = 0; i < RECORD_COUNT; i++) {
        // create the message to send
        textMessage = queueSession.createTextMessage("Test Message Content" + messageCount);
        // Send message
        queueSender.send(textMessage);
        messageCount++;
    }
    queueSender.close();
    queueSession.close();
    queueConnection.close();
}

From source file:org.socraticgrid.taskmanager.TaskManagerImpl.java

/**
 * Queue the message to the task handler.
 *
 * @param msgObject//from   w  w w.  j  a v  a  2 s.co m
 * @return
 */
private QueueResponse queueMessage(java.io.Serializable msgObject) {
    QueueResponse response = new QueueResponse();
    String taskQ = null;
    QueueConnection queueConnection = null;

    try {
        //Get task queue name & queue factory
        taskQ = PropertyAccessor.getProperty(TASKMANAGER_PROPERTY_FILE, PROPERTY_TASK_QUEUE);
        String taskQFactory = PropertyAccessor.getProperty(TASKMANAGER_PROPERTY_FILE,
                PROPERTY_TASK_QUEUE_FACTORY);

        //Get queue connection
        Context jndiContext = new InitialContext();
        QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
                .lookup(taskQFactory);
        Queue queue = (Queue) jndiContext.lookup(taskQ);

        //Create connection session
        queueConnection = queueConnectionFactory.createQueueConnection();
        QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueSender queueSender = queueSession.createSender(queue);

        //Create message
        ObjectMessage message = queueSession.createObjectMessage(msgObject);

        //Send message
        queueSender.send(message);

        //Set response info
        response.ticket = message.getJMSMessageID();
        response.detail = TASK_MESSAGE_SUCCESS;
    } catch (PropertyAccessException pae) {
        String msg = TASK_MESSAGE_FAILURE + ": error accessing task properties in file:"
                + TASKMANAGER_PROPERTY_FILE + ".";
        log.error(msg, pae);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } catch (NamingException ne) {
        String msg = TASK_MESSAGE_FAILURE + ": error creating connection to queue: " + taskQ + ".";
        log.error(msg, ne);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } catch (JMSException jmse) {
        String msg = TASK_MESSAGE_FAILURE + ": error occurred trying to send notificaiton to task queue: "
                + taskQ + ".";
        log.error(msg, jmse);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } finally {
        //Close queue
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }

    return response;
}

From source file:org.wso2.carbon.oc.agent.publisher.mb.MBPublisher.java

/**
 * @param queueName   - String mb queue name
 * @param jsonMessage - String mb queue message json string
 *///w w  w  . ja v  a 2  s  .  co m
public void sendMessages(String queueName, String jsonMessage) {

    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(username, password));
        properties.put(QUEUE_NAME_PREFIX + queueName, queueName);
        InitialContext ctx = new InitialContext(properties);
        // lookup connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        QueueConnection queueConnection = connFactory.createQueueConnection();
        queueConnection.start();
        QueueSession queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        // send message
        Queue queue = (Queue) ctx.lookup(queueName);
        // create the message to send

        TextMessage textMessage = queueSession.createTextMessage(jsonMessage);
        QueueSender queueSender = queueSession.createSender(queue);
        queueSender.send(textMessage);
        queueSender.close();
        queueSession.close();
        queueConnection.close();
    } catch (JMSException e) {
        logger.error("MBPublisher connection down", e);
    } catch (NamingException e) {
        logger.error("Naming error", e);
    }

}