Search in sources :

Example 11 with Connection

use of javax.jms.Connection in project spring-framework by spring-projects.

the class AbstractMessageListenerContainer method doInvokeListener.

/**
	 * Invoke the specified listener as Spring SessionAwareMessageListener,
	 * exposing a new JMS Session (potentially with its own transaction)
	 * to the listener if demanded.
	 * @param listener the Spring SessionAwareMessageListener to invoke
	 * @param session the JMS Session to operate on
	 * @param message the received JMS Message
	 * @throws JMSException if thrown by JMS API methods
	 * @see SessionAwareMessageListener
	 * @see #setExposeListenerSession
	 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void doInvokeListener(SessionAwareMessageListener listener, Session session, Message message) throws JMSException {
    Connection conToClose = null;
    Session sessionToClose = null;
    try {
        Session sessionToUse = session;
        if (!isExposeListenerSession()) {
            // We need to expose a separate Session.
            conToClose = createConnection();
            sessionToClose = createSession(conToClose);
            sessionToUse = sessionToClose;
        }
        // Actually invoke the message listener...
        listener.onMessage(message, sessionToUse);
        // Clean up specially exposed Session, if any.
        if (sessionToUse != session) {
            if (sessionToUse.getTransacted() && isSessionLocallyTransacted(sessionToUse)) {
                // Transacted session created by this container -> commit.
                JmsUtils.commitIfNecessary(sessionToUse);
            }
        }
    } finally {
        JmsUtils.closeSession(sessionToClose);
        JmsUtils.closeConnection(conToClose);
    }
}
Also used : Connection(javax.jms.Connection) Session(javax.jms.Session)

Example 12 with Connection

use of javax.jms.Connection in project spring-framework by spring-projects.

the class DefaultMessageListenerContainer method refreshConnectionUntilSuccessful.

/**
	 * Refresh the underlying Connection, not returning before an attempt has been
	 * successful. Called in case of a shared Connection as well as without shared
	 * Connection, so either needs to operate on the shared Connection or on a
	 * temporary Connection that just gets established for validation purposes.
	 * <p>The default implementation retries until it successfully established a
	 * Connection, for as long as this message listener container is running.
	 * Applies the specified recovery interval between retries.
	 * @see #setRecoveryInterval
	 * @see #start()
	 * @see #stop()
	 */
protected void refreshConnectionUntilSuccessful() {
    BackOffExecution execution = this.backOff.start();
    while (isRunning()) {
        try {
            if (sharedConnectionEnabled()) {
                refreshSharedConnection();
            } else {
                Connection con = createConnection();
                JmsUtils.closeConnection(con);
            }
            logger.info("Successfully refreshed JMS Connection");
            break;
        } catch (Exception ex) {
            if (ex instanceof JMSException) {
                invokeExceptionListener((JMSException) ex);
            }
            StringBuilder msg = new StringBuilder();
            msg.append("Could not refresh JMS Connection for destination '");
            msg.append(getDestinationDescription()).append("' - retrying using ");
            msg.append(execution).append(". Cause: ");
            msg.append(ex instanceof JMSException ? JmsUtils.buildExceptionMessage((JMSException) ex) : ex.getMessage());
            if (logger.isDebugEnabled()) {
                logger.error(msg, ex);
            } else {
                logger.error(msg);
            }
        }
        if (!applyBackOffTime(execution)) {
            StringBuilder msg = new StringBuilder();
            msg.append("Stopping container for destination '").append(getDestinationDescription()).append("': back-off policy does not allow ").append("for further attempts.");
            logger.error(msg.toString());
            stop();
        }
    }
}
Also used : BackOffExecution(org.springframework.util.backoff.BackOffExecution) Connection(javax.jms.Connection) JMSException(javax.jms.JMSException) JmsException(org.springframework.jms.JmsException) JMSException(javax.jms.JMSException)

Example 13 with Connection

use of javax.jms.Connection in project spring-framework by spring-projects.

the class ConnectionFactoryUtils method doGetTransactionalSession.

/**
	 * Obtain a JMS Session that is synchronized with the current transaction, if any.
	 * @param connectionFactory the JMS ConnectionFactory to bind for
	 * (used as TransactionSynchronizationManager key)
	 * @param resourceFactory the ResourceFactory to use for extracting or creating
	 * JMS resources
	 * @param startConnection whether the underlying JMS Connection approach should be
	 * started in order to allow for receiving messages. Note that a reused Connection
	 * may already have been started before, even if this flag is {@code false}.
	 * @return the transactional Session, or {@code null} if none found
	 * @throws JMSException in case of JMS failure
	 */
