Example usage for javax.jms Session createConsumer

List of usage examples for javax.jms Session createConsumer

Introduction

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

Prototype

MessageConsumer createConsumer(Destination destination, java.lang.String messageSelector) throws JMSException;

Source Link

Document

Creates a MessageConsumer for the specified destination, using a message selector.

Usage

From source file:example.queue.selector.Consumer.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();/*from   w ww . j a v  a2s  .c  o  m*/
    }
    System.out.println("\nWaiting to receive messages... will timeout after " + TIMEOUT / 1000 + "s");
    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");
        MessageConsumer consumer = session.createConsumer(destination, "intended = 'me'");

        int i = 0;
        while (true) {
            Message message = consumer.receive(TIMEOUT);

            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    System.out.println("Got " + i++ + ". message: " + text);
                }
            } else {
                break;
            }
        }

        consumer.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:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * retrieve meta information for a UIMA-AS Service attached to a broker
 * It uses the port 1099 as the JMX port on the broker, unless overridden
 *   by defining the system property activemq.broker.jmx.port with a value of another port number
 * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden
 *   by defining the system property activemq.broker.jmx.domain with a value of the domain to use
 *   This normally never needs to be done unless multiple brokers are run on the same node 
 *   as is sometimes done for unit tests.
 * @param args - brokerUri serviceName [-verbose]
 *///from ww  w. j a  va2s  .  c  o m
public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Need arguments: brokerURI serviceName [-verbose]");
        System.exit(1);
    }
    String brokerURI = args[0];
    String queueName = args[1];
    boolean printReply = false;
    if (args.length > 2) {
        if (args[2].equalsIgnoreCase("-verbose")) {
            printReply = true;
        } else {
            System.err.println("Unknown argument: " + args[2]);
            System.exit(1);
        }
    }
    final Connection connection;
    Session producerSession = null;
    Queue producerQueue = null;
    MessageProducer producer;
    MessageConsumer consumer;
    Session consumerSession = null;
    TemporaryQueue consumerDestination = null;
    long startTime = 0;

    //  Check if JMX server port number was specified
    jmxPort = System.getProperty("activemq.broker.jmx.port");
    if (jmxPort == null || jmxPort.trim().length() == 0) {
        jmxPort = "1099"; // default
    }

    try {
        //  First create connection to a broker
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI);
        connection = factory.createConnection();
        connection.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                    if (jmxc != null) {
                        jmxc.close();
                    }
                } catch (Exception ex) {
                }
            }
        }));

        URI target = new URI(brokerURI);
        String brokerHost = target.getHost();

        attachToRemoteBrokerJMXServer(brokerURI);
        if (isQueueAvailable(queueName) == QueueState.exists) {
            System.out.println("Queue " + queueName + " found on " + brokerURI);
            System.out.println("Sending getMeta...");
        } else if (isQueueAvailable(queueName) == QueueState.existsnot) {
            System.err.println("Queue " + queueName + " does not exist on " + brokerURI);
            System.exit(1);
        } else {
            System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort);
            System.out.println("Sending getMeta anyway...");
        }

        producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producerQueue = producerSession.createQueue(queueName);
        producer = producerSession.createProducer(producerQueue);
        consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumerDestination = consumerSession.createTemporaryQueue();
        //  -----------------------------------------------------------------------------
        //  Create message consumer. The consumer uses a selector to filter out messages other
        //  then GetMeta replies. Currently UIMA AS service returns two messages for each request:
        //  ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the 
        //  service immediately upon receiving a message from a client. This serves dual purpose, 
        //  1) to make sure the client reply destination exists
        //  2) informs the client which service is processing its request
        //  -----------------------------------------------------------------------------
        consumer = consumerSession.createConsumer(consumerDestination, "Command=2001");
        TextMessage msg = producerSession.createTextMessage();
        msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName());
        msg.setStringProperty(UIMAMessage.ServerURI, brokerURI);
        msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request);
        msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta);
        msg.setJMSReplyTo(consumerDestination);
        msg.setText("");
        producer.send(msg);
        startTime = System.nanoTime();

        System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI);
        System.out.println("Waiting for getMeta reply...");
        ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive();
        long waitTime = (System.nanoTime() - startTime) / 1000000;

        System.out.println(
                "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms");
        if (printReply) {
            System.out.println("Reply MessageText: " + reply.getText());
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    System.exit(0);
}

From source file:com.adaptris.core.jms.VendorImplementationImp.java

@Override
public MessageConsumer createQueueReceiver(ConsumeDestination cd, JmsActorConfig c) throws JMSException {
    Session s = c.currentSession();
    Queue q = createQueue(cd.getDestination(), c);
    return s.createConsumer(q, cd.getFilterExpression());
}

From source file:org.springframework.integration.jms.JmsOutboundGatewayTests.java

