Example usage for javax.jms MessageConsumer receive

List of usage examples for javax.jms MessageConsumer receive

Introduction

In this page you can find the example usage for javax.jms MessageConsumer receive.

Prototype


Message receive() throws JMSException;

Source Link

Document

Receives the next message produced for this message consumer.

Usage

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

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

    try {/* w w w  .j  a v a 2  s .  co  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:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * retrieve meta information for a UIMA-AS Service attached to a broker
 * It uses the port 1099 as the JMX port on the broker, unless overridden
 *   by defining the system property activemq.broker.jmx.port with a value of another port number
 * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden
 *   by defining the system property activemq.broker.jmx.domain with a value of the domain to use
 *   This normally never needs to be done unless multiple brokers are run on the same node 
 *   as is sometimes done for unit tests.
 * @param args - brokerUri serviceName [-verbose]
 *///from  w ww.  j  a v  a2 s .  c  o  m
public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Need arguments: brokerURI serviceName [-verbose]");
        System.exit(1);
    }
    String brokerURI = args[0];
    String queueName = args[1];
    boolean printReply = false;
    if (args.length > 2) {
        if (args[2].equalsIgnoreCase("-verbose")) {
            printReply = true;
        } else {
            System.err.println("Unknown argument: " + args[2]);
            System.exit(1);
        }
    }
    final Connection connection;
    Session producerSession = null;
    Queue producerQueue = null;
    MessageProducer producer;
    MessageConsumer consumer;
    Session consumerSession = null;
    TemporaryQueue consumerDestination = null;
    long startTime = 0;

    //  Check if JMX server port number was specified
    jmxPort = System.getProperty("activemq.broker.jmx.port");
    if (jmxPort == null || jmxPort.trim().length() == 0) {
        jmxPort = "1099"; // default
    }

    try {
        //  First create connection to a broker
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI);
        connection = factory.createConnection();
        connection.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                    if (jmxc != null) {
                        jmxc.close();
                    }
                } catch (Exception ex) {
                }
            }
        }));

        URI target = new URI(brokerURI);
        String brokerHost = target.getHost();

        attachToRemoteBrokerJMXServer(brokerURI);
        if (isQueueAvailable(queueName) == QueueState.exists) {
            System.out.println("Queue " + queueName + " found on " + brokerURI);
            System.out.println("Sending getMeta...");
        } else if (isQueueAvailable(queueName) == QueueState.existsnot) {
            System.err.println("Queue " + queueName + " does not exist on " + brokerURI);
            System.exit(1);
        } else {
            System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort);
            System.out.println("Sending getMeta anyway...");
        }

        producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producerQueue = producerSession.createQueue(queueName);
        producer = producerSession.createProducer(producerQueue);
        consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumerDestination = consumerSession.createTemporaryQueue();
        //  -----------------------------------------------------------------------------
        //  Create message consumer. The consumer uses a selector to filter out messages other
        //  then GetMeta replies. Currently UIMA AS service returns two messages for each request:
        //  ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the 
        //  service immediately upon receiving a message from a client. This serves dual purpose, 
        //  1) to make sure the client reply destination exists
        //  2) informs the client which service is processing its request
        //  -----------------------------------------------------------------------------
        consumer = consumerSession.createConsumer(consumerDestination, "Command=2001");
        TextMessage msg = producerSession.createTextMessage();
        msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName());
        msg.setStringProperty(UIMAMessage.ServerURI, brokerURI);
        msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request);
        msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta);
        msg.setJMSReplyTo(consumerDestination);
        msg.setText("");
        producer.send(msg);
        startTime = System.nanoTime();

        System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI);
        System.out.println("Waiting for getMeta reply...");
        ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive();
        long waitTime = (System.nanoTime() - startTime) / 1000000;

        System.out.println(
                "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms");
        if (printReply) {
            System.out.println("Reply MessageText: " + reply.getText());
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    System.exit(0);
}

From source file:sk.seges.test.jms.multiple.QueueSendReceiveTest.java

