Example usage for javax.jms Session commit

List of usage examples for javax.jms Session commit

Introduction

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

Prototype


void commit() throws JMSException;

Source Link

Document

Commits all messages done in this transaction and releases any locks currently held.

Usage

From source file:org.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java

/**
 * {@inheritDoc}/*from ww w .  j  a v a 2 s  .c o m*/
 * 
 */
@Override
public String[] executeInternal(final TaskExecutionEnv env, final SendType config,
        final Map<String, Properties> idPropertyMap)
        throws TaskExecutionException, BlackboardAccessException, RecordFilterNotFoundException {
    Connection connection = null;
    Session session = null;
    try {
        // get cached connection, if do not cache connections -> socket error when many records pushed
        connection = env.getServices().getBrokerConnections().getConnection(config, true);
        connection.start();
        session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        final Destination destination = session.createQueue(config.getQueue());
        final MessageProducer producer = session.createProducer(destination);
        if (config.isPersistentDelivery()) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        final Iterator<Entry<String, Properties>> entries = idPropertyMap.entrySet().iterator();
        while (entries.hasNext()) {
            final Entry<String, Properties> entry = entries.next();
            // get message record, optionally a filtered copy.
            final Record record = createMessageRecord(entry.getKey(), config, env);
            // prepare queue message. messages are actually sent on session.commit() below.
            producer.send(createMessage(config, record, entry.getValue(), session));
        }

        // we must commit here so that the message consumer find the correct record version in storages.
        env.getBlackboard().commit();
        env.setCommitRequired(false);
        // finally send the messages.
        session.commit();

        return idPropertyMap.keySet().toArray(new String[idPropertyMap.size()]);
    } catch (final Throwable e) {
        _log.error(msg("Error"), e);
        rollbackQuietly(session);
        throw new TaskExecutionException(e);
    } finally {
        closeQuietly(session);
        closeQuietly(connection);
    }
}

From source file:org.jboss.processFlow.knowledgeService.AsyncBAMProducerPool.java

public void passivateObject(Object obj) throws Exception {
    //log.info("passivateObject() ");
    Session pSession = ((BAMProducerWrapper) obj).getSession();
    pSession.commit();
}

From source file:org.mule.modules.jmsbatchmessaging.JmsBatchMessagingConnector.java

/**
 * Complete the batch operation and release all resources (including closing any open transactions.)
 * <p/>/*from w  w  w. j ava2s . co  m*/
 * {@sample.xml ../../../doc/jms-batch-messaging-connector.xml.sample
 * jms-batch-messaging:complete}
 *
 * @param muleMessage the current MuleMessage
 * @throws Exception
 */
@Processor
@Inject
public void complete(MuleMessage muleMessage) throws Exception {
    Session session = muleMessage.getInboundProperty("session");
    MessageConsumer consumer = muleMessage.getInboundProperty("consumer");

    Boolean isTransactional = muleMessage.getInboundProperty("transactional");

    if (isTransactional) {
        session.commit();
    }
    session.close();
    consumer.close();
}

From source file:org.springframework.jms.connection.JmsResourceHolder.java

public void commitAll() throws JMSException {
    for (Session session : this.sessions) {
        try {/*from  ww w. j  av  a  2s .  com*/
            session.commit();
        } catch (TransactionInProgressException ex) {
            // Ignore -> can only happen in case of a JTA transaction.
        } catch (javax.jms.IllegalStateException ex) {
            if (this.connectionFactory != null) {
                try {
                    Method getDataSourceMethod = this.connectionFactory.getClass().getMethod("getDataSource");
                    Object ds = ReflectionUtils.invokeMethod(getDataSourceMethod, this.connectionFactory);
                    while (ds != null) {
                        if (TransactionSynchronizationManager.hasResource(ds)) {
                            // IllegalStateException from sharing the underlying JDBC Connection
                            // which typically gets committed first, e.g. with Oracle AQ --> ignore
                            return;
                        }
                        try {
                            // Check for decorated DataSource a la Spring's DelegatingDataSource
                            Method getTargetDataSourceMethod = ds.getClass().getMethod("getTargetDataSource");
                            ds = ReflectionUtils.invokeMethod(getTargetDataSourceMethod, ds);
                        } catch (NoSuchMethodException nsme) {
                            ds = null;
                        }
                    }
                } catch (Throwable ex2) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("No working getDataSource method found on ConnectionFactory: " + ex2);
                    }
                    // No working getDataSource method - cannot perform DataSource transaction check
                }
            }
            throw ex;
        }
    }
}

