Example usage for javax.jms Session createConsumer

List of usage examples for javax.jms Session createConsumer

Introduction

In this page you can find the example usage for javax.jms Session createConsumer.

Prototype


MessageConsumer createConsumer(Destination destination) throws JMSException;

Source Link

Document

Creates a MessageConsumer for the specified destination.

Usage

From source file:example.tempdest.ProducerRequestReply.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();/*  w  w  w  .j a  v a 2  s . c om*/
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test-queue");
        MessageProducer producer = session.createProducer(destination);
        Destination replyDest = session.createTemporaryQueue();

        // set up the consumer to handle the reply
        MessageConsumer replyConsumer = session.createConsumer(replyDest);
        replyConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                System.out.println("*** REPLY *** ");
                System.out.println(message.toString());
            }
        });

        TextMessage message = session.createTextMessage("I need a response for this, please");
        message.setJMSReplyTo(replyDest);

        producer.send(message);

        // wait for a response
        TimeUnit.SECONDS.sleep(2);
        producer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:example.wildcard.Client.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();//from  w ww. j av a 2 s .  c  o m
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {
        Topic senderTopic = new ActiveMQTopic(System.getProperty("topicName"));

        connection = connectionFactory.createConnection("admin", "password");

        Session senderSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        MessageProducer sender = senderSession.createProducer(senderTopic);

        Session receiverSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);

        String policyType = System.getProperty("wildcard", ".*");
        String receiverTopicName = senderTopic.getTopicName() + policyType;
        Topic receiverTopic = receiverSession.createTopic(receiverTopicName);

        MessageConsumer receiver = receiverSession.createConsumer(receiverTopic);
        receiver.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        String text = ((TextMessage) message).getText();
                        System.out.println("We received a new message: " + text);
                    }
                } catch (JMSException e) {
                    System.out.println("Could not read the receiver's topic because of a JMSException");
                }
            }
        });

        connection.start();
        System.out.println("Listening on '" + receiverTopicName + "'");
        System.out.println("Enter a message to send: ");

        Scanner inputReader = new Scanner(System.in);

        while (true) {
            String line = inputReader.nextLine();
            if (line == null) {
                System.out.println("Done!");
                break;
            } else if (line.length() > 0) {
                try {
                    TextMessage message = senderSession.createTextMessage();
                    message.setText(line);
                    System.out.println("Sending a message: " + message.getText());
                    sender.send(message);
                } catch (JMSException e) {
                    System.out.println("Exception during publishing a message: ");
                }
            }
        }

        receiver.close();
        receiverSession.close();
        sender.close();
        senderSession.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("When trying to close connection: ");
            }
        }
    }

}

From source file:example.composite.dest.Consumer.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();//from   w  w  w .  j a v  a 2 s . c  o m
    }
    System.out.println("\nWaiting to receive messages... will timeout after " + TIMEOUT / 1000 + "s");
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test-queue");
        Destination destinationFoo = session.createQueue("test-queue-foo");
        Destination destinationBar = session.createQueue("test-queue-bar");
        Destination destinationTopicFoo = session.createTopic("test-topic-foo");

        MessageConsumer consumer = session.createConsumer(destination);
        MessageConsumer consumerFoo = session.createConsumer(destinationFoo);
        MessageConsumer consumerBar = session.createConsumer(destinationBar);
        MessageConsumer consumerTopicFoo = session.createConsumer(destinationTopicFoo);

        int i = 0;
        while (true) {
            Message message = consumer.receive(TIMEOUT);

            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    System.out.println("Got " + i++ + ". message on test-queue: " + text);
                }
            } else {
                break;
            }

            message = consumerFoo.receive(TIMEOUT);

            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    System.out.println("Got " + i++ + ". message on test-queue-foo: " + text);
                }
            } else {
                break;
            }

            message = consumerBar.receive(TIMEOUT);

            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    System.out.println("Got " + i++ + ". message on test-queue-bar: " + text);
                }
            } else {
                break;
            }

            message = consumerTopicFoo.receive(TIMEOUT);

            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    System.out.println("Got " + i++ + ". message on test-topic-bar: " + text);
                }
            } else {
                break;
            }

        }

        consumer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

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

