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:com.fusesource.examples.activemq.SimpleConsumer.java

public static void main(String args[]) {
    Connection connection = null;

    try {/*ww w .  j ava2s. co m*/
        // JNDI lookup of JMS Connection Factory and JMS Destination
        Context context = new InitialContext();
        ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
        Destination destination = (Destination) context.lookup(DESTINATION_NAME);

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

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(destination);

        LOG.info("Start consuming messages from " + destination.toString() + " with "
                + MESSAGE_TIMEOUT_MILLISECONDS + "ms timeout");

        // Synchronous message consumer
        int i = 1;
        while (true) {
            Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS);
            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    LOG.info("Got " + (i++) + ". message: " + text);
                }
            } else {
                break;
            }
        }

        consumer.close();
        session.close();
    } catch (Throwable t) {
        LOG.error(t);
    } finally {
        // Cleanup code
        // In general, you should always close producers, consumers,
        // sessions, and connections in reverse order of creation.
        // For this simple example, a JMS connection.close will
        // clean up all other resources.
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOG.error(e);
            }
        }
    }
}

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

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

    ConnectionFactory connectionFactory = ConnectionFactoryFacade
            .createConnectionFactory("tcp://sci-serv5.diamond.ac.uk:61616");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("testQ");

    final MessageConsumer consumer = session.createConsumer(queue);
    connection.start();/*ww  w .  j av  a 2  s  .c o  m*/

    while (true) { // You have to kill it to stop it!
        Message m = consumer.receive(1000);
        if (m != null) {
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;
                System.out.println(t.getText());
                try {
                    ObjectMapper mapper = new ObjectMapper();
                    final SweepBean colBack = mapper.readValue(t.getText(), SweepBean.class);
                    System.out.println("Data collection found: " + colBack.getDataCollectionId());

                } catch (Exception ne) {
                    System.out.println(m + " is not a data collection.");
                }
            } else if (m instanceof ObjectMessage) {
                ObjectMessage o = (ObjectMessage) m;
                System.out.println(o.getObject());
            }
        }
    }
}

From source file:example.transaction.Client.java

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

    try {
        connection = connectionFactory.createConnection();
        connection.start();
        Topic destination = new ActiveMQTopic("transacted.client.example");

        Session senderSession = connection.createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Session receiverSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer receiver = receiverSession.createConsumer(destination);
        receiver.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (message instanceof TextMessage) {
                    try {
                        String value = ((TextMessage) message).getText();
                        System.out.println("We received a new message: " + value);
                    } catch (JMSException e) {
                        System.out.println("Could not read the receiver's topic because of a JMSException");
                    }
                }
            }
        });

        MessageProducer sender = senderSession.createProducer(destination);

        connection.start();
        acceptInputFromUser(senderSession, sender);
        senderSession.close();
        receiverSession.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.queue.Consumer.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 2s .  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");
        MessageConsumer consumer = session.createConsumer(destination);

        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: " + 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:example.topic.Subscriber.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();// w  w  w  .  j ava2 s . c  o m
    }
    System.out
            .println("\nWaiting to receive messages... Either waiting for END message or press Ctrl+C to exit");
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;
    final CountDownLatch latch = new CountDownLatch(1);

    try {

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

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic("test-topic");

        MessageConsumer consumer = session.createConsumer(destination);
        consumer.setMessageListener(new Subscriber(latch));

        latch.await();
        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:example.tempdest.Consumer.java

public static void main(String[] args) {

    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();/* w  w w .  j  ava2 s .  c om*/
    }
    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();

        final Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test-queue");
        MessageConsumer consumer = session.createConsumer(destination);

        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: " + text);
                    Destination replyTo = message.getJMSReplyTo();
                    MessageProducer producer = session.createProducer(replyTo);
                    producer.send(
                            session.createTextMessage("You made it to the consumer, here is your response"));
                    producer.close();
                }
            } 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:example.queue.exclusive.Consumer.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();//from   ww  w  .j  a  v a 2s.  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);
        Queue destination = session.createQueue("test-queue?consumer.exclusive=true");
        MessageConsumer consumer = session.createConsumer(destination);

        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: " + 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:com.fusesource.examples.activemq.VirtualConsumer.java

