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.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();/*  www. j  av  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.logicblaze.lingo.jmx.remote.jms.MBeanJmsServerConnectionClient.java

/**
 * Construct this thing/*from  w  w w  .  ja v  a 2s.  co  m*/
 * 
 * @param connection
 * @throws JMSException
 */
public MBeanJmsServerConnectionClient(MBeanJmsServerConnection connection, Connection jmsConnection)
        throws JMSException {
    super(connection);
    this.serverConnection = connection;
    Session jmsSession = jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    replyToDestination = jmsSession.createTemporaryTopic();
    MessageConsumer consumer = jmsSession.createConsumer(replyToDestination);
    consumer.setMessageListener(this);
}

From source file:com.opengamma.examples.analyticservice.ExampleAnalyticServiceUsage.java

private void pushTrade(String securityId, Connection connection, String destinationName,
        JmsConnector jmsConnector, JmsByteArrayMessageDispatcher jmsDispatcher) {
    String providerId = generateTrade(securityId, destinationName, jmsConnector);
    String topicStr = PREFIX + SEPARATOR + providerId + SEPARATOR + "Default" + SEPARATOR
            + ValueRequirementNames.FAIR_VALUE;
    try {//from  ww w  . j av  a  2s  .  c  o  m
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(topicStr);
        final MessageConsumer messageConsumer = session.createConsumer(topic);
        messageConsumer.setMessageListener(jmsDispatcher);
    } catch (JMSException e) {
        throw new OpenGammaRuntimeException("Failed to create subscription to JMS topics ", e);
    }
}

From source file:biz.fstechnology.micro.server.jms.AbstractJmsService.java

/**
 * @see biz.fstechnology.micro.server.Service#init()
 *///from  w ww  .  j  a  va2s  .  c o m
@Override
public void init() throws Exception {
    Connection connection = createJmsTemplate().getConnectionFactory().createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(getListenTopic()));
    consumer.setMessageListener(this);

    replyProducer = session.createProducer(null);
    replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    connection.start();
}

From source file:biz.fstechnology.micro.common.jms.SyncSessionCallbackImpl.java

/**
 * @see org.springframework.jms.core.SessionCallback#doInJms(javax.jms.Session)
 *///w  ww . j a  va  2  s . c o  m
@Override
public T doInJms(Session session) throws JMSException {
    Topic destTopic = session.createTopic(topicName);
    TemporaryQueue responseQueue = session.createTemporaryQueue();

    // oh my god...
    // why MessageProducer & MessageConsumer not have AutoCloseable!!!
    try (AutoCloseableWrapper<MessageProducer> producerCont = new AutoCloseableWrapper<>(
            () -> createProducer(session, destTopic), JmsUtils::closeMessageProducer);
            AutoCloseableWrapper<MessageConsumer> consumerCont = new AutoCloseableWrapper<>(
                    () -> createConsumer(session, responseQueue), JmsUtils::closeMessageConsumer)) {

        MessageProducer producer = producerCont.unwrap();
        MessageConsumer consumer = consumerCont.unwrap();
        consumer.setMessageListener(this);

        if (getMessageCreator() == null) {
            RequestMessageCreator messageCreator = new RequestMessageCreator();
            messageCreator.setContents(getMessageObj());
            setMessageCreator(messageCreator);
        }
        if (getMessageCreator() instanceof RequestMessageCreator) {
            ((RequestMessageCreator) getMessageCreator()).setReplyTo(responseQueue);
        }
        Message requestMessage = getMessageCreator().createMessage(session);
        producer.send(destTopic, requestMessage);

        if (getMessageCreator() instanceof RequestMessageCreator) {
            return waitResponse(consumer, requestMessage);
        } else {
            return null;
        }
    }
}

From source file:org.calrissian.mango.jms.stream.JmsFileTransferSupportTest.java

public void testFullCycle() throws Exception {
    try {/*  w  ww .ja  v  a 2  s  .  c  o  m*/
        URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {

            @Override
            public URLStreamHandler createURLStreamHandler(String protocol) {
                if ("testprot".equals(protocol))
                    return new URLStreamHandler() {

                        @Override
                        protected URLConnection openConnection(URL u) throws IOException {
                            return new URLConnection(u) {

                                @Override
                                public void connect() throws IOException {

                                }

                                @Override
                                public InputStream getInputStream() throws IOException {
                                    return new ByteArrayInputStream(TEST_STR.getBytes());
                                }

                                @Override
                                public String getContentType() {
                                    return "content/notnull";
                                }
                            };
                        }
                    };
                return null;
            }
        });
    } catch (Error ignored) {
    }

    final ActiveMQTopic ft = new ActiveMQTopic("testFileTransfer");

    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    te.initialize();

    JmsFileSenderListener listener = new JmsFileSenderListener();
    final String hashAlgorithm = "MD5";
    listener.setHashAlgorithm(hashAlgorithm);
    listener.setStreamRequestDestination(ft);
    listener.setPieceSize(9);
    listener.setTaskExecutor(te);

    ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    cf = new SingleTopicConnectionFactory(cf, "test");
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(60000);
    listener.setJmsTemplate(jmsTemplate);

    Connection conn = cf.createConnection();
    conn.start();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = sess.createConsumer(ft);
    consumer.setMessageListener(listener);

    JmsFileReceiver receiver = new JmsFileReceiver();
    receiver.setHashAlgorithm(hashAlgorithm);
    receiver.setStreamRequestDestination(ft);
    receiver.setJmsTemplate(jmsTemplate);
    receiver.setPieceSize(9);

    JmsFileReceiverInputStream stream = (JmsFileReceiverInputStream) receiver.receiveStream("testprot:test");
    StringBuilder buffer = new StringBuilder();
    int read;
    while ((read = stream.read()) >= 0) {
        buffer.append((char) read);
    }
    stream.close();

    assertEquals(TEST_STR, buffer.toString());

    conn.stop();

}

