Example usage for javax.jms MessageListener MessageListener

List of usage examples for javax.jms MessageListener MessageListener

Introduction

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

Prototype

MessageListener

Source Link

Usage

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

@Override
public void systemStarted() throws Exception {
    // initializing apps
    Map<String, String> lApps = mSettings.getApps();
    for (String lAppName : lApps.keySet()) {
        try {//from  w  ww. j av a 2s.co m
            execAppBeforeLoadChecks(lAppName, lApps.get(lAppName));
            loadApp(lAppName, lApps.get(lAppName), false);
        } catch (Exception lEx) {
            mLog.error(Logging.getSimpleExceptionMessage(lEx, "loading '" + lAppName + "' application"));
        }
    }

    notifyToApps(BaseScriptApp.EVENT_SYSTEM_STARTED, new Object[0]);
    try {
        // registering on message hub if running on a cluster
        getServer().getJMSManager().subscribe(new MessageListener() {

            @Override
            public void onMessage(Message aMessage) {
                try {
                    // discard processing if the message comes from the current server node
                    if (JWebSocketConfig.getConfig().getNodeId()
                            .equals(aMessage.getStringProperty(Attributes.NODE_ID))) {
                        return;
                    }

                    ClusterMessageTypes lType = ClusterMessageTypes
                            .valueOf(aMessage.getStringProperty(Attributes.MESSAGE_TYPE));
                    switch (lType) {
                    case LOAD_APP: {
                        String lAppName = aMessage.getStringProperty("appName");
                        Boolean lHotLoad = aMessage.getBooleanProperty("hotLoad");
                        String lPath = mSettings.getApps().get(lAppName);

                        // loading app
                        loadApp(lAppName, lPath, lHotLoad);
                        break;
                    }
                    case UNDEPLOY_APP: {
                        String lAppName = aMessage.getStringProperty("appName");
                        // validating
                        BaseScriptApp lScriptApp = mApps.get(lAppName);

                        // notifying event before undeploy
                        lScriptApp.notifyEvent(BaseScriptApp.EVENT_UNDEPLOYING, new Object[0]);

                        // deleting app
                        mApps.remove(lAppName);
                        FileUtils.deleteDirectory(new File(lScriptApp.getPath()));
                        break;
                    }
                    }
                } catch (Exception lEx) {
                    mLog.error(Logging.getSimpleExceptionMessage(lEx,
                            "processing cluster message: " + aMessage.toString()));
                }
            }
        }, "ns = '" + NS + "'");
    } catch (Exception aException) {
        mLog.error("Exception catched while getting the JMS Manager instance with the following message: "
                + aException.getMessage());
    }

    if (mLog.isDebugEnabled()) {
        mLog.debug("Scripting plug-in finished startup process!");
    }
}

From source file:drepcap.frontend.jms.JmsAdapter.java

