Example usage for javax.jms QueueConnection close

List of usage examples for javax.jms QueueConnection close

Introduction

In this page you can find the example usage for javax.jms QueueConnection close.

Prototype


void close() throws JMSException;

Source Link

Document

Closes the connection.

Usage

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

/**
 * Main method.//from   www .  ja v  a2s .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.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 w  w  w. ja v  a  2  s . 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  www .ja  va2s. co  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 testJmsRecordWriter() throws Exception {
    Context jndiContext = getJndiContext();
    Queue queue = (Queue) jndiContext.lookup("q");
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
            .lookup("QueueConnectionFactory");
    QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
    QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    queueConnection.start();/*from  ww w  . j  av a 2  s.com*/

    String dataSource = "foo" + LINE_SEPARATOR + "bar";

    aNewJob().reader(new StringRecordReader(dataSource)).processor(new JmsMessageTransformer(queueSession))
            .writer(new JmsQueueRecordWriter(queueConnectionFactory, queue)).call();

    // Assert that queue contains 2 messages: "foo" and "bar"
    QueueBrowser queueBrowser = queueSession.createBrowser(queue);
    Enumeration enumeration = queueBrowser.getEnumeration();

    assertThat(enumeration.hasMoreElements()).isTrue();
    TextMessage message1 = (TextMessage) enumeration.nextElement();
    assertThat(message1.getText()).isEqualTo("foo");

    assertThat(enumeration.hasMoreElements()).isTrue();
    TextMessage message2 = (TextMessage) enumeration.nextElement();
    assertThat(message2.getText()).isEqualTo("bar");

    assertThat(enumeration.hasMoreElements()).isFalse();

    queueSession.close();
    queueConnection.close();
}

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

/**
 * Queue the message to the task handler.
 *
 * @param msgObject//from  w  ww .j  a va  2s  .  c om
 * @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.andes.core.QueueManagerServiceImpl.java

/**
 * Publish message to given JMS queue/*w w w.ja v  a2s .c  om*/
 *
 * @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);
        }
    }
}

From source file:org.wso2.carbon.integration.test.client.JMSPublisherClient.java

/**
 * This method will publish the data in the test data file to the given queue via ActiveMQ message broker
 *
 * @param queueName             the queue which the messages should be published under
 * @param messageFormat         messageFormat of the test data file
 * @param testCaseFolderName    Testcase folder name which is in the test artifacts folder
 * @param dataFileName          data file name with the extension to be read
 *
 *//*w w  w.  j  ava  2  s  .  co  m*/
public static void publishToQueue(String queueName, String messageFormat, String testCaseFolderName,
        String dataFileName) throws JMSException, IOException, NamingException {

    //create connection
    Properties properties = new Properties();
    properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
    Context context = new InitialContext(properties);
    QueueConnectionFactory connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
    QueueConnection queueConnection = connFactory.createQueueConnection();
    queueConnection.start();
    Session session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(queueName);
    MessageProducer producer = session.createProducer(queue);

    //publish data
    String filePath = getTestDataFileLocation(testCaseFolderName, dataFileName);
    List<String> messagesList = readFile(filePath);
    if (messageFormat.equalsIgnoreCase("map")) {
        publishMapMessages(producer, session, messagesList);
    } else {
        publishTextMessage(producer, session, messagesList);
    }

    //close connection
    producer.close();
    session.close();
    queueConnection.stop();
    queueConnection.close();
}

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
 *//*from   w w w .  ja va 2 s .  c om*/
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);
    }

}

From source file:org.wso2.carbon.sample.consumer.JMSQueueMessageConsumer.java

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {/*w  w  w  .j ava 2  s .  c om*/
        queueConnection = queueConnectionFactory.createQueueConnection();

        queueConnection.start();
    } catch (JMSException e) {
        log.info("Can not create queue connection." + e);
        return;
    }
    Session session = null;
    try {

        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(destination);

        int count = 0;
        long totalLatency = 0;
        long lastTimestamp = System.currentTimeMillis();

        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                //                    if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                long currentTime = System.currentTimeMillis();
                long sentTimestamp = (Long) mapMessage.getObject("time");

                totalLatency = totalLatency + (currentTime - sentTimestamp);

                int logCount = 1000;

                if ((count % logCount == 0) && (count > warmUpCount)) {
                    double rate = (logCount * 1000.0d / (System.currentTimeMillis() - lastTimestamp));
                    log.info("Consumer: " + consumerId + " (" + logCount + " received) rate: " + rate
                            + " Latency:" + (totalLatency / (logCount * 1.0d)));
                    //                            log.info("total latency:" + totalLatency);
                    log.info("Total rate: " + (int) (consumers * rate));
                    totalLatency = 0;
                    lastTimestamp = System.currentTimeMillis();
                }
                count++;
            }
        }
        log.info("Finished listening for messages.");

    } catch (JMSException e) {
        log.info("Can not subscribe." + e);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                log.error(e);
            }
        }
        try {
            queueConnection.stop();
            queueConnection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.wso2.carbon.sample.consumer.QueueConsumer.java

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {/*from   w w  w.j a  va 2s  . c  om*/
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueConnection.start();
    } catch (JMSException e) {
        log.error("Can not create queue connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {
        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    log.info("Received Map Message : " + map);
                } else if (message instanceof TextMessage) {
                    log.info("Received Text Message : " + ((TextMessage) message).getText());
                } else {
                    log.info("Received message : " + message.toString());
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        queueConnection.stop();
        queueConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}