@Test
public void testReplyContainerRecovery() throws Exception {
    JmsOutboundGateway gateway = new JmsOutboundGateway();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestDestinationName("foo");
    gateway.setUseReplyContainer(true);/*from w w  w  .java2s. c o  m*/
    ReplyContainerProperties replyContainerProperties = new ReplyContainerProperties();
    final List<Throwable> errors = new ArrayList<Throwable>();
    ErrorHandlingTaskExecutor errorHandlingTaskExecutor = new ErrorHandlingTaskExecutor(
            Executors.newFixedThreadPool(10), new ErrorHandler() {

                @Override
                public void handleError(Throwable t) {
                    logger.info("Error:", t);
                    errors.add(t);
                    throw new RuntimeException(t);
                }
            });
    replyContainerProperties.setTaskExecutor(errorHandlingTaskExecutor);
    replyContainerProperties.setRecoveryInterval(100L);
    gateway.setReplyContainerProperties(replyContainerProperties);
    final Connection connection = mock(Connection.class);
    final AtomicInteger connectionAttempts = new AtomicInteger();
    doAnswer(new Answer<Connection>() {

        @SuppressWarnings("serial")
        @Override
        public Connection answer(InvocationOnMock invocation) throws Throwable {
            int theCount = connectionAttempts.incrementAndGet();
            if (theCount > 1 && theCount < 4) {
                throw new JmsException("bar") {
                };
            }
            return connection;
        }
    }).when(connectionFactory).createConnection();
    Session session = mock(Session.class);
    when(connection.createSession(false, 1)).thenReturn(session);
    MessageConsumer consumer = mock(MessageConsumer.class);
    when(session.createConsumer(any(Destination.class), anyString())).thenReturn(consumer);
    when(session.createTemporaryQueue()).thenReturn(mock(TemporaryQueue.class));
    final Message message = mock(Message.class);
    final AtomicInteger count = new AtomicInteger();
    doAnswer(new Answer<Message>() {

        @SuppressWarnings("serial")
        @Override
        public Message answer(InvocationOnMock invocation) throws Throwable {
            int theCount = count.incrementAndGet();
            if (theCount > 1 && theCount < 4) {
                throw new JmsException("foo") {
                };
            }
            if (theCount > 4) {
                Thread.sleep(100);
                return null;
            }
            return message;
        }
    }).when(consumer).receive(anyLong());
    when(message.getJMSCorrelationID()).thenReturn("foo");
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    beanFactory.registerSingleton("taskScheduler", taskScheduler);
    gateway.setBeanFactory(beanFactory);
    gateway.afterPropertiesSet();
    gateway.start();
    Thread.sleep(1000);
    assertTrue(count.get() > 4);
    assertEquals(0, errors.size());
}

From source file:org.apache.servicemix.jbi.cluster.requestor.AbstractJmsRequestorPool.java

/**
 * Create a JMS MessageConsumer for the given Session and Destination.
 * <p>This implementation uses JMS 1.1 API.
 * @param session the JMS Session to create a MessageConsumer for
 * @param destination the JMS Destination to create a MessageConsumer for
 * @return the new JMS MessageConsumer/* w ww  . j  a  v a  2s .  c  o m*/
 * @throws javax.jms.JMSException if thrown by JMS API methods
 */
protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException {
    return session.createConsumer(destination, getMessageSelector());
}

From source file:org.seedstack.jms.internal.JmsPlugin.java

private MessageConsumer createMessageConsumer(MessageListenerDefinition messageListenerDefinition)
        throws JMSException {
    LOGGER.debug("Creating JMS consumer for listener {}", messageListenerDefinition.getName());

    MessageConsumer consumer;/*from   w  ww . j a  va2  s .c o m*/
    Session session = messageListenerDefinition.getSession();

    if (StringUtils.isNotBlank(messageListenerDefinition.getSelector())) {
        consumer = session.createConsumer(messageListenerDefinition.getDestination(),
                messageListenerDefinition.getSelector());
    } else {
        consumer = session.createConsumer(messageListenerDefinition.getDestination());
    }

    MessagePoller messagePoller;
    if (messageListenerDefinition.getPoller() != null) {
        try {
            LOGGER.debug("Creating poller for JMS listener {}", messageListenerDefinition.getName());

            Connection connection = connections.get(messageListenerDefinition.getConnectionName());

            messagePoller = messageListenerDefinition.getPoller().newInstance();
            messagePoller.setSession(session);
            messagePoller.setMessageConsumer(consumer);
            messagePoller.setMessageListener(new MessageListenerAdapter(messageListenerDefinition.getName()));

            if (connection instanceof ManagedConnection) {
                messagePoller.setExceptionListener((ExceptionListener) connection);
            } else {
                messagePoller.setExceptionListener(connection.getExceptionListener());
            }
        } catch (Exception e) {
            throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_POLLER).put("pollerClass",
                    messageListenerDefinition.getPoller());
        }

        pollers.put(messageListenerDefinition.getName(), messagePoller);
    } else {
        consumer.setMessageListener(new MessageListenerAdapter(messageListenerDefinition.getName()));
    }

    return consumer;
}