/**
 * @param args the queue used by the example
 *///from  w ww. ja  v a 2 s  .  c  o  m
public static void main(String[] args) {
    String destinationName = null;
    Context jndiContext = null;
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    Destination destination = null;
    MessageConsumer consumer = null;

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

    /*
     * Create a JNDI API InitialContext object
     */
    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 destination.
     */
    try {
        connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
        destination = (Destination) jndiContext.lookup(destinationName);
    } 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 destination until a non-text
     * message is received indicating end of message stream. Close
     * connection.
     */
    try {
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumer = session.createConsumer(destination);
        connection.start();
        while (true) {
            Message m = consumer.receive(1);
            if (m != null) {
                if (m instanceof TextMessage) {
                    TextMessage message = (TextMessage) m;
                    LOG.info("Reading message: " + message.getText());
                } else {
                    break;
                }
            }
        }
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
}

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

/**
 * @param args the queue used by the example
 *///from   w ww . ja v  a  2 s.  co m
public static void main(String... args) {
    String destinationName = null;
    Context jndiContext = null;
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    Destination destination = null;
    MessageConsumer consumer = null;

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

    /*
     * Create a JNDI API InitialContext object
     */
    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 destination.
     */
    try {
        connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
        destination = (Destination) jndiContext.lookup(destinationName);
    } 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 destination until a non-text
     * message is received indicating end of message stream. Close
     * connection.
     */
    try {
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumer = session.createConsumer(destination);
        connection.start();
        while (true) {
            Message m = consumer.receive(1);
            if (m != null) {
                if (m instanceof TextMessage) {
                    TextMessage message = (TextMessage) m;
                    LOG.info("Reading message: " + message.getText());
                } else {
                    break;
                }
            }
        }
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:org.firstopen.singularity.util.JMSUtil.java

public static Connection registerListenerOnQueue(MessageListener listener, String queueName) throws Exception {
    InitialContext jndiContext = JNDIUtil.getInitialContext();
    Queue queue = (Queue) jndiContext.lookup("queue/" + queueName);
    ConnectionFactory qcf = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
    Connection connection = qcf.createConnection();
    Session m_session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer m_receiver = m_session.createConsumer(queue);
    m_receiver.setMessageListener(listener);
    return connection;
}

From source file:test.SecureSampleApp.java

private static String sendMessage(final String encryptedMessage) {
    return template.execute(new SessionCallback<String>() {
        @Override/*from   ww  w . jav a  2  s.c o m*/
        public String doInJms(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(encryptedMessage);
            Queue outQueue = session.createQueue("receive");
            Destination inDest = session.createTemporaryQueue();
            String correlationID = UUID.randomUUID().toString();
            message.setJMSReplyTo(inDest);
            message.setJMSCorrelationID(correlationID);
            MessageProducer producer = session.createProducer(outQueue);
            producer.send(outQueue, message);
            return ((TextMessage) session.createConsumer(inDest).receive(10000)).getText();
        }
    }, true);
}

From source file:nl.nn.adapterframework.extensions.esb.EsbUtils.java

public static String receiveMessageAndMoveToErrorStorage(EsbJmsListener esbJmsListener,
        JdbcTransactionalStorage errorStorage) {
    String result = null;//from   w  ww.ja v a2  s .c o m

    PoolingConnectionFactory jmsConnectionFactory = null;
    PoolingDataSource jdbcDataSource = null;
    BitronixTransactionManager btm = null;
    javax.jms.Connection jmsConnection = null;

    try {
        jmsConnectionFactory = getPoolingConnectionFactory(esbJmsListener);
        if (jmsConnectionFactory != null) {
            jdbcDataSource = getPoolingDataSource(errorStorage);
            if (jdbcDataSource != null) {
                String instanceNameLc = AppConstants.getInstance().getString("instance.name.lc", null);
                String logDir = AppConstants.getInstance().getString("log.dir", null);
                TransactionManagerServices.getConfiguration().setServerId(instanceNameLc + ".tm");
                TransactionManagerServices.getConfiguration()
                        .setLogPart1Filename(logDir + File.separator + instanceNameLc + "-btm1.tlog");
                TransactionManagerServices.getConfiguration()
                        .setLogPart2Filename(logDir + File.separator + instanceNameLc + "-btm2.tlog");
                btm = TransactionManagerServices.getTransactionManager();

                jmsConnection = jmsConnectionFactory.createConnection();

                Session jmsSession = null;
                MessageConsumer jmsConsumer = null;

                java.sql.Connection jdbcConnection = null;

                btm.begin();
                log.debug("started transaction [" + btm.getCurrentTransaction().getGtrid() + "]");

                try {
                    jmsSession = jmsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
                    String queueName = esbJmsListener.getPhysicalDestinationShortName();
                    Queue queue = jmsSession.createQueue(queueName);
                    jmsConsumer = jmsSession.createConsumer(queue);

                    jmsConnection.start();

                    long timeout = 30000;
                    log.debug("looking for message on queue [" + queueName + "] with timeout of [" + timeout
                            + "] msec");
                    Message rawMessage = jmsConsumer.receive(timeout);

                    if (rawMessage == null) {
                        log.debug("no message found on queue [" + queueName + "]");
                    } else {
                        String id = rawMessage.getJMSMessageID();
                        log.debug("found message on queue [" + queueName + "] with messageID [" + id + "]");
                        Serializable sobj = null;
                        if (rawMessage != null) {
                            if (rawMessage instanceof Serializable) {
                                sobj = (Serializable) rawMessage;
                            } else {
                                try {
                                    sobj = new MessageWrapper(rawMessage, esbJmsListener);
                                } catch (ListenerException e) {
                                    log.error("could not wrap non serializable message for messageId [" + id
                                            + "]", e);
                                    if (rawMessage instanceof TextMessage) {
                                        TextMessage textMessage = (TextMessage) rawMessage;
                                        sobj = textMessage.getText();
                                    } else {
                                        sobj = rawMessage.toString();
                                    }
                                }
                            }
                        }

                        jdbcConnection = jdbcDataSource.getConnection();

                        result = errorStorage.storeMessage(jdbcConnection, id, id,
                                new Date(System.currentTimeMillis()), "moved message", null, sobj);
                    }

                    log.debug("committing transaction [" + btm.getCurrentTransaction().getGtrid() + "]");
                    btm.commit();
                } catch (Exception e) {
                    if (btm.getCurrentTransaction() != null) {
                        log.debug("rolling back transaction [" + btm.getCurrentTransaction().getGtrid() + "]");
                        btm.rollback();
                    }
                    log.error("exception on receiving message and moving to errorStorage", e);
                } finally {
                    if (jdbcConnection != null) {
                        jdbcConnection.close();
                    }
                    if (jmsConnection != null) {
                        jmsConnection.stop();
                    }
                    if (jmsConsumer != null) {
                        jmsConsumer.close();
                    }
                    if (jmsSession != null) {
                        jmsSession.close();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("exception on receiving message and moving to errorStorage", e);
    } finally {
        if (jmsConnection != null) {
            try {
                jmsConnection.close();
            } catch (JMSException e) {
                log.warn("exception on closing connection", e);
            }
        }
        if (jmsConnectionFactory != null) {
            jmsConnectionFactory.close();
        }
        if (jdbcDataSource != null) {
            jdbcDataSource.close();
        }
        if (btm != null) {
            btm.shutdown();
        }
    }
    return result;
}

From source file:Log4jJMSAppenderExample.java

public Log4jJMSAppenderExample() throws Exception {
    // create a logTopic topic consumer
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
    Connection conn = factory.createConnection();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    conn.start();//w w  w.  ja va2  s. c  om
    MessageConsumer consumer = sess.createConsumer(sess.createTopic("logTopic"));
    consumer.setMessageListener(this);
    // log a message
    Logger log = Logger.getLogger(Log4jJMSAppenderExample.class);
    log.info("Test log");
    // clean up
    Thread.sleep(1000);
    consumer.close();
    sess.close();
    conn.close();
    System.exit(1);
}

From source file:org.apache.activemq.store.kahadb.MultiKahaDBQueueDeletionTest.java

@Override
protected void createConsumer(ActiveMQDestination dest) throws JMSException {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerConnectURI);
    Connection connection = factory.createConnection();
    connection.setClientID("client1");
    connection.start();//from  w w w .  j av  a 2s.co m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    session.createConsumer(dest);
}