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:net.blogracy.controller.DistributedHashTable.java

public void lookup(final String id) {
    try {//from  w  w w  . j  a  v  a2 s.c o  m
        Destination tempDest = session.createTemporaryQueue();
        MessageConsumer responseConsumer = session.createConsumer(tempDest);
        responseConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message response) {
                try {
                    String msgText = ((TextMessage) response).getText();
                    JSONObject keyValue = new JSONObject(msgText);
                    String value = keyValue.getString("value");
                    PublicKey signerKey = JsonWebSignature.getSignerKey(value);
                    JSONObject record = new JSONObject(JsonWebSignature.verify(value, signerKey));
                    JSONObject currentRecord = getRecord(id);
                    if (currentRecord == null
                            || currentRecord.getString("version").compareTo(record.getString("version")) < 0) {
                        putRecord(record);
                        String uri = record.getString("uri");
                        FileSharing.getSingleton().download(uri);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        JSONObject record = new JSONObject();
        record.put("id", id);

        TextMessage message = session.createTextMessage();
        message.setText(record.toString());
        message.setJMSReplyTo(tempDest);
        producer.send(lookupQueue, message);

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

From source file:com.espertech.esper.example.servershell.ServerShellMain.java

public ServerShellMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }/* ww  w  .  j  a va2s . c om*/
    properties.load(propertiesIS);

    // Start RMI registry
    log.info("Starting RMI registry");
    int port = Integer.parseInt(properties.getProperty(ServerShellConstants.MGMT_RMI_PORT));
    LocateRegistry.createRegistry(port);

    // Obtain MBean servera
    log.info("Obtaining JMX server and connector");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    String jmxServiceURL = properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL);
    JMXServiceURL jmxURL = new JMXServiceURL(jmxServiceURL);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(jmxURL, null, mbs);
    cs.start();

    // Initialize engine
    log.info("Getting Esper engine instance");
    Configuration configuration = new Configuration();
    configuration.addEventType("SampleEvent", SampleEvent.class.getName());
    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(configuration);

    // Initialize engine
    log.info("Creating sample statement");
    SampleStatement.createStatement(engine.getEPAdministrator());

    // Register MBean
    log.info("Registering MBean");
    ObjectName name = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMX mbean = new EPServiceProviderJMX(engine);
    mbs.registerMBean(mbean, name);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    int numListeners = Integer.parseInt(properties.getProperty(ServerShellConstants.JMS_NUM_LISTENERS));
    log.info("Creating " + numListeners + " listeners to destination '" + destination + "'");

    SampleJMSMessageListener listeners[] = new SampleJMSMessageListener[numListeners];
    for (int i = 0; i < numListeners; i++) {
        listeners[i] = new SampleJMSMessageListener(engine.getEPRuntime());
        MessageConsumer consumer = jmsCtx.getSession().createConsumer(jmsCtx.getDestination());
        consumer.setMessageListener(listeners[i]);
    }

    // Start processing
    log.info("Starting JMS connection");
    jmsCtx.getConnection().start();

    // Register shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            isShutdown = true;
        }
    });

    // Report statistics
    long startTime = System.currentTimeMillis();
    long currTime;
    double deltaSeconds;
    int lastTotalEvents = 0;
    AccumulatingStat avgLast5 = new AccumulatingStat(5);
    AccumulatingStat avgLast10 = new AccumulatingStat(10);
    AccumulatingStat avgLast20 = new AccumulatingStat(20);
    do {
        // sleep
        Thread.sleep(1000);
        currTime = System.currentTimeMillis();
        deltaSeconds = (currTime - startTime) / 1000.0;

        // compute stats
        int totalEvents = 0;
        for (int i = 0; i < listeners.length; i++) {
            totalEvents += listeners[i].getCount();
        }

        double totalLastBatch = totalEvents - lastTotalEvents;

        avgLast5.add(totalLastBatch);
        avgLast10.add(totalLastBatch);
        avgLast20.add(totalLastBatch);

        log.info("total=" + totalEvents + " last=" + totalLastBatch + " last5Avg=" + avgLast5.getAvg()
                + " last10Avg=" + avgLast10.getAvg() + " last20Avg=" + avgLast20.getAvg() + " time="
                + deltaSeconds);
        lastTotalEvents = totalEvents;
    } while (!isShutdown);

    log.info("Shutting down server");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up JNDI context
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("queue.QUEUE", "BasicQueue");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);
    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up queue
    Destination queue = (Destination) context.lookup("QUEUE");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side separately with minimal clutter
    {/*  w  ww  .  j av  a  2 s  .  c om*/
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(queue);

        // Send messages
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    {
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // Create consumer
        MessageConsumer consumer = session.createConsumer(queue);
        // create a listener callback to receive the messages
        consumer.setMessageListener(message -> {
            try {
                // receives message is passed to callback
                System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter
                        message.getJMSMessageID());
                message.acknowledge();
            } catch (Exception e) {
                logger.error(e);
            }
        });

        // wait on the main thread until all sent messages have been received
        while (totalReceived.get() < totalSend) {
            Thread.sleep(1000);
        }
        consumer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:Chat.java

/** Create JMS client for publishing and subscribing to messages. */
private void chatter(String broker, String username, String password) {
    // Create a connection.
    try {//from w ww.  j a  v a 2  s  .  co 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);
        javax.jms.MessageConsumer subscriber = subSession.createConsumer(topic);
        subscriber.setMessageListener(this);
        publisher = pubSession.createProducer(topic);
        // Now that setup is complete, start the Connection
        connect.start();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }

    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("\nChat application:\n" + "=================\n" + "The application user " + username
                + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n"
                + "The application will publish messages to the " + APP_TOPIC + " topic.\n"
                + "The application also subscribes to that topic to consume any messages published there.\n\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);
                publisher.send(msg);
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
}

From source file:org.dhatim.routing.jms.activemq.ActiveMQProvider.java

private void addListener(String destinationName, MessageListener listener, Session session)
        throws JMSException {
    Destination destination = lookupDestination(destinationName);
    MessageConsumer consumer = session.createConsumer(destination);

    consumer.setMessageListener(listener);
    consumers.add(consumer);//from  w ww  . j a  v  a  2  s.  c o m
}

From source file:org.apache.qpid.multiconsumer.AMQTest.java

public void testCompression() throws Exception {
    setup();//from   www.ja v a2  s. c  o m
    String comp = this.compressString(HUGECONTENT);
    try {
        MsgHandler listener = new MsgHandler();
        MessageConsumer subscriber = subSession.createConsumer(topic);
        subscriber.setMessageListener(listener);
        MessageProducer publisher = pubSession.createProducer(topic);

        // Send a single message
        TextMessage msg = pubSession.createTextMessage();
        // Set the compressed text
        msg.setText(comp);
        msg.setBooleanProperty(COMPRESSION_PROPNAME, true);
        publisher.send(msg);
        Thread.sleep(1000);
        // Check listeners to ensure we got it
        if (listener.isGotIt()) {
            System.out.println("Got callback for listener");
        } else {
            TestCase.fail("Listener did not get callback");
        }
    } finally {
        close();
    }
}

From source file:org.apache.qpid.multiconsumer.AMQTest.java

public void testMultipleListeners() throws Exception {
    setup();/*from   w w w .j a va  2 s.c  o  m*/
    try {
        // Create 5 listeners
        MsgHandler[] listeners = new MsgHandler[5];
        for (int i = 0; i < listeners.length; i++) {
            listeners[i] = new MsgHandler();
            MessageConsumer subscriber = subSession.createConsumer(topic);
            subscriber.setMessageListener(listeners[i]);
        }
        MessageProducer publisher = pubSession.createProducer(topic);
        // Send a single message
        TextMessage msg = pubSession.createTextMessage();
        msg.setText(DUMMYCONTENT);
        publisher.send(msg);
        Thread.sleep(5000);
        // Check listeners to ensure they all got it
        for (int i = 0; i < listeners.length; i++) {
            if (listeners[i].isGotIt()) {
                System.out.println("Got callback for listener " + i);
            } else {
                TestCase.fail("Listener " + i + " did not get callback");
            }
        }
    } catch (Throwable e) {
        System.err.println("Error: " + e);
        e.printStackTrace(System.err);
    } finally {
        close();
    }
}

From source file:org.apache.activemq.network.MQTTNetworkOfBrokersFailoverTest.java

private CountDownLatch listenForConsumersOn(BrokerService broker) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);

    URI brokerUri = broker.getVmConnectorURI();

    final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(brokerUri.toASCIIString());
    final Connection connection = cf.createConnection();
    connection.start();//from  w  ww.  j  ava 2  s. co  m
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination dest = session
            .createTopic("ActiveMQ.Advisory.Consumer.Queue.Consumer.foo:AT_LEAST_ONCE.VirtualTopic.foo.bar");
    MessageConsumer consumer = session.createConsumer(dest);
    consumer.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            latch.countDown();
            // shutdown this connection
            Dispatch.getGlobalQueue().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        session.close();
                        connection.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    });

    return latch;
}

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