public void startReceiveData() throws JMSException {
    dataTopic = session.createTopic(componentName + ".data");
    dataConsumer = session.createConsumer(dataTopic);
    dataConsumer.setMessageListener(new MessageListener() {
        @Override//from w w w  .ja va2 s . c  om
        public void onMessage(Message msg) {
            for (ByteArrayReceiver baDataReceiver : byteArrayDataReceivers) {
                if (baDataReceiver != null && msg instanceof BytesMessage) {
                    BytesMessage bMsg = (BytesMessage) msg;
                    try {
                        byte[] data = new byte[(int) bMsg.getBodyLength()];
                        bMsg.readBytes(data);
                        baDataReceiver.process(data);
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }

            for (ObjectReceiver objReceiver : objectReceivers) {
                if (objReceiver != null && msg instanceof ObjectMessage) {
                    ObjectMessage objMsg = (ObjectMessage) msg;
                    try {
                        objReceiver.process(objMsg.getObject());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
}

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 non-null value and
 * check the correct routing key comes as a JMS property for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException/*from   www  . j ava  2  s . co  m*/
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "topic" })
public void topicRoutingKeyPropertyTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.setProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY, "1");
    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),
                "RoutingKeyPropertyTopic", "Invalid value received for " + "routing key property.");

    }
}

From source file:org.openmrs.event.EventEngine.java

/**
 * @see Event#subscribe(Destination, EventListener)
 *///from ww  w. j a  v a2 s  .  co m
public void subscribe(Destination destination, final EventListener listenerToRegister) {

    initializeIfNeeded();

    TopicConnection conn;
    Topic topic = (Topic) destination;

    try {
        conn = (TopicConnection) jmsTemplate.getConnectionFactory().createConnection();
        TopicSession session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
        TopicSubscriber subscriber = session.createSubscriber(topic);
        subscriber.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                listenerToRegister.onMessage(message);
            }
        });

        //Check if this is a duplicate and remove it
        String key = topic.getTopicName() + DELIMITER + listenerToRegister.getClass().getName();
        if (subscribers.containsKey(key)) {
            unsubscribe(destination, listenerToRegister);
        }

        subscribers.put(key, subscriber);
        conn.start();

    } catch (JMSException e) {
        // TODO Auto-generated catch block. Do something smarter here.
        e.printStackTrace();
    }

    //      List<EventListener> currentListeners = listeners.get(key);
    //
    //      if (currentListeners == null) {
    //         currentListeners = new ArrayList<EventListener>();
    //         currentListeners.add(listenerToRegister);
    //         listeners.put(key, currentListeners);
    //         if (log.isInfoEnabled())
    //            log.info("subscribed: " + listenerToRegister + " to key: "
    //                  + key);
    //
    //      } else {
    //         // prevent duplicates because of weird spring loading
    //         String listernToRegisterName = listenerToRegister.getClass()
    //               .getName();
    //         Iterator<EventListener> iterator = currentListeners.iterator();
    //         while (iterator.hasNext()) {
    //            EventListener lstnr = iterator.next();
    //            if (lstnr.getClass().getName().equals(listernToRegisterName))
    //               iterator.remove();
    //         }
    //
    //         if (log.isInfoEnabled())
    //            log.info("subscribing: " + listenerToRegister + " to key: "
    //                  + key);
    //
    //         currentListeners.add(listenerToRegister);
    //      }

}

From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java

/**
 * Starts a connection which listens to the topic and if
 * a cancel is found published, tries to terminate the subprocess.
 * /* w  w  w  . j  a va2s  .c o  m*/
 * @param p
 */
protected void createTerminateListener() throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    ProgressableProcess.this.topicConnection = connectionFactory.createConnection();
    topicConnection.start();

    Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

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

    final Class clazz = bean.getClass();
    final ObjectMapper mapper = new ObjectMapper();

    MessageListener listener = new MessageListener() {
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {
                    TextMessage t = (TextMessage) message;
                    final StatusBean tbean = mapper.readValue(t.getText(), clazz);

                    if (bean.getStatus().isFinal()) { // Something else already happened
                        topicConnection.close();
                        return;
                    }

                    if (bean.getUniqueId().equals(tbean.getUniqueId())) {
                        if (tbean.getStatus() == Status.REQUEST_TERMINATE) {
                            bean.merge(tbean);
                            out.println("Terminating job '" + tbean.getName() + "'");

                            terminate();
                            topicConnection.close();

                            bean.setStatus(Status.TERMINATED);
                            bean.setMessage("Foricibly terminated before finishing.");
                            broadcast(bean);

                            return;
                        }
                    }

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

    };
    consumer.setMessageListener(listener);

}

From source file:com.seajas.search.profiler.service.profiler.ProfilerService.java

/**
 * Default constructor.//from   w  w  w. j  a  v a  2  s.  co  m
 * 
 * @param jobNames
 * @param jobDescriptions
 * @param availableApplicationLanguages
 * @param availableSearchLanguages
 * @param jmsRequestQueue
 * @param jmsConnectionFactory
 * @throws Exception
 */