@Test
public void testReceive() throws Exception {
    Connection connection = testConnectionFactory.createConnection();
    connection.start();/*from w ww.j  ava  2 s  .  c o  m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(testQueueA);
    Message rawMessage = consumer.receive();
    assertTrue(rawMessage instanceof TextMessage);

    TextMessage message = (TextMessage) rawMessage;
    assertEquals("test text", message.getText());
    connection.close();
}

From source file:sk.seges.test.jms.activemq.SimpleActiveMQQueueSendReceiveTest.java

@Test
public void testReceive() throws Exception {
    Connection connection = activeMQConnectionFactory.createConnection();
    connection.start();/*from  w  ww .  j  a  v  a 2  s . co  m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(activeMQTestQueueA);
    Message rawMessage = consumer.receive();
    assertTrue(rawMessage instanceof TextMessage);

    TextMessage message = (TextMessage) rawMessage;
    assertEquals("test text", message.getText());
    connection.close();
}

From source file:Supplier.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;/*from  ww  w  . ja va  2  s .  co m*/
    Destination orderQueue;
    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue(QUEUE);
        MessageConsumer consumer = session.createConsumer(orderQueue);

        connection.start();

        while (true) {
            Message message = consumer.receive();
            MessageProducer producer = session.createProducer(message.getJMSReplyTo());
            MapMessage orderMessage;
            if (message instanceof MapMessage) {
                orderMessage = (MapMessage) message;
            } else {
                // End of Stream
                producer.send(session.createMessage());
                session.commit();
                producer.close();
                break;
            }

            int quantity = orderMessage.getInt("Quantity");
            System.out.println(
                    ITEM + " Supplier: Vendor ordered " + quantity + " " + orderMessage.getString("Item"));

            MapMessage outMessage = session.createMapMessage();
            outMessage.setInt("VendorOrderNumber", orderMessage.getInt("VendorOrderNumber"));
            outMessage.setString("Item", ITEM);

            quantity = Math.min(orderMessage.getInt("Quantity"),
                    new Random().nextInt(orderMessage.getInt("Quantity") * 10));
            outMessage.setInt("Quantity", quantity);

            producer.send(outMessage);
            System.out.println(ITEM + " Supplier: Sent " + quantity + " " + ITEM + "(s)");
            session.commit();
            System.out.println(ITEM + " Supplier: committed transaction");
            producer.close();
        }
        connection.close();
    } catch (JMSException e) {
        e.printStackTrace();
    }
}

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

public void receiveMessages(MessageConsumer consumer) throws NamingException, JMSException {

    PropertyConfigurator.configure("log4j.properties");

    //Receive all the message
    while (consumer.receive() != null) {
        messageCount++;//from   w w w.ja va2 s  .c  o m

    }

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

From source file:org.apache.falcon.messaging.ProcessProducerTest.java

private void consumer() throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();/* w  ww. j a v  a  2s.  c o m*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(getTopicName());
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();

    for (int index = 0; index < outputFeedNames.length; ++index) {
        MapMessage m = (MapMessage) consumer.receive();
        System.out.println("Consumed: " + m.toString());
        assertMessage(m);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_NAMES.getName()),
                outputFeedNames[index]);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName()),
                outputFeedPaths[index]);
    }
    connection.close();
}

From source file:org.apache.falcon.messaging.FeedProducerTest.java

private void verifyMesssage(MessageConsumer consumer) throws JMSException {
    for (String instancePath : instancePaths) {
        // receive call is blocking
        MapMessage m = (MapMessage) consumer.receive();

        System.out.println("Received JMS message {}" + m.toString());
        System.out.println("Consumed: " + m.toString());
        assertMessage(m);/* ww w  . j av  a 2s  . c  o m*/
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName()), instancePath);
    }
}

From source file:org.apache.falcon.regression.core.supportClasses.JmsMessageConsumer.java

@Override
public void run() {
    try {/*from  w  ww  . j  av a  2 s. c o  m*/
        // Getting JMS connection from the server
        Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection();
        connection.start();

        // Creating session for sending messages
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);

        try {
            LOGGER.info("Starting to receive messages.");
            int count = 0;
            for (; count < MAX_MESSAGE_COUNT; ++count) {
                Message message = consumer.receive(); //blocking call
                if (message == null) {
                    LOGGER.info("Received empty message, count = " + count);
                } else {
                    LOGGER.info("Received message, id = " + message.getJMSMessageID());
                    receivedMessages.add((MapMessage) message);
                }
            }
            if (count >= MAX_MESSAGE_COUNT) {
                LOGGER.warn("Not reading more messages, already read " + count + " messages.");
            }
        } finally {
            LOGGER.info("Stopping to receive messages.");
            connection.close();
        }
    } catch (Exception e) {
        LOGGER.info("caught exception: " + ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.apache.falcon.oozie.workflow.FalconPostProcessingTest.java

private void verifyMesssage(MessageConsumer consumer) throws JMSException {
    for (int index = 0; index < outputFeedPaths.length; ++index) {
        // receive call is blocking
        MapMessage m = (MapMessage) consumer.receive();

        System.out.println("Received JMS message {}" + m.toString());
        System.out.println("Consumed: " + m.toString());
        assertMessage(m);//  www.j a v  a 2  s  .  co  m
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_NAMES.getName()),
                outputFeedNames[index]);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName()),
                outputFeedPaths[index]);
    }
}