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.sakaiproject.kernel.email.outgoing.OutgoingEmailMessageListener.java

protected void activate(ComponentContext ctx) {
    @SuppressWarnings("unchecked")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = (Integer) props.get(MAX_RETRIES);
    if (_maxRetries != null) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;/*from   w w  w. j  av  a 2 s.c om*/
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = (Integer) props.get(RETRY_INTERVAL);
    if (_retryInterval != null) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = (Integer) props.get(SMTP_PORT);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = (String) props.get(SMTP_SERVER);
    boolean smtpServerEmpty = _smtpServer == null || _smtpServer.trim().length() == 0;
    if (!smtpServerEmpty) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    String _brokerUrl = (String) props.get(BROKER_URL);

    try {
        boolean urlEmpty = _brokerUrl == null || _brokerUrl.trim().length() == 0;
        if (!urlEmpty) {
            if (diff(brokerUrl, _brokerUrl)) {
                LOGGER.info("Creating a new ActiveMQ Connection Factory");
                connectionFactory = connFactoryService.createFactory(_brokerUrl);
            }

            if (connectionFactory != null) {
                connection = connectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Topic dest = session.createTopic(TOPIC_NAME);
                MessageConsumer consumer = session.createConsumer(dest);
                consumer.setMessageListener(this);
                connection.start();
            }
        } else {
            LOGGER.error("Cannot create JMS connection factory with an empty URL.");
        }
        brokerUrl = _brokerUrl;
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void registerListener(String consumerName, MessageListener messageListener) {
    MessageConsumer consumer = _testConsumers.get(consumerName);
    try {/*from   w w w  .  jav a2 s.  c om*/
        consumer.setMessageListener(messageListener);
    } catch (JMSException e) {
        throw new DistributedTestException("Unable to register message listener with consumer: " + consumerName,
                e);
    }
}

From source file:org.sakaiproject.nakamura.email.outgoing.OutgoingEmailMessageListener.java

protected void activate(ComponentContext ctx) {
    @SuppressWarnings("rawtypes")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = (Integer) props.get(MAX_RETRIES);
    if (_maxRetries != null) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;/*from   w  w  w.  j  av a 2 s  .  c o m*/
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = (Integer) props.get(RETRY_INTERVAL);
    if (_retryInterval != null) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = (Integer) props.get(SMTP_PORT);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = (String) props.get(SMTP_SERVER);
    boolean smtpServerEmpty = _smtpServer == null || _smtpServer.trim().length() == 0;
    if (!smtpServerEmpty) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    try {
        connection = connFactoryService.getDefaultConnectionFactory().createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue dest = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(this);
        connection.start();
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

From source file:org.apache.camel.component.sjms.SjmsConsumer.java

/**
 * Creates a {@link MessageConsumerResources} with a dedicated
 * {@link Session} required for transacted and InOut consumers.
 *//*from www .j  a  v a2 s.com*/
private MessageConsumerResources createConsumer() throws Exception {
    MessageConsumerResources answer;
    Connection conn = getConnectionResource().borrowConnection();
    try {
        Session session = conn.createSession(isTransacted(),
                isTransacted() ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        Destination destination = getEndpoint().getDestinationCreationStrategy().createDestination(session,
                getDestinationName(), isTopic());
        MessageConsumer messageConsumer = JmsObjectFactory.createMessageConsumer(session, destination,
                getMessageSelector(), isTopic(), getDurableSubscriptionId());
        MessageListener handler = createMessageHandler(session);
        messageConsumer.setMessageListener(handler);

        answer = new MessageConsumerResources(session, messageConsumer);
    } catch (Exception e) {
        log.error("Unable to create the MessageConsumer", e);
        throw e;
    } finally {
        getConnectionResource().returnConnection(conn);
    }
    return answer;
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void setInstructionListener(final Client client) {
    try {//from  w  w  w .  java 2s .c o m
        _instructionQueue = _controllerSession.createTemporaryQueue();
        final MessageConsumer instructionConsumer = _controllerSession.createConsumer(_instructionQueue);
        instructionConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(final Message message) {
                client.processInstruction(JmsMessageAdaptor.messageToCommand(message));
            }
        });
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to setup instruction listener", jmse);
    }
}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception {
    MessageConsumer consumer;
    for (int i = 0; i < consumerCount; i++) {
        TimedMessageListener list = new TimedMessageListener();
        consumer = createDurableSubscriber(factory.createConnection(), dest, "consumer" + (i + 1));
        consumer.setMessageListener(list);
        consumers.put(consumer, list);/*from   w  w  w.ja  va2  s .com*/
    }
}

From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java

private void addMessageListener(String topic, MessageListener listener) throws JMSException {
    Destination destination = session.createTopic(topic);
    MessageConsumer consumer = session.createConsumer(destination);
    consumer.setMessageListener(listener);
}

From source file:org.apache.synapse.transport.jms.JMSConnectionFactory.java

/**
 * Listen on the given destination from this connection factory. Used to
 * start listening on a destination associated with a newly deployed service
 *
 * @param destinationJNDIname the JMS destination to listen on
 *//* w w  w . ja  v a2s .  c om*/
public void startListeningOnDestination(String destinationJNDIname, String destinationType) {

    Session session = (Session) jmsSessions.get(destinationJNDIname);
    // if we already had a session open, close it first
    if (session != null) {
        try {
            session.close();
        } catch (JMSException ignore) {
        }
    }

    try {
        session = JMSUtils.createSession(connection, false, Session.AUTO_ACKNOWLEDGE, destinationType);
        Destination destination = null;

        try {
            destination = (Destination) context.lookup(destinationJNDIname);

        } catch (NameNotFoundException e) {
            log.warn("Cannot find destination : " + destinationJNDIname + ". Creating a Queue");
            destination = JMSUtils.createDestination(session, destinationJNDIname, destinationType);
        }

        MessageConsumer consumer = JMSUtils.createConsumer(session, destination);
        consumer.setMessageListener(jmsMessageReceiver);
        jmsSessions.put(destinationJNDIname, session);

        // catches NameNotFound and JMSExceptions and marks service as faulty    
    } catch (Exception e) {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException ignore) {
            }
        }

        BaseUtils.markServiceAsFaulty((String) serviceJNDINameMapping.get(destinationJNDIname),
                "Error looking up JMS destination : " + destinationJNDIname, cfgCtx.getAxisConfiguration());
    }
}

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

/**
 * This test publishes 1000 messages and the subscriber accepts all message and then wait for the redelivered
 * message./*  ww w . j a  va 2  s .com*/
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void allAcknowledgeMessageListenerForMultipleMessagesTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 1000;
    final List<String> receivedMessages = new ArrayList<>();

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

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "allAcknowledgeMultiplePerAckQueue");
    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) {
            try {
                TextMessage textMessage = (TextMessage) message;
                message.acknowledge();
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

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

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME * 2);
    log.info("Received Messages : " + receivedMessages);

    for (int i = 0; i < sendCount; i++) {
        Assert.assertEquals(receivedMessages.get(i), "#" + Integer.toString(i),
                "Invalid messages received. #" + Integer.toString(i) + " expected.");
    }

    Assert.assertEquals(receivedMessages.size(), sendCount, "Message receiving failed.");
}

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

/**
 * This test publishes 10 messages and the subscriber rejects the 8th message and then wait for the redelivered
 * message.// w ww.  ja v a 2 s.c o  m
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void unacknowledgeMiddleMessageMessageListenerPerAckTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<String> receivedMessages = new ArrayList<>();

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

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "unacknowledgeMiddleMessagePerAckQueue");
    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) {
            try {
                TextMessage textMessage = (TextMessage) message;
                if (!textMessage.getText().equals("#7") || receivedMessages.contains(textMessage.getText())) {
                    message.acknowledge();
                }
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

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

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    log.info("Received Messages : " + receivedMessages);

    for (int i = 0; i < sendCount; i++) {
        Assert.assertEquals(receivedMessages.get(i), "#" + Integer.toString(i),
                "Invalid messages received. #" + Integer.toString(i) + " expected.");
    }

    Assert.assertEquals(receivedMessages.get(10), "#7", "Invalid messages received. #7 expected.");

    Assert.assertEquals(receivedMessages.size(), sendCount + 1, "Message receiving failed.");
}