public static Session doGetTransactionalSession(ConnectionFactory connectionFactory, ResourceFactory resourceFactory, boolean startConnection) throws JMSException {
    Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
    Assert.notNull(resourceFactory, "ResourceFactory must not be null");
    JmsResourceHolder resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager.getResource(connectionFactory);
    if (resourceHolder != null) {
        Session session = resourceFactory.getSession(resourceHolder);
        if (session != null) {
            if (startConnection) {
                Connection con = resourceFactory.getConnection(resourceHolder);
                if (con != null) {
                    con.start();
                }
            }
            return session;
        }
        if (resourceHolder.isFrozen()) {
            return null;
        }
    }
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        return null;
    }
    JmsResourceHolder resourceHolderToUse = resourceHolder;
    if (resourceHolderToUse == null) {
        resourceHolderToUse = new JmsResourceHolder(connectionFactory);
    }
    Connection con = resourceFactory.getConnection(resourceHolderToUse);
    Session session = null;
    try {
        boolean isExistingCon = (con != null);
        if (!isExistingCon) {
            con = resourceFactory.createConnection();
            resourceHolderToUse.addConnection(con);
        }
        session = resourceFactory.createSession(con);
        resourceHolderToUse.addSession(session, con);
        if (startConnection) {
            con.start();
        }
    } catch (JMSException ex) {
        if (session != null) {
            try {
                session.close();
            } catch (Throwable ex2) {
            // ignore
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (Throwable ex2) {
            // ignore
            }
        }
        throw ex;
    }
    if (resourceHolderToUse != resourceHolder) {
        TransactionSynchronizationManager.registerSynchronization(new JmsResourceSynchronization(resourceHolderToUse, connectionFactory, resourceFactory.isSynchedLocalTransactionAllowed()));
        resourceHolderToUse.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolderToUse);
    }
    return session;
}
Also used : Connection(javax.jms.Connection) TopicConnection(javax.jms.TopicConnection) QueueConnection(javax.jms.QueueConnection) JMSException(javax.jms.JMSException) QueueSession(javax.jms.QueueSession) Session(javax.jms.Session) TopicSession(javax.jms.TopicSession)

Example 14 with Connection

use of javax.jms.Connection in project spring-framework by spring-projects.

the class JmsTransactionManager method doBegin.

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        throw new InvalidIsolationLevelException("JMS does not support an isolation level concept");
    }
    JmsTransactionObject txObject = (JmsTransactionObject) transaction;
    Connection con = null;
    Session session = null;
    try {
        con = createConnection();
        session = createSession(con);
        if (logger.isDebugEnabled()) {
            logger.debug("Created JMS transaction on Session [" + session + "] from Connection [" + con + "]");
        }
        txObject.setResourceHolder(new JmsResourceHolder(getConnectionFactory(), con, session));
        txObject.getResourceHolder().setSynchronizedWithTransaction(true);
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getResourceHolder().setTimeoutInSeconds(timeout);
        }
        TransactionSynchronizationManager.bindResource(getConnectionFactory(), txObject.getResourceHolder());
    } catch (Throwable ex) {
        if (session != null) {
            try {
                session.close();
            } catch (Throwable ex2) {
            // ignore
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (Throwable ex2) {
            // ignore
            }
        }
        throw new CannotCreateTransactionException("Could not create JMS transaction", ex);
    }
}
Also used : CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) Connection(javax.jms.Connection) InvalidIsolationLevelException(org.springframework.transaction.InvalidIsolationLevelException) Session(javax.jms.Session)

Example 15 with Connection

use of javax.jms.Connection in project spring-framework by spring-projects.

the class SingleConnectionFactory method createTopicConnection.

@Override
public TopicConnection createTopicConnection() throws JMSException {
    Connection con;
    synchronized (this.connectionMonitor) {
        this.pubSubMode = Boolean.TRUE;
        con = createConnection();
    }
    if (!(con instanceof TopicConnection)) {
        throw new javax.jms.IllegalStateException("This SingleConnectionFactory does not hold a TopicConnection but rather: " + con);
    }
    return ((TopicConnection) con);
}
Also used : Connection(javax.jms.Connection) TopicConnection(javax.jms.TopicConnection) QueueConnection(javax.jms.QueueConnection) TopicConnection(javax.jms.TopicConnection)

Aggregations

Connection (javax.jms.Connection)124 Session (javax.jms.Session)88 Test (org.junit.Test)62 MessageProducer (javax.jms.MessageProducer)46 ConnectionFactory (javax.jms.ConnectionFactory)44 Message (javax.jms.Message)38 MessageConsumer (javax.jms.MessageConsumer)38 JMSException (javax.jms.JMSException)32 TextMessage (javax.jms.TextMessage)32 QueueConnection (javax.jms.QueueConnection)22 TopicConnection (javax.jms.TopicConnection)22 Destination (javax.jms.Destination)15 Queue (javax.jms.Queue)12 QueueConnectionFactory (javax.jms.QueueConnectionFactory)11 TopicConnectionFactory (javax.jms.TopicConnectionFactory)11 ActiveMQConnectionFactory (org.apache.activemq.ActiveMQConnectionFactory)7 JmsTemplate (org.springframework.jms.core.JmsTemplate)7 TransactionStatus (org.springframework.transaction.TransactionStatus)7 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)7 TransactionAttribute (javax.ejb.TransactionAttribute)4