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) throws JMSException;

Source Link

Document

Creates a MessageConsumer for the specified destination.

Usage

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

public void testFullCycle() throws Exception {
    try {/*ww  w  .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:org.apache.activemq.camel.JmsJdbcXARollbackTest.java

private boolean consumedFrom(String qName) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://testXA");
    factory.setWatchTopicAdvisories(false);
    Connection connection = factory.createConnection();
    connection.start();//from   w w  w . ja  v  a 2  s . c o m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(qName));
    Message message = consumer.receive(500);
    LOG.info("Got from queue:{} {}", qName, message);
    connection.close();
    return message != null;
}

From source file:org.apache.falcon.regression.core.supportClasses.JmsMessageConsumer.java

@Override
public void run() {
    try {//from w  ww. j  a  v a2 s .  com
        // Getting JMS connection from the server
        Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection();
        connection.start();

        // Creating session for sending messages
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);

        try {
            LOGGER.info("Starting to receive messages.");
            int count = 0;
            for (; count < MAX_MESSAGE_COUNT; ++count) {
                Message message = consumer.receive(); //blocking call
                if (message == null) {
                    LOGGER.info("Received empty message, count = " + count);
                } else {
                    LOGGER.info("Received message, id = " + message.getJMSMessageID());
                    receivedMessages.add((MapMessage) message);
                }
            }
            if (count >= MAX_MESSAGE_COUNT) {
                LOGGER.warn("Not reading more messages, already read " + count + " messages.");
            }
        } finally {
            LOGGER.info("Stopping to receive messages.");
            connection.close();
        }
    } catch (Exception e) {
        LOGGER.info("caught exception: " + ExceptionUtils.getStackTrace(e));
    }
}

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

@Override
public void subscribe() {
    try {//from  w ww  .j a v a2s .  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.logicblaze.lingo.jmx.remote.jms.MBeanJmsServerConnectionClient.java

/**
 * Construct this thing//from w w w.  ja va  2  s  .  c o  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:org.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

private void createQueueOnBroker(Session session, Destination destination) throws JMSException {
    session.createConsumer(destination).close(); // Create a consumer only to cause queue creation
}

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 w w  w . j a v  a2  s  .  co 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:io.fabric8.msg.gateway.TestGateway.java

/**
 * TODO - lets figure out a way of mocking kubernetes, running a ZK ensemble, an Artemis broker and testing it!
 * @throws Exception//from   ww w . java  2 s  .com
 */
@Ignore
public void simpleTest() throws Exception {
    int numberOfMessages = 10;
    String destinationName = "jms.queue.test.foo";
    String brokerURL = "tcp://0.0.0.0:61616";
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);

    Connection consumerConnection = factory.createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination consumerDestination = consumerSession.createQueue(destinationName);
    MessageConsumer messageConsumer = consumerSession.createConsumer(consumerDestination);

    Connection producerConnection = factory.createConnection();
    producerConnection.start();
    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = producerSession.createQueue(destinationName);
    MessageProducer producer = producerSession.createProducer(destination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = producerSession.createTextMessage("test message: " + i);
        producer.send(message);
        //System.err.println("Sent message " + message);

    }

    Message message;

    for (int i = 0; i < numberOfMessages; i++) {
        message = messageConsumer.receive(5000);
        Assert.assertNotNull(message);
        //System.err.println("Got Message " + message);

    }
    messageConsumer.close();

}

From source file:org.apache.falcon.messaging.ProcessProducerTest.java

private void consumer() throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();/*from   www. j a va  2s . c  o m*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(getTopicName());
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();

    for (int index = 0; index < outputFeedNames.length; ++index) {
        MapMessage m = (MapMessage) consumer.receive();
        System.out.println("Consumed: " + m.toString());
        assertMessage(m);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_NAMES.getName()),
                outputFeedNames[index]);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName()),
                outputFeedPaths[index]);
    }
    connection.close();
}

From source file:org.fusesource.mq.itests.MQDistroTest.java

@Test
public void testWebConsoleAndClient() throws Exception {
    // send message via webconsole, consume from jms openwire
    HttpClient client = new HttpClient();

    // set credentials
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD));

    // need to first get the secret
    GetMethod get = new GetMethod(WEB_CONSOLE_URL + "send.jsp");
    get.setDoAuthentication(true);/*from   ww  w.j a  v a  2  s .  c o  m*/

    // Give console some time to start
    for (int i = 0; i < 20; i++) {
        Thread.currentThread().sleep(1000);
        try {
            i = client.executeMethod(get);
        } catch (java.net.ConnectException ignored) {
        }
    }
    assertEquals("get succeeded on " + get, 200, get.getStatusCode());

    String response = get.getResponseBodyAsString();
    final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\"";
    String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length());
    secret = secret.substring(0, secret.indexOf("\"/>"));

    final String destination = "validate.console.send";
    final String content = "Hi for the " + Math.random() + "' time";

    PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action");
    post.setDoAuthentication(true);
    post.addParameter("secret", secret);

    post.addParameter("JMSText", content);
    post.addParameter("JMSDestination", destination);
    post.addParameter("JMSDestinationType", "queue");

    // execute the send
    assertEquals("post succeeded, " + post, 302, client.executeMethod(post));

    // consume what we sent
    ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory()
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connection.start();
    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TextMessage textMessage = (TextMessage) session.createConsumer(new ActiveMQQueue(destination))
                .receive(10 * 1000);
        assertNotNull("got a message", textMessage);
        assertEquals("it is ours", content, textMessage.getText());
    } finally {
        connection.close();
    }

    // verify osgi registration of cf
    ConnectionFactory connectionFactory = getOsgiService(ConnectionFactory.class);
    assertTrue(connectionFactory instanceof ActiveMQConnectionFactory);
    ActiveMQConnection connectionFromOsgiFactory = (ActiveMQConnection) connectionFactory
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connectionFromOsgiFactory.start();
    try {
        assertEquals("same broker", connection.getBrokerName(), connectionFromOsgiFactory.getBrokerName());
    } finally {
        connectionFromOsgiFactory.close();
    }

    // verify mq-client
    Process process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar producer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("producer worked, exit(0)?", 0, process.exitValue());

    process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar consumer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("consumer worked, exit(0)?", 0, process.exitValue());

    System.out.println(executeCommand("activemq:bstat"));
}