Example usage for javax.jms MessageConsumer setMessageListener

List of usage examples for javax.jms MessageConsumer setMessageListener

Introduction

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

Prototype

void setMessageListener(MessageListener listener) throws JMSException;

Source Link

Document

Sets the MessageConsumer 's MessageListener .

Usage

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a queue with setting "AndesSetRoutingKey" system property set to null value and check
 * null comes as a JMS property "JMS_ANDES_ROUTING_KEY" for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException//from   w  ww.j  a v a 2 s  . com
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void queueRoutingKeyPropertyNullTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.clearProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY);
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), null,
                "Invalid value received for routing key property.");
    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a topic with setting "AndesSetRoutingKey" system property set to null value and check
 * null comes as a JMS property "JMS_ANDES_ROUTING_KEY" for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException/*from  w  ww.  jav a2  s  .  c om*/
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "topic" })
public void topicRoutingKeyPropertyNullTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.clearProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY);
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();
    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), null,
                "Invalid value received for routing key property.");

    }
}

From source file:com.oneops.controller.jms.CmsListener.java

/**
 * Inits the.//from   www. j  a va2 s.  c  o  m
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {

    connection = connFactory.createConnection();
    connection.setClientID(consumerName);
    session = connection.createSession(true, Session.SESSION_TRANSACTED);

    Queue queue = session.createQueue(queueName);

    MessageConsumer consumer = session.createConsumer(queue);
    consumer.setMessageListener(this);
    connection.start();

    logger.info(">>>>>>>>>>>>>>CmsListener Waiting for messages...");
}

From source file:com.fusesource.forge.jmstest.benchmark.command.transport.JMSCommandTransport.java

public void start() {
    synchronized (lock) {
        if (started || released) {
            return;
        }/*from www. j  a  v  a 2  s  .c  o  m*/
        ReleaseManager.getInstance().register(this);
        log().info("JMSCommandTransport (re)starting.");
        while (!started && !released) {
            if (getConnection() != null) {
                try {
                    getConnection().setExceptionListener(this);
                    session = getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);
                    MessageConsumer consumer = session.createConsumer(
                            getJmsDestinationProvider().getDestination(session, getDestinationName()));
                    consumer.setMessageListener(this);
                    getConnection().start();
                    started = true;
                } catch (Exception e) {
                    log().error("Error creating JMSCommandTransport.", e);
                    resetConnection();
                }
            }
            if (!started) {
                try {
                    log.warn("Trying to reinitialize JMSTransport Connection in 5 seconds.");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
        }
        if (started) {
            log().info("JMSCommandTransport started.");
        }
    }
}

From source file:SelectorChat.java

/** Create JMS client for publishing and subscribing to messages. */
private void chatter(String broker, String username, String password, String selection) {

    // Create a connection.
    try {/* w ww  .  j ava 2 s  . c  o  m*/
        javax.jms.ConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createConnection(username, password);
        pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Cannot connect to Broker - " + broker);
        jmse.printStackTrace();
        System.exit(1);
    }

    // Create Publisher and Subscriber to 'chat' topics

    try {
        javax.jms.Topic topic = pubSession.createTopic(APP_TOPIC);
        // NOTE: The subscriber's message selector will now be set:
        javax.jms.MessageConsumer subscriber = subSession.createConsumer(topic,
                PROPERTY_NAME + " = \'" + selection + "\'", false);
        subscriber.setMessageListener(this);
        publisher = pubSession.createProducer(topic);
        // Now that setup is complete, start the Connection
        connect.start();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
        System.exit(1);
    }

    try {
        // Read all standard input and send it as a message.

        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        System.out.println("\nSelectorChat application:\n" + "===========================\n"
                + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME
                + ".\n" + "The application will publish messages with " + PROPERTY_NAME + " set to " + selection
                + " to the " + APP_TOPIC + " topic .\n"
                + "The application also subscribes to that topic, selecting only messages where "
                + PROPERTY_NAME + " is " + selection + ".\n"
                + "Type some text, and then press Enter to publish it as a TextMesssage from " + username
                + ".\n");

        while (true) {
            String s = stdin.readLine();

            if (s == null)
                exit();
            else if (s.length() > 0) {
                javax.jms.TextMessage msg = pubSession.createTextMessage();
                msg.setText(username + ": " + s);
                // NOTE: here we set a property on messages to be published:
                msg.setStringProperty(PROPERTY_NAME, selection);
                publisher.send(msg);
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
}

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizFac(Context ctx, Object obj) throws Exception {

    ConnectionFactory f = (ConnectionFactory) obj;
    final JmsIO me = this;
    Connection conn;//from   ww w .j a v  a 2 s  . c om
    Object c = ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createConnection(_jmsUser, _jmsPwd);
    } else {
        conn = f.createConnection();
    }

    _conn = conn;

    if (c instanceof Destination) {
        //TODO ? ack always ?
        Session s = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer u = s.createConsumer((Destination) c);
        u.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                me.onMessage(msg);
            }
        });
    } else {
        throw new Exception("JmsIO: Object not of Destination type");
    }
}