@Autowired
public ProfilerService(@Value("${profiler.project.search.enricher.jobs}") final String jobNames,
        @Value("${profiler.project.search.enricher.jobs.descriptions}") final String jobDescriptions,
        @Value("${profiler.project.languages.available}") final String availableApplicationLanguages,
        @Value("${profiler.project.search.languages}") final String availableSearchLanguages,
        @Qualifier("jmsPrimaryRequestQueue") final ActiveMQQueue jmsRequestQueue,
        @Qualifier("connectionFactory") final ConnectionFactory jmsConnectionFactory) throws Exception {
    /* InputStream caCertificate = getClass().getClassLoader().getResourceAsStream("ca.crt"); LicenseValidator.validateLicenseFile(caCertificate, licenseFile);
     * 
     * try { caCertificate.close(); } catch (IOException e) { logger.error("Could not close the CA certificate stream."); } */

    String[] names = jobNames.split(",");
    String[] descriptions = jobDescriptions.split(",");

    this.jobNames = new LinkedHashMap<String, String>();

    for (int i = 0; i < names.length; i++)
        this.jobNames.put(names[i].trim(), descriptions[i].trim());

    this.availableApplicationLanguages = Arrays
            .asList(StringUtils.tokenizeToStringArray(availableApplicationLanguages, ",", true, true));
    this.availableSearchLanguages = Arrays
            .asList(StringUtils.tokenizeToStringArray(availableSearchLanguages, ",", true, true));

    // Keep track of the active consumers on the request channel

    Connection connection = jmsConnectionFactory.createConnection();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

    connection.start();

    Destination destinationAdvisory = AdvisorySupport.getConsumerAdvisoryTopic(jmsRequestQueue);
    MessageConsumer consumerAdvisory = session.createConsumer(destinationAdvisory);

    consumerAdvisory.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(final Message message) {
            try {
                Object consumerCount = ((ActiveMQMessage) message).getProperty("consumerCount");

                if (consumerCount != null) {
                    String clientId = ((ActiveMQMessage) message).getConnection().getConnectionInfo()
                            .getClientId();

                    if (activeContenderClients.contains(clientId) && ((Integer) consumerCount == 0)) {
                        if (staticLogger.isInfoEnabled())
                            staticLogger.info("Client with ID " + clientId
                                    + " was dropped from the current consumer-clients");

                        activeContenderClients.remove(clientId);
                    } else if (!activeContenderClients.contains(clientId) && ((Integer) consumerCount > 0)) {
                        if (staticLogger.isInfoEnabled())
                            staticLogger.info("Client with ID " + clientId
                                    + " was added to the current consumer-clients");

                        activeContenderClients.add(clientId);
                    }
                }
            } catch (IOException e) {
                staticLogger.error("Could not retrieve consumer count from connection message", e);
            }
        }
    });
}

From source file:org.aludratest.service.jms.JmsActionImplTest.java

/**
 *  Check durable messaging./* w  ww . j  av a 2s  . c  o m*/
 *  <ul>
 *      <li>subscribe durable</li>
 *      <li>disconnect the {@link JmsService} that subscribed</li>
 *      <li>send a message with unique content to the topic</li>
 *      <li>connect a new {@link JmsService} to the subscription</li>
 *      <li>check if messages where received</li>
 *      <li>unsubscribe the durable subscription</li>
 *      <li>send a message with unique content to the topic</li>
 *      <li>check that no messages where received</li>
 *  </ul>
 */
@Test
public void testDurableTopicSubscriberRegisterUnregister() {

    LOGGER.info("Begin testDurableTopicSubscriberRegisterUnregister");

    final List<Message> received = new ArrayList<Message>();
    final MessageListener listener = new MessageListener() {
        @Override
        public void onMessage(Message message) {
            LOGGER.info("Got message!");
            received.add(message);
        }
    };

    final String topicName = topics[0];
    final String subscriptionName = "testDurableTopicSubscriberRegisterUnregister@" + topicName;
    final String expectedText = UUID.randomUUID().toString();

    try {
        LOGGER.info("Create durable subscription [" + subscriptionName + "] on TOPIC " + topicName);
        JmsService subscriber1 = buildJmsService();
        subscriber1.perform().subscribeTopic(listener, topicName, null, subscriptionName, true);
        subscriber1.close();

        LOGGER.info("Sending message to the TOPIC " + topicName);
        received.clear();
        this.perform.sendTextMessage(expectedText, topicName);

        LOGGER.info("Connecting a new client using the subscription " + subscriptionName);
        subscriber1 = buildJmsService();
        subscriber1.perform().subscribeTopic(listener, topicName, null, subscriptionName, true);

        LOGGER.info("Waiting for messages on subscription...");
        Thread.sleep(100);

        LOGGER.info("Check for expected message");
        Assert.assertTrue("Expected message not received!", containtsTextMessage(received, expectedText));
        received.clear();

        LOGGER.info("Unsubscribing subscription " + subscriptionName);
        subscriber1.perform().unsubscribeTopic(subscriptionName);

        LOGGER.info("Sending message to the TOPIC " + topicName);
        received.clear();
        this.perform.sendTextMessage(expectedText, topicName);

        LOGGER.info("Waiting for messages on subscription...");
        Thread.sleep(100);
        Assert.assertTrue("Received unexpected message!", received.isEmpty());
        subscriber1.close();

    } catch (Exception e) {
        Assert.fail("Unexpected excpetion on testTopicSubscriber " + " : " + e.getMessage());
    }
    LOGGER.info("End testDurableTopicSubscriberRegisterUnregister");

}

