Example usage for javax.jms Session SESSION_TRANSACTED

List of usage examples for javax.jms Session SESSION_TRANSACTED

Introduction

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

Prototype

int SESSION_TRANSACTED

To view the source code for javax.jms Session SESSION_TRANSACTED.

Click Source Link

Document

This value may be passed as the argument to the method createSession(int sessionMode) on the Connection object to specify that the session should use a local transaction.

Usage

From source file:org.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

public void testTransactedSessionWithUnackMessages() throws Exception {
    _connection = getConnection();/* w ww  . ja  v a2  s . c o m*/
    _connection.start();

    boolean transactional = true;
    int numberOfMessages = 2;
    final Session session = _connection.createSession(transactional, Session.SESSION_TRANSACTED);
    final Destination destination = session.createQueue(getTestQueueName());
    final MessageConsumer consumer = session.createConsumer(destination);

    sendMessage(session, destination, numberOfMessages);
    receiveMessagesWithoutCommit(consumer, numberOfMessages);

    final ManagedConnection mBean = getConnectionMBean();
    final CompositeDataSupport row = getTheOneChannelRow(mBean);
    boolean flowBlocked = false;
    assertChannelRowData(row, numberOfMessages, transactional, flowBlocked);

    // check that commit advances the lastIoTime
    final Date initialLastIOTime = mBean.getLastIoTime();
    session.commit();
    assertTrue("commit should have caused last IO time to advance",
            mBean.getLastIoTime().after(initialLastIOTime));

    // check that channels() now returns one session with no unacknowledged messages
    final CompositeDataSupport rowAfterCommit = getTheOneChannelRow(mBean);
    final Number unackCountAfterCommit = (Number) rowAfterCommit.get(ManagedConnection.UNACKED_COUNT);
    assertEquals("Unexpected number of unacknowledged messages", 0, unackCountAfterCommit);
}

From source file:org.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

public void testProducerFlowBlocked() throws Exception {
    _connection = getConnection();/*ww  w  . java2 s .c  o m*/
    _connection.start();

    String queueName = getTestQueueName();
    Session session = _connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(queueName);
    createQueueOnBroker(session, queue);

    ManagedQueue managedQueue = _jmxUtils.getManagedQueue(queueName);
    managedQueue.setFlowResumeCapacity(DEFAULT_MESSAGE_SIZE * 2l);
    managedQueue.setCapacity(DEFAULT_MESSAGE_SIZE * 3l);

    final ManagedConnection managedConnection = getConnectionMBean();

    // Check that producer flow is not block before test
    final CompositeDataSupport rowBeforeSend = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowBeforeSend, false);

    // Check that producer flow does not become block too soon
    sendMessage(session, queue, 3);
    final CompositeDataSupport rowBeforeFull = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowBeforeFull, false);

    // Fourth message will over-fill the queue (but as we are not sending more messages, client thread wont't block)
    sendMessage(session, queue, 1);
    final CompositeDataSupport rowAfterFull = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowAfterFull, true);

    // Consume two to bring the queue down to the resume capacity
    MessageConsumer consumer = session.createConsumer(queue);
    assertNotNull("Could not receive first message", consumer.receive(1000));
    assertNotNull("Could not receive second message", consumer.receive(1000));
    session.commit();

    // Check that producer flow is no longer blocked
    final CompositeDataSupport rowAfterReceive = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowAfterReceive, false);
}

From source file:org.apache.qpid.systest.management.jmx.QueueManagementTest.java

private void createConnectionAndSession() throws JMSException, NamingException {
    _connection = getConnection();/*from  w  w w . jav  a  2  s .c  o  m*/
    _connection.start();
    _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
}

From source file:org.apache.qpid.systest.rest.VirtualHostRestTest.java

