Example usage for javax.jms Connection createSession

List of usage examples for javax.jms Connection createSession

Introduction

In this page you can find the example usage for javax.jms Connection createSession.

Prototype


Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;

Source Link

Document

Creates a Session object, specifying transacted and acknowledgeMode .

Usage

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

/**
 * This method is called when a message was received at the incoming queue
 *
 * @param message The incoming JMS Message
 *//*from www  . j a  va2 s  .c  o m*/
@Override
public void onMessage(final Message message) {
    final MapMessage map = (MapMessage) message;
    try {
        final Connection con = this.cf.createConnection();
        final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MapMessage res = session.createMapMessage();
        try {
            final String messageID = this.submit(map);
            res.setStringProperty("messageId", messageID);
        } catch (final TransformationException | ValidationException e) {
            BackendJMSImpl.LOG.error("Exception occurred: ", e);
            res.setString("ErrorMessage", e.getMessage());
        }

        res.setJMSCorrelationID(map.getJMSCorrelationID());
        final MessageProducer sender = session.createProducer(this.outQueue);
        sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        sender.send(res);
        sender.close();
        session.close();
        con.close();

    } catch (final JMSException ex) {
        BackendJMSImpl.LOG.error("Error while sending response to queue", ex);

    }
}

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   ww w  .  j a va 2  s. c o m*/
        // 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:org.mule.transport.jms.Jms11Support.java

public Session createSession(Connection connection, boolean topic, boolean transacted, int ackMode,
        boolean noLocal) throws JMSException {
    return connection.createSession(transacted, (transacted ? Session.SESSION_TRANSACTED : ackMode));
}

From source file:fr.xebia.springframework.jms.support.converter.JaxbMessageConverterTest.java

@Before
public void before() throws Exception {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
            "vm://localhost?broker.persistent=false&broker.useJmx=false");
    Connection connection = connectionFactory.createConnection();
    connection.start();/*  w w  w  .j a  va  2s . c  om*/
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

}

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

@Override
public Session createSession(Connection c, boolean transacted, int acknowledgeMode) throws JMSException {
    Session s = c.createSession(transacted, acknowledgeMode);
    applyVendorSessionProperties(s);//w  w w.j  av a  2 s. c  o m
    return s;
}

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   www  .jav  a  2 s  . c  o m*/
        // 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:org.sakaiproject.kernel.messaging.email.EmailMessagingService.java

private void createSessions() {
    int sessionsPerConnection = 1;
    Session sess = null;//from   w  w  w .j  a  v a  2  s  . c o m
    for (Connection conn : connections) {
        for (int i = 0; i < sessionsPerConnection; ++i) {
            sess = null;
            try {
                sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                sessions.put(conn.getClientID(), sess);
            } catch (JMSException e) {
                try {
                    LOG.error("Fail to create connection[" + i + "]: " + conn.getClientID());
                } catch (JMSException e1) {
                    // TMI
                }
                e.printStackTrace();
            }
        }
    }

}

From source file:org.apache.camel.component.sjms.producer.InOutProducer.java