From source file:org.springframework.jms.core.JmsTemplate.java

protected void doSend(Session session, Destination destination, MessageCreator messageCreator)
        throws JMSException {
    MessageProducer producer = createProducer(session, destination);
    Message message = messageCreator.createMessage(session);
    if (logger.isDebugEnabled()) {
        logger.debug("Sending created message [" + message + "]");
    }/*from  w  w w  .  j av a2  s. com*/
    doSend(producer, message);
    if (session.getTransacted() && !TransactionSynchronizationManager.hasResource(getConnectionFactory())) {
        // transacted session created by this template -> commit
        session.commit();
    }
}

From source file:org.springframework.jms.core.JmsTemplate.java

protected Message doReceive(Session session, Destination destination) throws JMSException {
    MessageConsumer consumer = createConsumer(session, destination);
    try {//from www . j  av  a2s .c  o m
        // use transaction timeout if available
        long timeout = getReceiveTimeout();
        ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager
                .getResource(getConnectionFactory());
        if (conHolder != null && conHolder.hasTimeout()) {
            timeout = conHolder.getTimeToLiveInMillis();
        }
        Message message = (timeout >= 0) ? consumer.receive(timeout) : consumer.receive();
        if (session.getTransacted()) {
            if (conHolder == null) {
                // transacted session created by this template -> commit
                session.commit();
            }
        } else if (message != null && isClientAcknowledge(session)) {
            message.acknowledge();
        }
        return message;
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
    }
}

From source file:org.springframework.jms.support.JmsUtils.java

/**
 * Commit the Session if not within a JTA transaction.
 * @param session the JMS Session to commit
 * @throws JMSException if committing failed
 *//*from ww  w .j a  v  a 2s. c o  m*/
public static void commitIfNecessary(Session session) throws JMSException {
    Assert.notNull(session, "Session must not be null");
    try {
        session.commit();
    } catch (javax.jms.TransactionInProgressException ex) {
        // Ignore -> can only happen in case of a JTA transaction.
    } catch (javax.jms.IllegalStateException ex) {
        // Ignore -> can only happen in case of a JTA transaction.
    }
}

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

/**
 * Create and start an asynchrounous publisher that will send MAX_QUEUE_MESSAGE_COUNT
 * messages to the provided destination. Messages are sent in a new connection
 * on a transaction. Any error is captured and the test is signalled to exit.
 *
 * @param destination// ww  w  . ja v a 2s  .  c o  m
 */
private void startPublisher(final Destination destination) {
    _publisher = new Thread(new Runnable() {

        public void run() {
            try {
                Connection connection = getConnection();
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

                MessageProducer publisher = session.createProducer(destination);

                for (int count = 0; count < MAX_QUEUE_MESSAGE_COUNT; count++) {
                    publisher.send(createNextMessage(session, count));
                    session.commit();
                }
            } catch (Exception e) {
                _publisherError = e;
                _disconnectionLatch.countDown();
            }
        }
    });

    _publisher.start();
}

From source file:org.wso2.carbon.event.output.adapter.jms.internal.util.JMSMessageSender.java

/**
 * Perform actual send of JMS message to the Destination selected
 */// w  w w .  ja  v  a2s  . co  m
