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:siia.jms.MessageListenerContainerDemo.java

public static void main(String[] args) {
    // establish common resources
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
    Destination queue = new ActiveMQQueue("siia.queue");
    // setup and start listener container
    DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setDestination(queue);// w  ww  . ja  v a2s.c o  m
    container.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            try {
                if (!(message instanceof TextMessage)) {
                    throw new IllegalArgumentException("expected TextMessage");
                }
                System.out.println("received: " + ((TextMessage) message).getText());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        }
    });
    container.afterPropertiesSet();
    container.start();
    // send Message
    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setDefaultDestination(queue);
    jmsTemplate.convertAndSend("Hello World");
}

From source file:example.transaction.Client.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();//from   ww w  .j  av a2s  .  com
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {
        connection = connectionFactory.createConnection();
        connection.start();
        Topic destination = new ActiveMQTopic("transacted.client.example");

        Session senderSession = connection.createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Session receiverSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer receiver = receiverSession.createConsumer(destination);
        receiver.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (message instanceof TextMessage) {
                    try {
                        String value = ((TextMessage) message).getText();
                        System.out.println("We received a new message: " + value);
                    } catch (JMSException e) {
                        System.out.println("Could not read the receiver's topic because of a JMSException");
                    }
                }
            }
        });

        MessageProducer sender = senderSession.createProducer(destination);

        connection.start();
        acceptInputFromUser(senderSession, sender);
        senderSession.close();
        receiverSession.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:example.wildcard.Client.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();// w w  w  .  j a  v  a  2 s  .  com
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {
        Topic senderTopic = new ActiveMQTopic(System.getProperty("topicName"));

        connection = connectionFactory.createConnection("admin", "password");

        Session senderSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        MessageProducer sender = senderSession.createProducer(senderTopic);

        Session receiverSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);

        String policyType = System.getProperty("wildcard", ".*");
        String receiverTopicName = senderTopic.getTopicName() + policyType;
        Topic receiverTopic = receiverSession.createTopic(receiverTopicName);

        MessageConsumer receiver = receiverSession.createConsumer(receiverTopic);
        receiver.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        String text = ((TextMessage) message).getText();
                        System.out.println("We received a new message: " + text);
                    }
                } catch (JMSException e) {
                    System.out.println("Could not read the receiver's topic because of a JMSException");
                }
            }
        });

        connection.start();
        System.out.println("Listening on '" + receiverTopicName + "'");
        System.out.println("Enter a message to send: ");

        Scanner inputReader = new Scanner(System.in);

        while (true) {
            String line = inputReader.nextLine();
            if (line == null) {
                System.out.println("Done!");
                break;
            } else if (line.length() > 0) {
                try {
                    TextMessage message = senderSession.createTextMessage();
                    message.setText(line);
                    System.out.println("Sending a message: " + message.getText());
                    sender.send(message);
                } catch (JMSException e) {
                    System.out.println("Exception during publishing a message: ");
                }
            }
        }

        receiver.close();
        receiverSession.close();
        sender.close();
        senderSession.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("When trying to close connection: ");
            }
        }
    }

}

From source file:example.tempdest.ProducerRequestReply.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();// w ww.  ja va2  s. c  om
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test-queue");
        MessageProducer producer = session.createProducer(destination);
        Destination replyDest = session.createTemporaryQueue();

        // set up the consumer to handle the reply
        MessageConsumer replyConsumer = session.createConsumer(replyDest);
        replyConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                System.out.println("*** REPLY *** ");
                System.out.println(message.toString());
            }
        });

        TextMessage message = session.createTextMessage("I need a response for this, please");
        message.setJMSReplyTo(replyDest);

        producer.send(message);

        // wait for a response
        TimeUnit.SECONDS.sleep(2);
        producer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:com.fusesource.forge.jmstest.tests.simple.SimpleConsumer.java

