Example usage for javax.jms QueueConnection createQueueSession

List of usage examples for javax.jms QueueConnection createQueueSession

Introduction

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

Prototype

QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException;

Source Link

Document

Creates a QueueSession object, specifying transacted and acknowledgeMode .

Usage

From source file:org.dawnsci.commandserver.mx.example.ActiveMQProducer.java

public static void main(String[] args) throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade
            .createConnectionFactory("tcp://ws097.diamond.ac.uk:61616");
    Connection send = connectionFactory.createConnection();

    Session session = send.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("testQ");

    final MessageProducer producer = session.createProducer(queue);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    Message message = session.createTextMessage("Hello World");
    producer.send(message);/*from   w w  w.j  a  va2s  . c  o m*/

    message = session.createTextMessage("...and another message");
    producer.send(message);

    message = session.createObjectMessage(new TestObjectBean("this could be", "anything"));
    producer.send(message);

    // Test JSON
    SweepBean col = new SweepBean("fred", "d0000000001", 0, 100);

    ObjectMapper mapper = new ObjectMapper();
    String jsonString = mapper.writeValueAsString(col);

    message = session.createTextMessage(jsonString);
    producer.send(message);

    producer.close();
    session.close();
    send.close();

    // Now we peak at the queue
    // If the consumer is not going, the messages should still be there
    if (REQUIRE_PEAK) {
        QueueConnection qCon = connectionFactory.createQueueConnection();
        QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queue = qSes.createQueue("testQ");
        qCon.start();

        QueueBrowser qb = qSes.createBrowser(queue);
        Enumeration e = qb.getEnumeration();
        if (e.hasMoreElements())
            System.out.println("Peak at queue:");
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;
                System.out.println(t.getText());
            } else if (m instanceof ObjectMessage) {
                ObjectMessage o = (ObjectMessage) m;
                System.out.println(o.getObject());
            }
        }

        qb.close();
        qSes.close();
        qCon.close();
    }

}

From source file:io.datalayer.activemq.consumer.SimpleQueueReceiver.java

/**
 * Main method./*from w  ww .  j a va  2 s  . c o m*/
 * 
 * @param args the queue used by the example
 */
public static void main(String... args) {
    String queueName = null;
    Context jndiContext = null;
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
    QueueReceiver queueReceiver = null;
    TextMessage message = null;

    /*
     * Read queue name from command line and display it.
     */
    if (args.length != 1) {
        LOG.info("Usage: java " + "SimpleQueueReceiver <queue-name>");
        System.exit(1);
    }
    queueName = args[0];
    LOG.info("Queue name is " + queueName);

    /*
     * 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.toString());
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create receiver, then start message
     * delivery. Receive all text messages from queue until a non-text
     * message is received indicating end of message stream. Close
     * connection.
     */
    try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueReceiver = queueSession.createReceiver(queue);
        queueConnection.start();
        while (true) {
            Message m = queueReceiver.receive(1);
            if (m != null) {
                if (m instanceof TextMessage) {
                    message = (TextMessage) m;
                    LOG.info("Reading message: " + message.getText());
                } else {
                    break;
                }
            }
        }
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e.toString());
    } finally {
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }
}

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

/**
 * Main method./*from  www .  j a  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:io.datalayer.activemq.producer.SimpleQueueSender.java

/**
 * Main method.//from   w  w  w. j  av  a  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.tutorials.advanced.jms.JMSUtil.java

public static void initJMSFactory() throws Exception {

    Properties p = new Properties();
    p.load(JMSUtil.class.getResourceAsStream(("/org/easybatch/tutorials/advanced/jms/jndi.properties")));
    Context jndiContext = new InitialContext(p);

    queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
    queue = (Queue) jndiContext.lookup("q");

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

}

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  . j a v  a 2  s.c om
        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. j  a v a 2  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.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
 *
 *//*from   w w  w. j a v  a  2 s. c  om*/
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.panksdmz.jms.tibco.MessageRecieverBean.java

public void recieve() {
    try {//from  ww w . j  a va2s.c  o m
        QueueConnection connection = connectionFactory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(this.recieveQueueName);
        QueueReceiver receiver = session.createReceiver(queue);
        connection.start();

        Message receive = receiver.receive();

        System.out.println(receive);

    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:org.panksdmz.jms.tibco.MessageSenderBean.java

public void send() {
    try {//from ww w  . j a v  a  2  s.c  o m
        QueueConnection connection = connectionFactory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(sendQueueName);
        QueueSender sender = session.createSender(queue);
        TextMessage message = session
                .createTextMessage("Message @ " + CaliHDateTime.now().getTimeInMillis() + " from thread "
                        + Thread.currentThread().getId() + " from session [" + session.toString() + "]");

        sender.send(message);
        session.close();

    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}