public static void main(String args[]) {
    Connection connection = null;

    try {//from  www  . j  ava2s. c  o  m
        // JNDI lookup of JMS Connection Factory and JMS Destination
        Context context = new InitialContext();
        ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);

        connection = factory.createConnection();
        connection.setClientID(System.getProperty("clientID"));
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(System.getProperty("queue"));

        MessageConsumer consumer = session.createConsumer(queue);

        LOG.info("Start consuming messages from " + queue + " with " + MESSAGE_TIMEOUT_MILLISECONDS
                + "ms timeout");

        // Synchronous message consumer
        int i = 1;
        while (true) {
            Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS);
            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    LOG.info("Got " + (i++) + ". message: " + text);
                }
            } else {
                break;
            }
        }

        consumer.close();
        session.close();
    } catch (Throwable t) {
        LOG.error(t);
    } finally {
        // Cleanup code
        // In general, you should always close producers, consumers,
        // sessions, and connections in reverse order of creation.
        // For this simple example, a JMS connection.close will
        // clean up all other resources.
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOG.error(e);
            }
        }
    }
}

From source file:org.jboss.activemq.clients.JMSConsumer.java

public static void main(String args[]) {
    Connection connection = null;

    try {/* w w w. j av a2 s . c o  m*/

        Options options = new Options();
        options.addOption("h", "help", false, "help:");
        options.addOption("url", true, "url for the broker to connect to");
        options.addOption("u", "username", true, "User name for connection");
        options.addOption("p", "password", true, "password for connection");
        options.addOption("d", "destination", true, "destination to send to");
        options.addOption("n", "number", true, "number of messages to send");
        options.addOption("delay", true, "delay between each send");

        CommandLineParser parser = new BasicParser();
        CommandLine commandLine = parser.parse(options, args);

        if (commandLine.hasOption("h")) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("OptionsTip", options);
            System.exit(0);
        }

        String url = commandLine.hasOption("host") ? commandLine.getOptionValue("host") : URL;

        String userName = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "admin";
        String password = commandLine.hasOption("p") ? commandLine.getOptionValue("p") : "admin";
        String destinationName = commandLine.hasOption("d") ? commandLine.getOptionValue("d")
                : DESTINATION_NAME;
        int numberOfMessages = commandLine.hasOption("n") ? Integer.parseInt(commandLine.getOptionValue("n"))
                : NUM_MESSAGES_TO_RECEIVE;
        ;

        ConnectionFactory factory = new ActiveMQConnectionFactory(userName, password, url);

        connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(destinationName);

        MessageConsumer consumer = session.createConsumer(topic);

        LOG.info("Start consuming " + numberOfMessages + " messages from " + topic.toString());

        for (int i = 0; i < numberOfMessages; i++) {
            Message message = consumer.receive();
            if (message != null) {
                if (message instanceof BytesMessage) {
                    BytesMessage bytesMessage = (BytesMessage) message;
                    int len = (int) bytesMessage.getBodyLength();
                    byte[] data = new byte[len];
                    bytesMessage.readBytes(data);
                    String value = new String(data);

                    LOG.info("Got " + value);
                } else {
                    LOG.info("Got a message " + message);
                }
            }
        }

        consumer.close();
        session.close();
    } catch (Throwable t) {
        LOG.error("Error receiving message", t);
    } finally {

        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOG.error("Error closing connection", e);
            }
        }
    }
}

From source file:com.fusesource.examples.activemq.SimpleSubscriber.java

public static void main(String args[]) {
    Connection connection = null;

    try {/*w w  w.  ja  v a 2s .  c  om*/
        // JNDI lookup of JMS Connection Factory and JMS Destination
        Context context = new InitialContext();
        ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
        connection = factory.createConnection();
        connection.setClientID("ApplicationA");

        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        String topicName = System.getProperty("topic");

        Topic topic = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(topic);

        LOG.info("Start consuming messages from " + topicName + " with " + MESSAGE_TIMEOUT_MILLISECONDS
                + "ms timeout");

        // Synchronous message consumer
        int i = 1;
        while (true) {
            Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS);
            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    LOG.info("Got " + (i++) + ". message: " + text);
                }
            } else {
                break;
            }
        }

        consumer.close();
        session.close();
    } catch (Throwable t) {
        LOG.error(t);
    } finally {
        // Cleanup code
        // In general, you should always close producers, consumers,
        // sessions, and connections in reverse order of creation.
        // For this simple example, a JMS connection.close will
        // clean up all other resources.
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOG.error(e);
            }
        }
    }
}