protected void run() {
    Connection con = null;//from   w  w w  .  ja v a2 s.  c om
    Session session = null;
    final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);
    try {
        con = getConnection();
        session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination dest = getDestinationProvider().getDestination(session, "queue:TEST");
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                String grp = null;
                long nr = 0L;
                try {
                    grp = msg.getStringProperty("JMSXGroupID");
                    nr = msg.getLongProperty("MsgNr");
                } catch (JMSException jme) {
                }
                log().info("Received Message Group=(" + grp + ") MsgNr=" + nr);
                latch.countDown();
            }
        });
        con.start();
        latch.await();
        con.close();
    } catch (Exception e) {
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.apache.servicemix.samples.bridge.BridgeTest.java

public void testSimpleCall() throws Exception {

    ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
    Destination outQueue = new ActiveMQQueue("bridge.output");
    Connection connection = factory.createConnection();
    connection.start();/*from ww  w  .  ja  v  a  2  s .c o  m*/
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer createConsumer = session.createConsumer(outQueue);
    createConsumer.setMessageListener(new MessageListener() {

        public void onMessage(Message arg0) {
            BridgeTest.recieved = true;
            ActiveMQTextMessage msg = (ActiveMQTextMessage) arg0;
            assertNotNull(msg);
        }

    });

    HttpClient client = new HttpClient();

    PostMethod post = new PostMethod(url);
    post.setRequestBody(new FileInputStream("src/test/resources/request.xml"));

    int executeMethod = client.executeMethod(post);

    assertEquals(202, executeMethod);

    int maxTry = 100;
    while (!recieved || maxTry == 0) {
        Thread.sleep(200);
        maxTry--;
    }

    session.close();
    connection.close();

}

From source file:org.openengsb.ports.jms.JMSIncomingPort.java

public void start() {
    simpleMessageListenerContainer = createListenerContainer(receive, new MessageListener() {
        @Override/*from  ww  w.j  a  v a2s  .c  om*/
        public void onMessage(Message message) {
            LOGGER.trace("JMS-message recieved. Checking if the type is supported");
            if (!(message instanceof TextMessage)) {
                LOGGER.debug("Received JMS-message is not type of text message.");
                return;
            }
            LOGGER.trace("Received a text message and start parsing");
            TextMessage textMessage = (TextMessage) message;
            String textContent = extractTextFromMessage(textMessage);
            HashMap<String, Object> metadata = new HashMap<String, Object>();
            String result = null;
            try {
                LOGGER.debug("starting filterchain for incoming message");
                result = (String) getFilterChainToUse().filter(textContent, metadata);
            } catch (Exception e) {
                LOGGER.error("an error occured when processing the filterchain", e);
                result = ExceptionUtils.getStackTrace(e);
            }
            Destination replyQueue;
            final String correlationID;
            try {
                if (message.getJMSCorrelationID() == null) {
                    correlationID = message.getJMSMessageID();
                } else {
                    correlationID = message.getJMSCorrelationID();
                }
                replyQueue = message.getJMSReplyTo();
            } catch (JMSException e) {
                LOGGER.warn("error when getting destination queue or correlationid from client message: {}", e);
                return;
            }
            if (replyQueue == null) {
                LOGGER.warn("no replyTo destination specifyed could not send response");
                return;
            }

            new JmsTemplate(connectionFactory).convertAndSend(replyQueue, result, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws JMSException {
                    message.setJMSCorrelationID(correlationID);
                    return message;
                }
            });
        }

        private String extractTextFromMessage(TextMessage textMessage) {
            try {
                return textMessage.getText();
            } catch (JMSException e) {
                throw new IllegalStateException("Couldn't extract text from jms message", e);
            }
        }

    });
    simpleMessageListenerContainer.start();
}

From source file:de.adorsys.jmspojo.JMSJavaFutureAdapterTest.java