From source file:com.adaptris.core.jms.VendorImplementationImp.java

@Override
public MessageConsumer createTopicSubscriber(ConsumeDestination cd, String subscriptionId, JmsActorConfig c)
        throws JMSException {
    Session s = c.currentSession();
    Topic t = createTopic(cd.getDestination(), c);
    MessageConsumer result = null;/*w w w. jav  a  2s . co  m*/
    if (!isEmpty(subscriptionId)) {
        result = s.createDurableSubscriber(t, subscriptionId, cd.getFilterExpression(), false);
    } else {
        result = s.createConsumer(t, cd.getFilterExpression());
    }
    return result;
}

From source file:org.jbpm.bpel.integration.server.SoapHandler.java

protected ObjectMessage receiveResponse(Session jmsSession, Destination replyTo, String requestId,
        JbpmContext jbpmContext) throws JMSException, SOAPFaultException {
    // set up consumer
    String selector = "JMSCorrelationID='" + requestId + '\'';
    MessageConsumer consumer = jmsSession.createConsumer(replyTo, selector);
    try {/*w ww . ja  va  2s  .c om*/
        // receive response message
        log.debug("listening for response: destination=" + replyTo + ", requestId=" + requestId);
        Number responseTimeout = getResponseTimeout(jbpmContext);
        ObjectMessage jmsResponse = (ObjectMessage) (responseTimeout != null
                ? consumer.receive(responseTimeout.longValue())
                : consumer.receive());
        // did a message arrive in time?
        if (jmsResponse == null) {
            log.debug("response timeout expired: destination=" + replyTo + ", requestId" + requestId);
            throw new SOAPFaultException(SoapBindConstants.SERVER_FAULTCODE,
                    SoapBindConstants.TIMEOUT_FAULTSTRING, null, null);
        }
        jmsResponse.acknowledge();
        log.debug("received response: " + RequestListener.messageToString(jmsResponse));
        return jmsResponse;
    } finally {
        // release consumer resources
        consumer.close();
    }
}

From source file:fr.xebia.sample.springframework.jms.requestreply.RequestReplyClientInvoker.java

/**
 * Request/Reply SpringFramework sample.
 * /*w  w w.j a  v  a  2  s .c om*/
 * @param request
 *            sent to the remote service
 * @return reply returned by the remote service
 * @throws JMSException
 */
public String requestReply(String request) throws JMSException {

    Connection connection = connectionFactory.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        try {
            MessageProducer messageProducer = session.createProducer(this.requestDestination);
            try {
                Message requestMessage = session.createTextMessage(request);
                requestMessage.setJMSReplyTo(this.replyToDestination);
                // requestMessage.setJMSCorrelationID(String.valueOf(random.nextLong()));

                messageProducer.send(requestMessage);
                String messageSelector = "JMSCorrelationID  LIKE '" + requestMessage.getJMSMessageID() + "'";

                MessageConsumer messageConsumer = session.createConsumer(this.replyToDestination,
                        messageSelector);
                TextMessage replyMessage = (TextMessage) messageConsumer.receive(timeoutInMillis);
                Assert.notNull(replyMessage, "Timeout waiting for jms response");
                logger.debug(
                        "requestReply " + "\r\nrequest : " + requestMessage + "\r\nreply : " + replyMessage);
                String result = replyMessage.getText();
                logger.debug("requestReply('" + request + "'): '" + result + "'");
                return result;
            } finally {
                JmsUtils.closeMessageProducer(messageProducer);
            }
        } finally {
            JmsUtils.closeSession(session);
        }
    } finally {
        JmsUtils.closeConnection(connection);
    }
}

From source file:org.jbpm.bpel.integration.jms.RequestListener.java

RequestListener(ReceiveAction receiveAction, Token token, IntegrationControl integrationControl,
        Session jmsSession, boolean oneShot) throws JMSException {
    this.receiveActionId = receiveAction.getId();
    this.tokenId = token.getId();

    this.integrationControl = integrationControl;
    this.jmsSession = jmsSession;

    this.oneShot = oneShot;

    // create message consumer
    Destination destination = integrationControl.getPartnerLinkEntry(receiveAction.getPartnerLink())
            .getDestination();/*from  w w  w .ja  va 2 s  .  com*/
    String selector = formatSelector(receiveAction, token);
    this.messageConsumer = jmsSession.createConsumer(destination, selector);

    integrationControl.addRequestListener(this);
    log.debug("created request listener: receiveAction=" + receiveAction + ", token=" + token);
}