From source file:Vendor.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;//  w  w  w.ja v a2 s  .  co  m
    Destination orderQueue;
    Destination monitorOrderQueue;
    Destination storageOrderQueue;
    TemporaryQueue vendorConfirmQueue;
    MessageConsumer orderConsumer = null;
    MessageProducer monitorProducer = null;
    MessageProducer storageProducer = null;

    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue("VendorOrderQueue");
        monitorOrderQueue = session.createQueue("MonitorOrderQueue");
        storageOrderQueue = session.createQueue("StorageOrderQueue");

        orderConsumer = session.createConsumer(orderQueue);
        monitorProducer = session.createProducer(monitorOrderQueue);
        storageProducer = session.createProducer(storageOrderQueue);

        Connection asyncconnection = connectionFactory.createConnection();
        asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED);

        vendorConfirmQueue = asyncSession.createTemporaryQueue();
        MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue);
        confirmConsumer.setMessageListener(this);

        asyncconnection.start();

        connection.start();

        while (true) {
            Order order = null;
            try {
                Message inMessage = orderConsumer.receive();
                MapMessage message;
                if (inMessage instanceof MapMessage) {
                    message = (MapMessage) inMessage;

                } else {
                    // end of stream
                    Message outMessage = session.createMessage();
                    outMessage.setJMSReplyTo(vendorConfirmQueue);
                    monitorProducer.send(outMessage);
                    storageProducer.send(outMessage);
                    session.commit();
                    break;
                }

                // Randomly throw an exception in here to simulate a Database error
                // and trigger a rollback of the transaction
                if (new Random().nextInt(3) == 0) {
                    throw new JMSException("Simulated Database Error.");
                }

                order = new Order(message);

                MapMessage orderMessage = session.createMapMessage();
                orderMessage.setJMSReplyTo(vendorConfirmQueue);
                orderMessage.setInt("VendorOrderNumber", order.getOrderNumber());
                int quantity = message.getInt("Quantity");
                System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item"));

                orderMessage.setInt("Quantity", quantity);
                orderMessage.setString("Item", "Monitor");
                monitorProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Monitor(s)");

                orderMessage.setString("Item", "HardDrive");
                storageProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)");

                session.commit();
                System.out.println("Vendor: Comitted Transaction 1");

            } catch (JMSException e) {
                System.out.println("Vendor: JMSException Occured: " + e.getMessage());
                e.printStackTrace();
                session.rollback();
                System.out.println("Vendor: Rolled Back Transaction.");
            }
        }

        synchronized (supplierLock) {
            while (numSuppliers > 0) {
                try {
                    supplierLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        connection.close();
        asyncconnection.close();

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

}

From source file:com.fusesource.forge.jmstest.tests.AsyncProducer.java

public void run() {

    try {/*from  ww  w . j  a  v a2 s.  c  o  m*/
        Connection conn = getConnection();
        Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        if (isExpectReply()) {
            Destination replyTo = getDestinationProvider().getDestination(session, getReplyDestination());
            MessageConsumer consumer = session.createConsumer(replyTo);
            consumer.setMessageListener(this);
        }

        Destination dest = getDestinationProvider().getDestination(session, getDestinationName());
        MessageProducer producer = session.createProducer(dest);
        producer.setDeliveryMode(getDeliveryMode().getCode());
        getConnection().start();

        LOG.info(">>Starting Message send loop");
        while (!done.get()) {
            try {
                locallySent++;
                Destination replyDest = null;
                Message msg = getMessageFactory().createMessage(session);
                if (getMsgGroup() != null) {
                    LOG.debug("Setting message group to : " + getMsgGroup());
                    msg.setStringProperty("JMSXGroupID", getMsgGroup());
                    if (getMessagesToSend() > 0) {
                        if (locallySent == getMessagesToSend()) {
                            LOG.debug("Closing message group: " + getMsgGroup());
                            msg.setIntProperty("JMSXGroupSeq", 0);
                        }
                    }
                }
                msg.setLongProperty("MsgNr", locallySent);
                if (isExpectReply()) {
                    corrId = getReplyDestination() + "Seq-" + locallySent;
                    msg.setStringProperty("JMSCorrelationID", corrId);
                    replyDest = getDestinationProvider().getDestination(session, getReplyDestination());
                    msg.setJMSReplyTo(replyDest);
                    receivedResponse = false;
                }
                long sendTime = System.currentTimeMillis();
                producer.send(msg, deliveryMode.getCode(), 4, ttl);
                if (sent != null) {
                    sent.incrementAndGet();
                }
                done.set((getMessagesToSend() > 0) && ((locallySent) == getMessagesToSend()));
                if (isExpectReply()) {
                    try {
                        LOG.debug("Waiting for response ...");
                        synchronized (corrId) {
                            try {
                                if (getReplyTimeOut() > 0) {
                                    corrId.wait(getReplyTimeOut());
                                } else {
                                    corrId.wait();
                                }
                            } catch (InterruptedException ie) {
                            }
                            if (receivedResponse) {
                                long duration = System.currentTimeMillis() - sendTime;
                                LOG.debug("Got response from peer in " + duration + " ms");
                            } else {
                                LOG.error("Response not received within time frame...");
                                if (timeOuts != null) {
                                    timeOuts.incrementAndGet();
                                }
                            }
                        }
                    } catch (Exception e) {
                        if (exceptions != null) {
                            exceptions.incrementAndGet();
                        }
                    }
                }
                if (sleep > 0L) {
                    try {
                        Thread.sleep(sleep);
                    } catch (InterruptedException ie) {
                    }
                }
            } catch (JMSException e) {
                if (exceptions != null) {
                    exceptions.incrementAndGet();
                }
            }
        }
    } catch (Exception e) {
    } finally {
        try {
            closeConnection();
        } catch (Throwable e) {
        }
    }
    LOG.info(">>MessageSender done...(" + sent + ")");
}

From source file:com.facetime.communication.activemq.AmqConsumer.java

public synchronized void closeConsumers() {
    for (Iterator<MessageConsumer> it = consumers.values().iterator(); it.hasNext();) {
        MessageConsumer consumer = it.next();
        it.remove();/*from w w w .ja  v a 2 s. co  m*/
        try {
            consumer.setMessageListener(null);
            if (consumer instanceof MessageAvailableConsumer) {
                ((MessageAvailableConsumer) consumer).setAvailableListener(null);
            }
            consumer.close();
        } catch (JMSException e) {
            LOG.debug("caught exception closing consumer", e);
        }
    }
}

From source file:org.apache.activemq.JmsQueueCompositeSendReceiveTest.java

/**
 * Test if all the messages sent are being received.
 *
 * @throws Exception// www.j a  v a 2s. c  o  m
 */
public void testSendReceive() throws Exception {
    super.testSendReceive();
    messages.clear();
    Destination consumerDestination = consumeSession.createQueue("FOO.BAR.HUMBUG2");
    LOG.info("Created  consumer destination: " + consumerDestination + " of type: "
            + consumerDestination.getClass());
    MessageConsumer consumer = null;
    if (durable) {
        LOG.info("Creating durable consumer");
        consumer = consumeSession.createDurableSubscriber((Topic) consumerDestination, getName());
    } else {
        consumer = consumeSession.createConsumer(consumerDestination);
    }
    consumer.setMessageListener(this);

    assertMessagesAreReceived();
    LOG.info("" + data.length + " messages(s) received, closing down connections");
}