@Override
public MessageProducerResources doCreateProducerModel() throws Exception {
    MessageProducerResources answer;//from ww w.j  a v  a 2 s.co  m
    Connection conn = getConnectionResource().borrowConnection();
    try {
        Session session = conn.createSession(isEndpointTransacted(), getAcknowledgeMode());
        Destination destination = getEndpoint().getDestinationCreationStrategy().createDestination(session,
                getDestinationName(), isTopic());
        MessageProducer messageProducer = JmsObjectFactory.createMessageProducer(session, destination,
                isPersistent(), getTtl());

        answer = new MessageProducerResources(session, messageProducer);

    } catch (Exception e) {
        log.error("Unable to create the MessageProducer", e);
        throw e;
    } finally {
        getConnectionResource().returnConnection(conn);
    }

    return answer;
}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testQueueBrowserWith2Consumers() throws Exception {
    final int numMessages = 1000;
    //        connection.setAlwaysSyncSend(false);
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10");
    ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1");
    connection.start();// w ww  .  j  a  v a 2  s  .c o  m

    Connection connection2 = factory.createConnection(userName, password);
    connection2.start();
    connections.add(connection2);
    Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destinationPrefetch10);

    for (int i = 0; i < numMessages; i++) {
        TextMessage message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }

    QueueBrowser browser = session2.createBrowser(destinationPrefetch1);
    Enumeration<Message> browserView = browser.getEnumeration();

    List<Message> messages = new ArrayList<Message>();
    for (int i = 0; i < numMessages; i++) {
        Message m1 = consumer.receive(5000);
        assertNotNull("m1 is null for index: " + i, m1);
        messages.add(m1);
    }

    int i = 0;
    for (; i < numMessages && browserView.hasMoreElements(); i++) {
        Message m1 = messages.get(i);
        Message m2 = browserView.nextElement();
        assertNotNull("m2 is null for index: " + i, m2);
        assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID());
    }

    // currently browse max page size is ignored for a queue browser consumer
    // only guarantee is a page size - but a snapshot of pagedinpending is
    // used so it is most likely more
    assertTrue("got at least our expected minimum in the browser: ", i > 200);

    assertFalse("nothing left in the browser", browserView.hasMoreElements());
    assertNull("consumer finished", consumer.receiveNoWait());
}

From source file:org.wso2.andes.systest.TestingBaseCase.java

/**
 * Perform the Main test of a topic Consumer with the given AckMode.
 *
 * Test creates a new connection and sets up the connection to prevent
 * failover/*from   w  w  w.ja v  a 2s.c  o m*/
 *
 * A new consumer is connected and started so that it will prefetch msgs.
 *
 * An asynchrounous publisher is started to fill the broker with messages.
 *
 * We then wait to be notified of the disconnection via the ExceptionListener
 *
 * 0-10 does not have the same notification paths but sync() apparently should
 * give us the exception, currently it doesn't, so the test is excluded from 0-10
 *
 * We should ensure that this test has the same path for all protocol versions.
 *
 * Clients should not have to modify their code based on the protocol in use.
 *
 * @param ackMode @see javax.jms.Session
 *
 * @throws Exception
 */
protected void topicConsumer(int ackMode, boolean durable) throws Exception {
    Connection connection = getConnection();

    connection.setExceptionListener(this);

    Session session = connection.createSession(ackMode == Session.SESSION_TRANSACTED, ackMode);

    _destination = session.createTopic(getName());

    MessageConsumer consumer;

    if (durable) {
        consumer = session.createDurableSubscriber(_destination, getTestQueueName());
    } else {
        consumer = session.createConsumer(_destination);
    }

    connection.start();

    // Start the consumer pre-fetching
    // Don't care about response as we will fill the broker up with messages
    // after this point and ensure that the client is disconnected at the
    // right point.
    consumer.receiveNoWait();
    startPublisher(_destination);

    boolean disconnected = _disconnectionLatch.await(DISCONNECTION_WAIT, TimeUnit.SECONDS);

    assertTrue("Client was not disconnected", disconnected);
    assertTrue("Client was not disconnected.", _connectionException != null);

    Exception linked = _connectionException.getLinkedException();

    _publisher.join(JOIN_WAIT);

    assertFalse("Publisher still running", _publisher.isAlive());

    //Validate publishing occurred ok
    if (_publisherError != null) {
        throw _publisherError;
    }

    // NOTE these exceptions will need to be modeled so that they are not
    // 0-8 specific. e.g. JMSSessionClosedException

    assertNotNull("No error received onException listener.", _connectionException);

    assertNotNull("No linked exception set on:" + _connectionException.getMessage(), linked);

    assertTrue("Incorrect linked exception received.", linked instanceof AMQException);

    AMQException amqException = (AMQException) linked;

    assertEquals("Channel was not closed with correct code.", AMQConstant.RESOURCE_ERROR,
            amqException.getErrorCode());
}