Example usage for javax.jms Session close

List of usage examples for javax.jms Session close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the session.

Usage

From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.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 the JNDI context 
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("topic.TOPIC", "BasicTopic");
    hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1");
    hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2");
    hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3");
    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 the topic
    Destination topic = (Destination) context.lookup("TOPIC");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side seperately with minimal clutter
    {//from w ww. j  a  v a 2  s. c  om
        // 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 producer
        MessageProducer producer = session.createProducer(topic);

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

    // Look up the subscription (pretending it's a queue)
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3");

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

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
    {/*from  www.j ava2s  .  com*/
        // 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:com.adaptris.core.jms.MetadataCorrelationIdSourceTest.java

public void testAdaptrisMessageMetadataToJmsCorrelationId_NoMetadataKey() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    JmsConnection conn = broker.getJmsConnection();
    try {//from  w  ww .j av  a  2 s .  c o  m
        broker.start();
        start(conn);
        Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        AdaptrisMessage adpMsg = AdaptrisMessageFactory.getDefaultInstance().newMessage(TEXT);
        adpMsg.addMetadata(CORRELATIONID_KEY, TEXT2);
        TextMessage jmsMsg = session.createTextMessage();
        MetadataCorrelationIdSource mcs = new MetadataCorrelationIdSource();
        mcs.processCorrelationId(adpMsg, jmsMsg);
        assertNotSame(adpMsg.getMetadataValue(CORRELATIONID_KEY), jmsMsg.getJMSCorrelationID());
        session.close();
    } finally {
        stop(conn);
        broker.destroy();
    }
}

From source file:eu.domibus.submission.jms.BackendJMSImpl.java

/**
 * This method checks for pending messages received by another gateway and processes them to a JMS destination
 *
 * @param ctx// w  w w  . jav a2s .co  m
 */
public void executeInternal(final JobExecutionContext ctx) {
    try {

        final Collection<String> ids = this.messageRetriever.listPendingMessages();

        if (!ids.isEmpty() || ids.size() > 0) {
            final String[] messageIds = ids.toArray(new String[ids.size()]);

            Connection connection;
            MessageProducer producer;

            connection = this.cf.createConnection();
            for (final String messageId : messageIds) {
                final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                producer = session.createProducer(this.receivingQueue);
                producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                final MapMessage resMessage = session.createMapMessage();
                this.downloadMessage(messageId, resMessage);
                producer.send(resMessage);
                producer.close();
                session.close();
            }
            connection.close();
        } else {
            BackendJMSImpl.LOG.debug("No pending messages to send");
        }

    } catch (final JMSException | ValidationException ex) {
        BackendJMSImpl.LOG.error(ex);
    }
}

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

public void testAdaptrisMessageMetadataToJmsCorrelationId() throws Exception {

    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    JmsConnection conn = broker.getJmsConnection();
    try {//w  ww.  j av a2  s .c  om
        broker.start();
        start(conn);
        Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        AdaptrisMessage adpMsg = AdaptrisMessageFactory.getDefaultInstance().newMessage(TEXT);
        adpMsg.addMetadata(CORRELATIONID_KEY, TEXT2);
        TextMessage jmsMsg = session.createTextMessage();
        MetadataCorrelationIdSource mcs = new MetadataCorrelationIdSource(CORRELATIONID_KEY);
        mcs.processCorrelationId(adpMsg, jmsMsg);
        assertEquals(adpMsg.getMetadataValue(CORRELATIONID_KEY), jmsMsg.getJMSCorrelationID());
        session.close();
    } finally {
        stop(conn);
        broker.destroy();
    }
}

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

public void testJmsCorrelationIdToAdaptrisMessageMetadata() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    JmsConnection conn = broker.getJmsConnection();
    try {/*from ww w.  j  ava2 s.c  o m*/
        broker.start();
        start(conn);
        Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        AdaptrisMessage adpMsg = AdaptrisMessageFactory.getDefaultInstance().newMessage(TEXT);
        TextMessage jmsMsg = session.createTextMessage();
        jmsMsg.setJMSCorrelationID(TEXT2);
        MetadataCorrelationIdSource mcs = new MetadataCorrelationIdSource(CORRELATIONID_KEY);
        mcs.processCorrelationId(jmsMsg, adpMsg);
        assertEquals("Check Correlation Id Keys", jmsMsg.getJMSCorrelationID(),
                adpMsg.getMetadataValue(CORRELATIONID_KEY));
        session.close();
    } finally {
        stop(conn);
        broker.destroy();
    }
}

From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Comsume messages. */
protected void consumeMessages(Connection connection, Session session, MessageConsumer consumer, long timeout)
        throws JMSException, IOException {
    Message message;//from   w w w  .j  a  v  a  2s  .c  om
    while (!this.receiver.getNoMoreMessagesFlag()) {
        while ((message = consumer.receive(timeout)) != null) {
            onMessageOptimistic(message);
        }
    }
    consumer.close();
    session.close();
    connection.close();
}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * This method creates a connection to the message broker Active MQ and
 * sends the message to the given topic. The method is used by all methods
 * of the second component./*w  ww  . j  av  a  2s .  com*/
 * 
 * @param message
 *            send to the output device
 * @param topic
 *            of the message broker
 */
public static void sendMessage(String message, String topic) {
    String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

    // Create a Connection
    Connection connection;
    try {
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic(topic);
        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        // Create a messages
        TextMessage message1 = session.createTextMessage(message);
        // Tell the producer to send the message
        producer.send(message1);
        session.close();
        connection.close();
    } catch (JMSException e) {
        logger.error("Message could not be sended to activemq", e);
    }

}

From source file:de.klemp.middleware.controller.Controller.java

public static void sendMessageFast(String message, String topic) {
    String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

    // Create a Connection
    Connection connection;//from w ww  . j  a  v  a 2 s . co  m
    try {
        connectionFactory.setOptimizeAcknowledge(true);
        connectionFactory.setUseAsyncSend(true);
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic(topic);
        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        // Create a messages
        TextMessage message1 = session.createTextMessage(message);
        // Tell the producer to send the message
        producer.send(message1);
        session.close();
        connection.close();
    } catch (JMSException e) {
        logger.error("Message could not be sended to activemq", e);
    }

}

From source file:com.datatorrent.lib.io.jms.JMSStringInputOperatorTest.java

private void produceMsg(int numMessages) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();//from  w  w w .  j a va  2s .  c o  m

    // Create a Session
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

    // Create the destination (Topic or Queue)
    Destination destination = session.createQueue("TEST.FOO");

    // Create a MessageProducer from the Session to the Topic or Queue
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    // Create a messages
    String text = "Hello world! From tester producer";
    TextMessage message = session.createTextMessage(text);
    for (int i = 0; i < numMessages; i++) {
        producer.send(message);
    }

    // Clean up
    session.close();
    connection.close();

}