/**
 * Inits the.//w  ww.j  a v a2 s  .com
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {

    connection = connFactory.createConnection();
    //session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    // lets make it transactional
    session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue controllerQueue = session.createQueue(ctrlrQueueName);

    MessageConsumer consumer = session.createConsumer(controllerQueue);

    consumer.setMessageListener(this);
    connection.start();

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

From source file:TopicReplier.java

/** Create JMS client for publishing and subscribing to messages. */
private void start(String broker, String username, String password, String mode) {
    // Set the operation mode
    imode = (mode.equals("uppercase")) ? UPPERCASE : LOWERCASE;

    // Create a connection.
    try {//  www . ja  v a  2  s  .  co m
        javax.jms.ConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createConnection(username, password);
        session = connect.createSession(true, 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 Subscriber to application topics as well as a Publisher
    // to use for JMS replies.
    try {
        javax.jms.Topic topic = session.createTopic(APP_TOPIC);
        javax.jms.MessageConsumer subscriber = session.createConsumer(topic);
        subscriber.setMessageListener(this);
        replier = session.createProducer(null); // Topic will be set for each reply
        // Now that all setup is complete, start the Connection
        connect.start();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }

    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));
        while (true) {
            System.out.println("\nReplier application:\n" + "============================\n"
                    + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME
                    + ".\n" + "The application gets requests with JMSReplyTo set on the " + APP_TOPIC
                    + " topic."
                    + "The message is transformed to all uppercase or all lowercase, and then returned to the requestor."
                    + "The Requestor application displays the result.\n\n"
                    + "Enter EXIT or press Ctrl+C to close the Replier.\n");
            String s = stdin.readLine();
            if (s == null || s.equalsIgnoreCase("EXIT")) {
                System.out.println("\nStopping Replier. Please wait..\n>");
                exit();
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    }
}