public void send(Object message, JMSEventAdapter.PublisherDetails publisherDetails, String jmsHeaders) {

    Map<String, String> messageProperties = publisherDetails.getMessageConfig();

    Boolean jtaCommit = getBooleanProperty(messageProperties, BaseConstants.JTA_COMMIT_AFTER_SEND);
    Boolean rollbackOnly = getBooleanProperty(messageProperties, BaseConstants.SET_ROLLBACK_ONLY);
    Boolean persistent = getBooleanProperty(messageProperties, JMSConstants.JMS_DELIVERY_MODE);
    Integer priority = getIntegerProperty(messageProperties, JMSConstants.JMS_PRIORITY);
    Integer timeToLive = getIntegerProperty(messageProperties, JMSConstants.JMS_TIME_TO_LIVE);

    MessageProducer producer = null;
    Destination destination = null;
    Session session = null;
    boolean sendingSuccessful = false;
    JMSConnectionFactory.JMSPooledConnectionHolder pooledConnection = null;
    try {

        pooledConnection = jmsConnectionFactory.getConnectionFromPool();

        producer = pooledConnection.getProducer();
        session = pooledConnection.getSession();
        Message jmsMessage = convertToJMSMessage(message, publisherDetails.getMessageConfig(), session);
        setJMSTransportHeaders(jmsMessage, jmsHeaders);

        // Do not commit, if message is marked for rollback
        if (rollbackOnly != null && rollbackOnly) {
            jtaCommit = Boolean.FALSE;
        }

        if (persistent != null) {
            try {
                producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            } catch (JMSException e) {
                handleConnectionException("Error setting JMS Producer for PERSISTENT delivery", e);
            }
        }
        if (priority != null) {
            try {
                producer.setPriority(priority);
            } catch (JMSException e) {
                handleConnectionException("Error setting JMS Producer priority to : " + priority, e);
            }
        }
        if (timeToLive != null) {
            try {
                producer.setTimeToLive(timeToLive);
            } catch (JMSException e) {
                handleConnectionException("Error setting JMS Producer TTL to : " + timeToLive, e);
            }
        }

        // perform actual message sending
        //        try {
        if (jmsSpec11 || isQueue == null) {
            producer.send(jmsMessage);

        } else {
            if (isQueue) {
                ((QueueSender) producer).send(jmsMessage);

            } else {
                ((TopicPublisher) producer).publish(jmsMessage);
            }
        }
        sendingSuccessful = true;

        if (log.isDebugEnabled()) {

            //            // set the actual MessageID to the message context for use by any others down the line
            String msgId = null;
            try {
                msgId = jmsMessage.getJMSMessageID();
            } catch (JMSException jmse) {
                log.error(jmse.getMessage(), jmse);
            }

            log.debug(" with JMS Message ID : " + msgId + " to destination : " + producer.getDestination());
        }

    } catch (JMSException e) {
        handleConnectionException("Error sending message to destination : " + destination, e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        if (jtaCommit != null) {

            try {
                if (session.getTransacted()) {
                    if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) {
                        session.commit();
                    } else {
                        session.rollback();
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug((sendingSuccessful ? "Committed" : "Rolled back")
                            + " local (JMS Session) Transaction");
                }

            } catch (Exception e) {
                handleConnectionException("Error committing/rolling back local (i.e. session) "
                        + "transaction after sending of message "//with MessageContext ID : " +
                        + " to destination : " + destination, e);
            }
        }
        if (pooledConnection != null) {
            jmsConnectionFactory.returnPooledConnection(pooledConnection);
        }
    }
}

From source file:tools.ConsumerTool.java

public void handleMessage(Session session, Message message, int perConsumerReceivedMessages) {
    try {/*from w w w .j  a  v a  2 s  . c  o  m*/
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText();
            LOGGER.info("Received text message: " + text);
        } else {
            LOGGER.info("Received message: " + message);
        }
        if (perMessageSleepMS > 0) {
            try {
                Thread.sleep(perMessageSleepMS);
            } catch (InterruptedException e) {
                LOGGER.debug("Interrupted while sleeping", e);
            }
        }
        if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
            if (perConsumerReceivedMessages % batchSize == 0) {
                message.acknowledge();
            }
        }
        if (transacted) {
            if (perConsumerReceivedMessages % batchSize == 0) {
                session.commit();
            }
        }
    } catch (JMSException e) {
        LOGGER.error("JMSException handling message: " + e.getMessage(), e);
    }
}