public void testGetHost() throws Exception {
    // create AMQP connection to get connection JSON details
    _connection = (AMQConnection) getConnection();
    _connection.createSession(true, Session.SESSION_TRANSACTED);

    Map<String, Object> hostDetails = getRestTestHelper().getJsonAsSingletonList("/rest/virtualhost/test");
    Asserts.assertVirtualHost("test", hostDetails);

    @SuppressWarnings("unchecked")
    Map<String, Object> statistics = (Map<String, Object>) hostDetails.get(Asserts.STATISTICS_ATTRIBUTE);
    assertEquals("Unexpected number of exchanges in statistics", EXPECTED_EXCHANGES.length,
            statistics.get(VirtualHost.EXCHANGE_COUNT));
    assertEquals("Unexpected number of queues in statistics", EXPECTED_QUEUES.length,
            statistics.get(VirtualHost.QUEUE_COUNT));
    assertEquals("Unexpected number of connections in statistics", 1,
            statistics.get(VirtualHost.CONNECTION_COUNT));

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> exchanges = (List<Map<String, Object>>) hostDetails
            .get(VIRTUALHOST_EXCHANGES_ATTRIBUTE);
    assertEquals("Unexpected number of exchanges", EXPECTED_EXCHANGES.length, exchanges.size());
    Asserts.assertDurableExchange("amq.fanout", "fanout",
            getRestTestHelper().find(Exchange.NAME, "amq.fanout", exchanges));
    Asserts.assertDurableExchange("amq.topic", "topic",
            getRestTestHelper().find(Exchange.NAME, "amq.topic", exchanges));
    Asserts.assertDurableExchange("amq.direct", "direct",
            getRestTestHelper().find(Exchange.NAME, "amq.direct", exchanges));
    Asserts.assertDurableExchange("amq.match", "headers",
            getRestTestHelper().find(Exchange.NAME, "amq.match", exchanges));
    Asserts.assertDurableExchange("<<default>>", "direct",
            getRestTestHelper().find(Exchange.NAME, "<<default>>", exchanges));

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> queues = (List<Map<String, Object>>) hostDetails
            .get(VIRTUALHOST_QUEUES_ATTRIBUTE);
    assertEquals("Unexpected number of queues", EXPECTED_QUEUES.length, queues.size());
    Map<String, Object> queue = getRestTestHelper().find(Queue.NAME, "queue", queues);
    Map<String, Object> ping = getRestTestHelper().find(Queue.NAME, "ping", queues);
    Asserts.assertQueue("queue", "standard", queue);
    Asserts.assertQueue("ping", "standard", ping);
    assertEquals("Unexpected value of queue attribute " + Queue.DURABLE, Boolean.FALSE,
            queue.get(Queue.DURABLE));
    assertEquals("Unexpected value of queue attribute " + Queue.DURABLE, Boolean.FALSE,
            ping.get(Queue.DURABLE));

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> connections = (List<Map<String, Object>>) hostDetails
            .get(VIRTUALHOST_CONNECTIONS_ATTRIBUTE);
    assertEquals("Unexpected number of connections", 1, connections.size());
    Asserts.assertConnection(connections.get(0), _connection);
}

From source file:org.apache.servicemix.jms.jca.JcaConsumerProcessor.java