From source file:org.apache.openejb.activemq.JMS2AMQTest.java

@Test
public void cdiListenerAPI() throws InterruptedException {
    final String text = TEXT + "4";

    final AtomicReference<Throwable> error = new AtomicReference<>();
    final CountDownLatch ready = new CountDownLatch(1);
    final CountDownLatch over = new CountDownLatch(1);
    new Thread() {
        {//from w  w w  .jav  a  2s  .co m
            setName(JMS2AMQTest.class.getName() + ".cdiListenerAPI#receiver");
        }

        @Override
        public void run() {
            final ContextsService contextsService = WebBeansContext.currentInstance().getContextsService();
            contextsService.startContext(RequestScoped.class, null);
            try {
                final JMSConsumer consumer = context.createConsumer(destination3);
                consumer.setMessageListener(new MessageListener() {
                    @Override
                    public void onMessage(final Message message) {
                        try {
                            assertEquals(text, message.getBody(String.class));
                        } catch (final Throwable e) {
                            error.set(e);
                        } finally {
                            over.countDown();
                            consumer.close();
                        }
                    }
                });
                ready.countDown();
            } catch (final Throwable t) {
                error.set(t);
            } finally {
                try {
                    over.await(1, TimeUnit.MINUTES);
                } catch (final InterruptedException e) {
                    Thread.interrupted();
                }
                contextsService.endContext(RequestScoped.class, null);
            }
        }
    }.start();

    ready.await(1, TimeUnit.MINUTES);

    // now send the message
    try (final JMSContext context = cf.createContext()) {
        context.createProducer().send(destination3, text);
    } catch (final JMSRuntimeException ex) {
        fail(ex.getMessage());
    }

    over.await(1, TimeUnit.MINUTES);

    // ensure we got the message and no exception
    final Throwable exception = error.get();
    if (exception != null) {
        exception.printStackTrace();
    }
    assertNull(exception == null ? "ok" : exception.getMessage(), exception);
}

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

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

    QueueConnectionFactory f = (QueueConnectionFactory) obj;
    final JmsIO me = this;
    QueueConnection conn;/*from  w ww  . java2 s . c om*/
    Queue q = (Queue) ctx.lookup(_dest);

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

    _conn = conn;

    QueueSession s = conn.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
    QueueReceiver r;

    r = s.createReceiver(q);
    r.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            me.onMessage(msg);
        }
    });
}

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

/**
 * This test publishes 10 messages and the subscriber rejects the first message and then wait for the redelivered
 * message.//from  w  w  w .j  av  a  2 s  .  c om
 * <p/>
 * The redelivered message is tested against the same message content with the original message and the timestamps
 * are also checked against the original message timestamp to make sure that the message was delayed.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void firstMessageInvalidOnlyQueueMessageListenerTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<ImmutablePair<String, Calendar>> receivedMessages = new ArrayList<>();
    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "firstMessageInvalidOnlyQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

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

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        private boolean receivedFirstMessage = false;

        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                if (!receivedFirstMessage && "#0".equals(textMessage.getText())) {
                    receivedFirstMessage = true;
                } else {
                    message.acknowledge();
                }
                receivedMessages.add(ImmutablePair.of(textMessage.getText(), Calendar.getInstance()));
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

    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);
    log.info("Received Messages : " + getMessageList(receivedMessages));

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

    validateMessageContentAndDelay(receivedMessages, 0, 10, "#0");

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