From source file:com.jaliansystems.activeMQLite.impl.RepositoryService.java

/**
 * Instantiates a new repository service.
 *
 * The queueNamePrefix is used to create a JMS queue with the name appending "-request" to it.
 * //from w ww.j  av a2 s. c o  m
 * @param connection the connection
 * @param brokerURL the broker url
 * @param queueNamePrefix the queue name prefix
 * @param objectRepository the object repository
 * @param client the client
 * @throws Exception the exception
 */
public RepositoryService(Connection connection, String brokerURL, String queueNamePrefix,
        ObjectRepository objectRepository, RepositoryClient client) throws Exception {
    this.objectRepository = objectRepository;
    this.client = client;

    sessionService = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination requestQueue = sessionService.createQueue(queueNamePrefix + "-request");
    MessageConsumer requestConsumer = sessionService.createConsumer(requestQueue);
    requestConsumer.setMessageListener(this);

    responseProducer = sessionService.createProducer(null);
    responseProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}

From source file:org.wso2.carbon.registry.caching.invalidator.connection.JMSNotification.java

@Override
public void subscribe() {
    try {//  www  .j a v a 2s .  co  m
        Session subSession = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE);
        MessageConsumer messageConsumer = subSession.createConsumer(destination);
        messageConsumer.setMessageListener(this);
        connection.start();
        log.info("Global cache invalidation is online");
    } catch (JMSException e) {
        log.error("Global cache invalidation: Error in subscribing to topic", e);
    }
}

From source file:org.apache.axis2.transport.jms.MockEchoEndpoint.java

@Setup
@SuppressWarnings("unused")
private void setUp(JMSTestEnvironment env, JMSRequestResponseChannel channel) throws Exception {
    Destination destination = channel.getDestination();
    Destination replyDestination = channel.getReplyDestination();
    connection = env.getConnectionFactory().createConnection();
    connection.setExceptionListener(this);
    connection.start();/*from ww w  .  ja v a  2  s  .c  om*/
    replyConnection = env.getConnectionFactory().createConnection();
    replyConnection.setExceptionListener(this);
    final Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final MessageProducer producer = replySession.createProducer(replyDestination);
    MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)
            .createConsumer(destination);
    consumer.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            try {
                log.info("Message received: ID = " + message.getJMSMessageID());
                Message reply;
                if (message instanceof BytesMessage) {
                    reply = replySession.createBytesMessage();
                    IOUtils.copy(new BytesMessageInputStream((BytesMessage) message),
                            new BytesMessageOutputStream((BytesMessage) reply));
                } else if (message instanceof TextMessage) {
                    reply = replySession.createTextMessage();
                    ((TextMessage) reply).setText(((TextMessage) message).getText());
                } else {
                    // TODO
                    throw new UnsupportedOperationException("Unsupported message type");
                }
                reply.setJMSCorrelationID(message.getJMSMessageID());
                reply.setStringProperty(BaseConstants.CONTENT_TYPE,
                        message.getStringProperty(BaseConstants.CONTENT_TYPE));
                producer.send(reply);
                log.info("Message sent: ID = " + reply.getJMSMessageID());
            } catch (Throwable ex) {
                fireEndpointError(ex);
            }
        }
    });
}

From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java

private void receiveFromSubscription(ConnectionStringBuilder csb, Context context, ConnectionFactory cf,
        String name) throws NamingException, JMSException, InterruptedException {
    AtomicInteger totalReceived = new AtomicInteger(0);
    System.out.printf("Subscription %s: \n", name);

    Destination subscription = (Destination) context.lookup(name);
    // Create Connection
    Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
    connection.start();//from w  w w  . jav  a2s  .co m
    // Create Session, no transaction, client ack
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    // Create consumer
    MessageConsumer consumer = session.createConsumer(subscription);
    // Set callback listener. Gets called for each received message.
    consumer.setMessageListener(message -> {
        try {
            System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the counter
                    message.getJMSMessageID());
            message.acknowledge();
        } catch (Exception e) {
            System.out.printf("%s", e.toString());
        }
    });

    // 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();
}