@Before
public void setup() throws Exception {
    broker = new BrokerService();
    broker.setPersistent(false);//from ww  w  . j  a  va 2  s .c  om

    // configure the broker
    broker.addConnector("vm://test");
    broker.setBrokerName("test");
    broker.setUseShutdownHook(false);

    broker.start();

    cf = new ActiveMQConnectionFactory("vm://localhost?create=false");
    qc = cf.createQueueConnection();
    QueueSession createQueueSession = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    testQueue = createQueueSession.createQueue("TestQueue");
    createQueueSession.createReceiver(testQueue).setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                boolean sendTimeout = message.getBooleanProperty("timeout");
                boolean sendError = message.getBooleanProperty("error");
                if (sendError) {
                    JMSJavaFutureAdapter<PingMessage> jmsSender = new JMSJavaFutureAdapter<PingMessage>(
                            objectMapper, cf, null, TIMEOUT);
                    HashMap<String, Object> messageProperties = new HashMap<String, Object>();
                    messageProperties.put("ERROR", "test error");
                    jmsSender.send(message.getJMSReplyTo(), messageProperties, null);
                } else if (!sendTimeout) {
                    JMSJavaFutureAdapter<PingMessage> jmsSender = new JMSJavaFutureAdapter<PingMessage>(
                            objectMapper, cf, null, TIMEOUT);
                    jmsSender.send(message.getJMSReplyTo(), null, ((TextMessage) message).getText());
                }

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

}

From source file:org.audit4j.core.AsyncAuditEngine.java

/**
 * Listen./*from   ww  w .  j av a  2 s  .com*/
 */
public void listen() {
    try {
        final MessageConsumer consumer = session.createConsumer(destination);

        final MessageListener listener = new MessageListener() {

            @Override
            public void onMessage(final Message message) {
                try {
                    final ObjectMessage objectMessage = (ObjectMessage) message;
                    final Object object = objectMessage.getObject();
                    if (object instanceof AnnotationAuditEvent) {
                        AsynchronousAnnotationProcessor processor = AsynchronousAnnotationProcessor
                                .getInstance();
                        processor.process((AnnotationAuditEvent) object);
                    } else if (object instanceof AsyncCallAuditDto) {

                    }
                } catch (final JMSException e) {
                    e.printStackTrace();
                }
                try {
                    message.acknowledge();
                } catch (final JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("Received Message");
            }
        };

        consumer.setMessageListener(listener);

    } catch (final Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
    }
}

From source file:de.adorsys.jmspojo.JMSServiceAdapterFactoryTest.java

@Before
public void setup() throws Exception {
    broker = new BrokerService();
    broker.setPersistent(false);//from  ww w.java2 s.co  m

    // configure the broker
    broker.addConnector("vm://test");
    broker.setBrokerName("test");
    broker.setUseShutdownHook(false);

    broker.start();

    cf = new ActiveMQConnectionFactory("vm://localhost?create=false");
    qc = cf.createQueueConnection();
    QueueSession createQueueSession = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    defaultQueue = createQueueSession.createQueue("TestQueue");
    createQueueSession.createReceiver(defaultQueue).setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                boolean sendTimeout = message.getBooleanProperty("timeout");
                if (!sendTimeout) {
                    JMSJavaFutureAdapter<PingMessage> jmsSender = new JMSJavaFutureAdapter<PingMessage>(
                            OBJECT_MAPPER, cf, null, JMS_TIMEOUT);
                    jmsSender.send(message.getJMSReplyTo(), null, ((TextMessage) message).getText());
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });

    dedicatedQueue = createQueueSession.createQueue("DedicatedQueue");
    createQueueSession.createReceiver(dedicatedQueue).setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                JMSJavaFutureAdapter<PingMessage> jmsSender = new JMSJavaFutureAdapter<PingMessage>(
                        OBJECT_MAPPER, cf, null, JMS_TIMEOUT);
                PingMessage data = new PingMessage();
                data.setPing("dedicted response");
                jmsSender.send(message.getJMSReplyTo(), null, data);
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });
    qc.start();

    JMSServiceAdapterFactory jmsServiceStubFactory = new JMSServiceAdapterFactory(OBJECT_MAPPER, cf,
            defaultQueue, JMS_TIMEOUT);
    service = jmsServiceStubFactory.generateJMSServiceProxy(JMSSampleService.class);

}