public void process(MessageExchange exchange) throws Exception {
    Context context = (Context) pendingMessages.remove(exchange.getExchangeId());
    Message message = (Message) context.getProperty(Message.class.getName());
    Message response = null;/*  ww w.  j a  va  2  s  .co m*/
    Connection connection = null;
    try {
        if (exchange.getStatus() == ExchangeStatus.DONE) {
            return;
        } else if (exchange.getStatus() == ExchangeStatus.ERROR) {
            if (endpoint.isRollbackOnError()) {
                TransactionManager tm = (TransactionManager) endpoint.getServiceUnit().getComponent()
                        .getComponentContext().getTransactionManager();
                tm.setRollbackOnly();
                return;
            } else if (exchange instanceof InOnly) {
                LOG.info("Exchange in error: " + exchange, exchange.getError());
                return;
            } else {
                connection = connectionFactory.createConnection();
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
                Exception error = exchange.getError();
                if (error == null) {
                    error = new Exception("Exchange in error");
                }
                response = session.createObjectMessage(error);
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        } else {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            response = fromNMSResponse(exchange, context, session);
            if (response != null) {
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
        if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    }
}

From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java

/**
 * Creates a new JMS Session./*from www  .  j  a va 2  s  .com*/
 *
 * @param connection The JMS Connection that must be used when creating the session.
 * @param mode Acknowledgement mode that must be used for this session.
 * @param isProducerSession Type of the session going to create
 * @return A JMS Session.
 * @throws JMSException
 */
public Session newSession(Connection connection, int mode, boolean isProducerSession) throws JMSException {
    if (connection == null) {
        logger.error(nameString() + " cannot create JMS Session. Invalid connection.");
        return null;
    }

    Session session;
    if (isVersion11) {
        if (isGuaranteedDeliveryEnable && isProducerSession) {
            session = connection.createSession(true, Session.SESSION_TRANSACTED);
        } else {
            session = connection.createSession(false, mode);
        }
    } else {
        if (isGuaranteedDeliveryEnable && isProducerSession) {
            session = ((QueueConnection) connection).createQueueSession(true, Session.SESSION_TRANSACTED);
        } else {
            session = ((QueueConnection) connection).createQueueSession(false, mode);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug(nameString() + ". Created JMS Session.");
    }
    return session;
}

From source file:org.eclipse.smila.connectivity.queue.AbstractBrokerPropertiesConfigImpl.java

/**
 * {@inheritDoc}/*from w  ww  .  ja  v  a 2s  . co m*/
 * 
 * @see org.eclipse.smila.connectivity.queue.ConnectivityBroker#start()
 */
public synchronized void start() throws BrokerException {
    Properties properties;
    try {
        properties = loadJMSProperties();
    } catch (final Exception e) {
        throw new BrokerException("Unable to load JMS properties", e);
    }
    Context ctx;
    try {
        ctx = new InitialContext(properties);
        System.setProperty(PROPERTY_DEFAULT_DIRECTORY_PREFIX,
                properties.getProperty(PROPERTY_DEFAULT_DIRECTORY_PREFIX));
        final ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
        _connection = factory.createConnection();
        _connection.start();
        _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
        _session.createQueue(DLQ);
    } catch (final Exception e) {
        throw new BrokerException("Error initializing Queue Broker with JMS properties resp. configuration", e);
    } finally {
        if (_session != null) {
            try {
                _session.commit();
            } catch (final JMSException e) {
                ;// nothing
            }
            try {
                _session.close();
            } catch (final JMSException e) {
                ;// nothing
            }
        }
    }
}

From source file:org.fusesource.jms.pool.XaConnectionPool.java

public Session createSession(boolean transacted, int ackMode) throws JMSException {
    PooledSession session = null;/*from  ww  w  .j av a  2  s . co  m*/
    try {
        boolean isXa = (transactionManager != null
                && transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION);
        if (isXa) {
            transacted = true;
            ackMode = Session.SESSION_TRANSACTED;
            session = (PooledSession) super.createXaSession(transacted, ackMode);
            session.setIgnoreClose(true);
            session.setIsXa(true);
            transactionManager.getTransaction().registerSynchronization(new Synchronization(session));
            incrementReferenceCount();
            transactionManager.getTransaction().enlistResource(createXaResource(session));
        } else {
            session = (PooledSession) super.createSession(transacted, ackMode);
            session.setIgnoreClose(false);
        }
        return session;
    } catch (RollbackException e) {
        final JMSException jmsException = new JMSException("Rollback Exception");
        jmsException.initCause(e);
        throw jmsException;
    } catch (SystemException e) {
        final JMSException jmsException = new JMSException("System Exception");
        jmsException.initCause(e);
        throw jmsException;
    }
}

From source file:org.jbpm.msg.jms.JmsMessageServiceFactoryImpl.java

public Service openService() {
    Connection connection = null;
    Session session = null;// w w w  .j ava 2s.c om

    try {
        connection = connectionFactory.createConnection();

        // If you use an XA connection factory in JBoss, the parameters will be ignored.  It will always take part in the global JTA transaction.
        // If you use a non XQ connection factory, the first parameter specifies whether you want to have all message productions and 
        // consumptions as part of one transaction (TRUE) or whether you want all productions and consumptions to be instantanious (FALSE)
        // Of course, we never want messages to be received before the current jbpm transaction commits so we just set it to true.
        session = connection.createSession(true, Session.SESSION_TRANSACTED);

    } catch (JMSException e) {
        throw new JbpmException("couldn't open jms message session", e);
    }

    return new JmsMessageServiceImpl(connection, session, destination, isCommitEnabled);
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Clear the specified topic/*from  w  w w . j a va2 s.co  m*/
 */
protected void purgeTopic(String destination, String topic) throws Exception {
    Connection c = null;
    Session s = null;

    try {
        logger.debug("purging topic : " + topic);
        c = getConnection(true, false);
        if (c == null) {
            logger.debug("could not create a connection to topic : " + destination);
        }

        c.start();
        s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED);

        logger.debug("created topic session");
        Topic dest = s.createTopic(destination);
        logger.debug("created topic destination");

        if (client != null) {
            client.dispose();
        }

        MessageConsumer consumer = null;

        try {
            consumer = s.createDurableSubscriber(dest, topic);
            logger.debug("created consumer");
            while (consumer.receiveNoWait() != null) {
                logger.debug("Topic " + topic + " isn't empty, draining it");
            }
            logger.debug("topic should be empty");
            consumer.close();
            s.unsubscribe(topic);
        } catch (JMSException e) {
            logger.debug("could not unsubscribe : " + topic);
        }
    }

    finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
    logger.debug("completed draining topic :" + topic);
}